Repository navigation
feat(decopilot): unified per-run projection workflow (consume step + hosted child harness) - #4179
Merged
Merged
Conversation
tlgimenes
force-pushed
the
eta-telescopii
branch
from
June 29, 2026 23:54
d8c4100 to
18718eb
Compare
Replaces the standalone durable projector (projector-consumer + start-durable-projector) with a single `consumeRunProjection` DBOS step inside the dispatch workflow — the sole terminal-status writer for both topologies. Adds the `hostedHarnessWorkflow` child + `HOSTED_HARNESS_QUEUE` and hoists the run-claim (fence mint) to the thread gate so the fence is in the DB before any harness code runs. Rebased onto #4183: keeps main's v3 wire contract, the `resolveHarnessExecutionSite` ("cluster" | "sandbox") gate, and the desktop-runtime removal. The gate now returns a hosted-enqueue descriptor (DBOS forbids startWorkflow inside a step) and no longer polls for terminal status; completion flows through the consume step. DBOS_WORKFLOW_VERSION bumped to "2" (gate step sequence changed: added consumeRunProjection, removed polling) and the workflow-source-guard snapshot re-baselined. Also gitignores packages/e2e Playwright artifacts. Squash of 23 WIP commits (Task 7a/7b); original history preserved on eta-telescopii-backup-prerebase. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ropped `runId === threadId`, so the run row (status) is shared across every turn of a thread. The consume step is the sole terminal-status writer and its entry guard returns early on a terminal status. The gate's `setRunFence` reset the per-turn fence + ack floor at turn-start but left `status` untouched, so a second turn inherited the prior turn's `completed`/`requires_action` status: its consume step short-circuited and the turn rendered "No response was generated" (with cross-turn contamination on the shared `runId` stream subject, since the dropped turn never drained/purged its stream). Reset `status` to `in_progress` atomically with the fence in `setRunFence` when claiming a turn (token non-null) — mirroring the per-turn `(runId, fenceToken)` message-id namespacing: a turn-stable runId needs an explicit per-turn re-arm. Clearing the fence (teardown) leaves status alone. Adds an e2e regression (`link-ingest.spec.ts`): two real dispatch+relay turns on one thread must both land their assistant text. The second turn's marker is the assertion — before this fix it was dropped by the stale terminal status. This closes the entry-guard gap the projection spec documented as having "no e2e-injectable surface". Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…s turns
The incremental checkpoint pass (`createRunPersistence({ terminal: false })`)
wired `emitFinal` to a no-op, relying on `emitStepParts` (fired by the AI SDK's
`onStepFinish`) to carry parts. But CLI harnesses (codex/claude-code) relay the
whole turn as ONE step, so `onStepFinish` never fires mid-turn — only `onFinish`
does, which calls `emitFinal`. Result: a long single-step turn persisted ZERO
assistant parts until the terminal `{done}`. Verified live — a 42-min Codex turn
streamed 2.7k chunks and 78 checkpoints yet held 0 parts in the DB until the end;
instrumenting the fold showed each checkpoint already had final parts assembled
(text `done`, tool `output-available`) that the no-op discarded.
Fix: in checkpoint mode, route `emitFinal` to `emitter.emitStepParts(message)` —
persist the message's FINAL parts but leave the finish anchor to the terminal
pass (the documented intent). Safe by construction: re-folds dedupe on the
deterministic part-row ids (`${runId}:${messageId}:${seq}` + ON CONFLICT DO
NOTHING), and the trailing in-flight part stays unpersisted until a later fold
finalizes it (no truncation). Helps decopilot's multi-step turns too.
Adds an e2e regression (`link-ingest.spec.ts`): relay a single-step stream
(text → `text-end`, NO `finish-step`) + a checkpoint WITHOUT a `{done}`, and
assert the part lands while the run is still in progress. Proven to fail on the
pre-fix no-op and pass with the fix. New `publishRelayManual` fixture gives the
test manual control over chunk / checkpoint / done ordering.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…tion Baseline for the message-id unification plan. Folds in the v3 consume-step projection tail and the approval-continuation snapshot fix (emitFinalSnapshot / replaceFinal). mesh tsc --noEmit is green at this commit. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…Id in all harnesses Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…erge in fold Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
… from originalMessages
…heckpoint + live ingest
…ssageId flow-through
…o duplicate message) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…rden Layer 2 gate) Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…n-id remap The first-message->proposal id remap is idempotent across re-folds only because a decopilot turn is a single UI message. Document the assumption and the guard to add before multi-message continuations become reachable (final-review note).
… source; revert natsChunkSource exhaustion hack Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
The shared-module test helpers (Tasks 1-6) passed `bun test` but tripped `noUncheckedIndexedAccess` under `tsc`: a write through out[i] and two indexed elements in a RawMsg[] literal. Build-then-push and non-null assertions; no behavior change. Surfaced by Task 7's workspace typecheck. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment-only sweep so the prose matches the single-id design: - project-chunks.ts: generateMessageId is the background-tool-only override (decopilot keeps the harness start.messageId verbatim), not a 'deterministic assistant-id generator'; originalMessages is seeded by BOTH persisting folds (terminal + checkpoint), not just the checkpoint workflow. - project-run.ts: the fence namespaces only the synthesized error id now. - run-persistence.ts / ingest-run.ts / project-run.ts: re-folds dedupe on STABLE part-row ids (harness id stable in the replayed chunk log), not server-'deterministic' ones.
…ment Resolves the Task 7 review note: onDone now fires on terminal close AND external cancel (the terminal close cancels the source via the pipeThrough chain), which is strictly more correct for the sole caller (idempotent sub.stop) and fixes a latent cancel-time subscription leak. Comment-only; no logic change. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…source decode Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…tore cleaned flag) Resolves the Task 8 review note: release() now wraps reader.releaseLock() in try/catch (it can throw per the WHATWG spec if cleanup fires from the abort handler mid-pull — the new reader-based wrapper introduced this; the original used iter.return() with no lock). Also restores the original's `cleaned` idempotency guard. Behavior-preserving in Bun; removes latent fragility. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
projectorChunkStream's two error exits (upstream-ended-without-done, and the gap-before-done finalSeq mismatch) released the reader lock but never cancelled it, so the cascade to natsChunkSource.onCancel (sub.stop) didn't fire — a projection error leaked the live JetStream subscription. Add await reader.cancel() before release() on both, mirroring the success exits. New test proves the cascade fires on the gap-before-done error via an infinite source (onCancel can only fire through the cascade, not natural exhaustion). Resolves the final-review follow-up. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The producer (publishChunk/publishRawChunk) and the batch reconstruction consumer (projector-run-log) each kept local copies of the Dp-Frag-Idx / Dp-Frag-Total header names, which would silently diverge from the shared nats-chunk-source decode if renamed. Import the exported constants instead. (projector-run-log's batch decode itself stays — its random-access seq Map + fragment-index reassembly is a different model from the streaming source.) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ions dispatch An approval/tool-output continuation re-POSTs the proposal's assistant message, so the old fence decision (reuse the fence whenever the message id is already persisted) handed the continuation the proposal's fence. Since the hosted-harness child workflow id is `decopilot-hosted:<runId>:<fenceToken>`, the continuation collided with the proposal's already-finished child and DBOS dedupe dropped the resume — the turn hung forever at requires_action. Key the fence reuse off gate-workflow existence (a genuine network redelivery) instead of message persistence. A fresh user message and an approval continuation each produce a NEW gate workflow id (distinct idempotency key), so each mints a fresh fence and dispatches its own harness child; only an identical re-POST collapses onto the in-flight fence. This restores the "fence is fresh per turn" invariant documented on mintRunFenceToken. Verified end-to-end on a local decopilot thread: proposal + continuation now run as two distinct hosted-harness workflows (distinct fences, both SUCCESS) and merge onto a single assistant message; reload renders one bubble. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ith checkpoint debounce Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…nt removal Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
… tests The 4 /checkpoint-* projector e2e stub routes returned hardcoded constants and their tests asserted those constants — vacuous scaffolding for the checkpoint machinery removed earlier in this branch. Keeps the 3 real projector e2e routes (crash-before-ack, dbos-recover, missing-chunk). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…s/harness Create `packages/harness/src/run-stream-codec.ts` as the single source of truth for the UIMessageChunk ⇄ JetStream wire format (serialize side): - `WireMessage`, `serializeChunk`, `serializeDone`, `serializeUnfencedDone` - msgId helpers: `buildChunkMsgId`, `buildDoneMsgId`, `parseRunStreamMsgId` - Subject helpers: `streamSubject`, `DECOPILOT_STREAM_SUBJECT_PREFIX` - Constants: `FRAG_INDEX_HEADER`, `FRAG_TOTAL_HEADER`, `MAX_CHUNKED_BYTES` Add `ai` to harness explicit dependencies (was phantom-transitive only). Re-export moved helpers from relay-publisher.ts and projector-stream-messages.ts so every existing importer compiles unchanged. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…h consumes it - Add RawMsg, DecodedEvent, concat, reassembleFragments, decodeMessage, decodeStream to run-stream-codec.ts (single authoritative definition) - FRAG_INDEX_HEADER / FRAG_TOTAL_HEADER are now defined only in the codec - nats-chunk-source.ts deletes moved defs; imports from codec and re-exports as forwarding aliases so all existing importers (nats-stream-buffer, projector-chunk-stream, test suite) continue to work unmodified - unwrapPayload is re-exported as decodeStream alias for back-compat - Adds M1 boundary test (MAX_PUBLISH_BYTES + 1 → 2 fragments) and decode/round-trip tests to run-stream-codec.test.ts Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
pump/publishChunk, publishRawChunk, publishDone, and the pump done-sentinel
now delegate to serializeChunk/serializeDone/serializeUnfencedDone from
@decocms/harness/run-stream-codec. The inline fragment loop, fragmentMsgId,
and all threshold/header imports (MAX_PUBLISH_BYTES, FRAG_INDEX/TOTAL_HEADER,
MAX_CHUNKED_BYTES, buildChunkMsgId, buildDoneMsgId, parseRunStreamMsgId) are
removed. The publishRawChunk interface and ingest-run caller now accept a
structured dedup ref { fenceToken, seq } instead of a pre-built msgId string.
Output is byte-identical; the createTailStream gate block is untouched.
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…done sentinel Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Rewire createDirectNatsPublisher (packages/sandbox) to use the shared
run-stream-codec (serializeChunk / serializeDone) on the desktop produce
path, gaining the same fragmentation that the hosted path already has.
Large chunks whose {p:chunk} JSON exceeds MAX_PUBLISH_BYTES are now split
into ordered fragment messages with Dp-Frag-Idx/Dp-Frag-Total headers and
per-fragment msgIds (runId:fence:seq:frag:i), preventing MAX_PAYLOAD_EXCEEDED
publish errors on large UI chunks. publishRelayBodyToNats is untouched.
Adds @nats-io/nats-core devDep (was a transitive dep but not hoisted).
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…am wire Remove temporary re-export bridges from relay-publisher.ts, projector-stream-messages.ts, and nats-chunk-source.ts; repoint all importers directly to @decocms/harness/run-stream-codec. Rename unwrapPayload → decodeStream at every call site and drop the alias. Fold-in fix: add console.warn for oversized drops in both publishLine branches of relay-publisher (ui-message-chunk and error), matching the nats-stream-buffer warn added in Task 4. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…load ref) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…idue
- Remove the temporary "[decopilot:stream] resume — resolved source state"
diagnostic (self-marked "drop once root-caused"; the resume path is now
verified end-to-end and it logged on every tool-approval resume).
- Remove the now-dead `terminal: false` "checkpoint pass" in run-persistence:
after the checkpoint machinery was deleted the durable projector folds once
at the terminal `{done}`, so no caller passes `terminal: false`. Drop the
flag + dead branch and align the comments to the single-terminal-fold model.
- Fix stale "checkpoint" comments left by the deletion (project-chunks fold
doc; the projection e2e spec's sibling-suite case list).
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
tlgimenes
force-pushed
the
eta-telescopii
branch
from
June 29, 2026 23:59
18718eb to
66d36fb
Compare
…ough
The /stream route replayed the entire per-thread JetStream subject
(deliverPolicy:"all") and re-wrapped it in a redundant createUIMessageStream,
so an accumulated subject (many runs of orphaned tool-outputs) choked the
client's readUIMessageStream ("missing toolcall id"). Make /stream a simple
NATS-chunk -> UIMessageChunk pass-through and fence-filter the tail to the
current run (the thread's run_fence_token), mirroring the durable projector.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
A continuation run (after approve/deny) emits the approved/denied tool's output under a fresh harness message id, while the pending tool part still lives on the proposal message. Both live reassemblers (the producer's consumeHarnessStream and the client's readUIMessageStream) lacked that prior context, so they threw "No tool invocation found" — surfacing as a server "stream pump error" and the client's "No response was generated" / error banner. The durable projector never threw because it seeds originalMessages from loadWindow; mirror that on both live paths. - Producer (ingest-run + dispatch-run): lazily loadWindow the trailing message and pass it as originalMessages to consumeHarnessStream, which already merges via continuationMessageId — it was just never fed a seed. - Client (thread-connection): when the trailing assistant holds an approval-requested/approval-responded tool part, seed a clone into readUIMessageStream and pin the folded id back to the proposal id so the continuation merges onto the proposal instead of creating a duplicate. Verified deny x3 + approve (real exec): single merged message, zero pump errors, clean projection, clean console. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The /stream connection is long-lived across runs, but the tail was fence-filtered to the run_fence_token read once at connection open. Run 2+ minted a new fence, so every chunk was dropped and the stream appeared to never end. Remove the fence-filter entirely: the tail now forwards every run's chunks verbatim (NATS log -> reassembleFragments -> decode -> SSE) and the client (useChat) is the sole reassembler. A continuation run's tool-output reconciles because the client seeds its reassembler from the proposal message (see thread-connection.ts foldSubStream). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
- knip: unexport isDurableDispatchRunInput (internal-only) and refresh the offload-messages doc comment that referenced the deleted payload-chunking.ts re-export (run-stream-codec.ts is the real MAX_PUBLISH_BYTES consumer). - dbos: re-baseline workflow-source-guard snapshot for the transitive source drift in hosted-harness-workflow.ts and thread-gate-workflow.ts (they import the dispatch-run/ingest-run modules touched by the continuation-seed fix). No DBOS.runStep sequence change, so no DBOS_WORKFLOW_VERSION bump. - e2e: the two optimistic-dispatch tests posted to a bare thread id; the v2 stream-of-record write path now persists the request message part under the thread row (FK), so create a real thread like the sibling tests. Still asserts the 202 optimistic accept with no live link. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Switching the approval level to "auto" while a tool approval is pending sent that approval's continuation at level "auto", which makes needsApproval=false. The SDK then re-resolves isApprovalNeeded() for the just-approved tool, sees it no longer requires approval, and denies it as a "fabricated" approval (validate-tool-approvals.ts) — emitting tool-output-denied. The chunk handler leaves the part's approval.approved=true, producing an invalid v6 part (output-denied requires approved:false) that bricks every later turn's validateUIMessages with "Type validation failed". Respond to the pending approval at the request-time level so the SDK still sees the tool as needing approval and honors the response; the freshly-selected level is already persisted and governs subsequent turns. No new types — restores the SDK invariant that needsApproval is stable for a given tool call. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
decocms Bot
pushed a commit
that referenced
this pull request
Jun 30, 2026
PR: #4179 feat(decopilot): unified per-run projection workflow (consume step + hosted child harness) Bump type: minor - decocms (apps/mesh/package.json): 3.71.0 -> 3.72.0 - @decocms/e2e (packages/e2e/package.json): 0.0.3 -> 0.1.0 - @decocms/harness (packages/harness/package.json): 1.9.3 -> 1.10.0 - @decocms/sandbox (packages/sandbox/package.json): 1.6.2 -> 1.7.0 Deploy-Scope: both
viktormarinho
added a commit
that referenced
this pull request
Jul 6, 2026
…me step still projects it (#4337) The run-reactor purged `decopilot.stream.<runId>` on every RUN_FAILED, under the pre-#4179 assumption that failed runs skip the projector. Since the unified consume step, EVERY dispatched run is projected (its entry guard deliberately ignores terminal status), and projection requires the contiguous seq 1..N log. The purge beheads that log in two live ways: - The 10-min idle reaper force-fails a run whose producer is still alive (e.g. a hung long tool); the purge wipes seq 1..K, late chunks resume at K+1, and the consume step then poisons the thread with a persisted "Error: missing seq 1" as the user-visible assistant message. - An ordinary in-band failure fires RUN_FAILED right before the consume step reads the subject; the fire-and-forget purge races that read. Purge ownership now lives solely with the projector (terminal projection) plus the dispatch-start cleanup of the previous turn; the stream's 24h max_age bounds never-projected runs. `RunReactorDeps` drops `streamBuffer` so the guarantee is structural. Co-authored-by: Claude Fable 5 <[email protected]>
pedrofrxncx
added a commit
that referenced
this pull request
Jul 8, 2026
…4370) The GitHub save/publish header could vanish entirely when the repo's "is a connection attached?" state was interpreted inconsistently across call sites, or when a repo-scoped github child was aggregated under more than one agent (the 1:1 invariant lived only in code and drifted). 1. Single source of truth: new resolveGithubAttachment() derives one discriminated status (none | public-clone | attached | detached) from metadata.githubRepo + live connections. getActiveGithubRepo and the agent-capabilities gates now all go through it instead of each re-interpreting the two fields independently. 2. SQL-enforced invariant (migration 125): a BEFORE INSERT trigger rejects attaching a repo-scoped github child (metadata.repoScope) to a second parent. Pre-existing violations are deduped first (keep the claiming parent, else oldest) so the last edge is never removed and the trigger installs cleanly. Verified against real Postgres. 3. Graceful degrade: a detached repo now renders a "Reconnect GitHub" pill instead of nothing, so a stale/mid-mutation aggregation never leaves the header blank with no recovery path. Also registers 123-drop-thread-projected-seq (committed in #4179 but forgotten from the migrations index, so it never ran) as 124, resolving the duplicate-123 collision and the red migration-index guardrail.
pedrofrxncx
added a commit
that referenced
this pull request
Jul 8, 2026
The unit-test job globbed only `apps/mesh/src` + `packages`, so the three tests under apps/mesh/migrations/ never ran in CI — including index.test.ts, the guardrail against forgetting to register a migration. That's why #4179 shipped 123-drop-thread-projected-seq unregistered with the guardrail red. Add apps/mesh/migrations to the find roots; all three pass.
tlgimenes
added a commit
that referenced
this pull request
Jul 9, 2026
…projector consumes (#4409) * feat(decopilot): hosted child publishes its own stream terminal The hosted-harness child workflow now wraps its agent-loop step in try/catch: on any caught failure it publishes a fence-scoped in-band error chunk (real err.message, never masked) + {done} to the run's subject, using the same StreamBuffer surface ingestRun uses on the clean path, and returns normally instead of rethrowing. The child's DBOS status becoming SUCCESS is intentional — run outcome now lives on the thread via the projector's fold of what's on the stream, which is the foundation Task 3 builds on to stop the gate awaiting the child. Co-Authored-By: Claude Fable 5 <[email protected]> * refactor(decopilot): projector is the single side-effect site for runs Closes the pump-swallow gap: a mid-stream hosted-ingest failure with healthy JetStream used to be caught and logged by NatsStreamBuffer.pump() but never propagated, so dispatchRunAndWait returned as if the run had finished cleanly and hostedHarnessWorkflowFn's failure-terminal catch never fired. pump() now returns a promise that rejects with the swallowed error (after still publishing the safety-net done sentinel); dispatchRunAndWait awaits it, so the error reaches the child's existing catch and a fenced terminal reaches the stream for every caught failure, not just setup ones. ingestRun now stamps the highest contiguous published seq onto a mid-stream throw (own-enumerable, survives the DBOS step boundary) so the failure-terminal publishes at the right seq instead of colliding with already-published content chunks. Strips dispatch-run.ts's now-duplicate chat_message_failed posthog capture from the hosted live path — the projector's recordFailed is the sole source for both topologies, restoring the analytics signal T1's change to the hosted child had silently dropped. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(decopilot)!: unified gate control plane — projector-authoritative completion for hosted runs (DBOS v4) The thread gate no longer treats hosted and desktop runs differently at completion time: it starts the hosted child workflow and moves on without awaiting its result, then falls straight through to the consume step, which now live-tails the run's JetStream subject for BOTH topologies — exactly the timing desktop has always used (its work item is published and the gate returns long before the daemon streams anything back). The hosted child is a fully detached, self-terminating executor (T1: it publishes its own fence-scoped terminal on a clean finish and on every caught failure; T2: the projector is the sole side-effect site) — consumeRunProjection's live tail is now the SOLE completion authority for both topologies. `enqueueHostedHarness` is split: `hostedChildWorkflowId(runId, fenceToken)` is now the single exported source of truth for the child workflow id (used by `startHostedHarness` and `cancelHostedHarness`, and by unified-control-plane T7's future stop-cancellation path), and `startHostedHarness` starts the child without awaiting `handle.getResult()`. Dropping that `getResult()` wait removes a recorded operation from `threadGateWorkflow`'s DBOS journal, and the consume step's live-tail now runs at a structurally different point in time for hosted runs (concurrently with the child instead of strictly after it) — both are step-sequence/timing contract changes on a durably-recorded workflow, so this bumps DBOS_WORKFLOW_VERSION 3 -> 4, the one deliberate version bump of the unified-control-plane project. Deploy consequence: any v3 gate workflow still mid-flight at deploy time (a message queued or a run in progress when the new pods roll out) strands — no v4 executor can recover it, by design. The existing Stop-button cancel path (cancelThreadGateHead + cancelHostedHarness) is the user-facing recovery: cancel the stranded gate/child and re-send. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(decopilot): stream-silence liveness terminal in the consume path A silent run subject (no events of any kind for RUN_IDLE_TIMEOUT_MS) is now a first-class liveness terminal instead of an opaque "projection" failure. - natsChunkSource errors with a distinguishable StreamIdleTimeoutError instead of a bare Error when the idle window trips. - consume-run-projection.ts threads idleTimeoutMs through to the chunk source, defaulting to the now-exported RUN_IDLE_TIMEOUT_MS (10m) — the same constant the progress-based reaper enforces, replacing the stale, unthreaded 30m DEFAULT_IDLE_TIMEOUT_MS. - runProjectorWorkflowBody's catch discriminates StreamIdleTimeoutError from other thrown errors and records markRunFailed(kind: "liveness", reason: "liveness: no stream events for {N}m") instead of the generic "projection" catch-all, via the same markRunFailed/recordFailed path. thread-gate-workflow.ts (the DBOS-registered workflow) is untouched — the default is applied inside consumeRunProjection itself, so no DBOS_WORKFLOW_VERSION bump or workflow-source-guard re-baseline is needed. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(decopilot): hosted run heartbeats during silent phases With the T4 liveness rule armed (silence on the run subject > RUN_IDLE_TIMEOUT_MS = terminal), a hosted executor that is alive but silent — a long tool execution or model wait with no incremental output — would be falsely killed at the 10-minute mark. Give the hosted executor a heartbeat: a transient `data-liveness` UIMessageChunk injected into the harness chunk stream whenever LIVENESS_HEARTBEAT_INTERVAL_MS (30s, ~20 beats of margin inside the 10-minute window) elapses with no real chunk. The heartbeat wraps the RAW harness source before ingestRun's seq-wrapper (dispatch-run.ts `chunks: withLivenessHeartbeat(dispatchHarnessChunks())`), so it flows through the exact same publish pipeline as every other chunk: it consumes a real seq (dedup contract `${runId}:${fenceToken}:${seq}` untouched) and resets natsChunkSource's per-pull idle window on the projector's consume side like any other subject event. Wire shape: `{type:"data-liveness", data:{t}, transient:true}`. The AI SDK's shared reducer (processUIMessageStream, [email protected]) never pushes a transient data chunk into the accumulated message parts, so the client fold (readUIMessageStream in thread-connection.ts) renders nothing and the durable projector fold (project-chunks.ts -> consumeHarnessStream) persists no part row per heartbeat — verified against the installed package source; the client additionally has two pre-existing catch-all `data-*` render guards (use-filter-parts.ts, assistant.tsx). The scheduler itself (HeartbeatEmitter + the 30s constant) lives in packages/harness/src/liveness-heartbeat.ts — pure, injected clock via @decocms/std sleep(ms, {signal}), arm/stop semantics, self-rescheduling — so unified-control-plane T6 can reuse it for the desktop daemon's relay pump (packages/sandbox already depends on @decocms/harness). No DBOS workflow file touched: no version bump, no source-guard snapshot churn. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(sandbox): daemon relay heartbeats during silent phases Mirrors T5's hosted-executor liveness heartbeat for the DESKTOP executor: with T4's liveness rule armed (silence on the run subject > 10 minutes = terminal), a desktop dispatch that is alive but silent — a long tool execution or model wait with no incremental SSE output from the local sandbox — would be falsely killed. Give the daemon's relay pump the same heartbeat T5 gave the hosted path. Traced the desktop dispatch pipeline end to end: the local sandbox daemon (packages/sandbox/daemon/routes/dispatch.ts) streams raw SSE over loopback; the link daemon's relay pump (apps/mesh/src/link-daemon/chunk-relay.ts, relayDispatchSSEAsChunkStream) is the ONLY place that assigns the wire seq and appends to the durable outbox, publishing straight to JetStream via packages/sandbox/dispatch/relay-publisher.ts (direct-NATS is the sole live relay path today — no HTTP-POST-to-cluster path remains). That's where the heartbeat had to go, mirroring T5's "wrap the raw source before the seq-wrapper" placement. relayDispatchSSEAsChunkStream's pump now owns a HeartbeatEmitter (@decocms/harness/liveness-heartbeat, the exact scheduler class T5 already relocated there for this purpose — no new dependency needed, apps/mesh already depends on @decocms/harness). Armed before the pump loop starts, re-armed on every real DispatchSSEEvent, stopped in a finally covering normal completion / error / abort. A firing heartbeat calls the SAME pushLine every real event uses, so it consumes a real wire seq, rides the outbox's dedup/resend/rolling-truncation contract unmodified, and resets the projector's idle window (natsChunkSource, T4) on the consume side like any other message on the run subject. New `livenessHeartbeatMs` input, explicitly distinguished from the pre-existing `heartbeatMs` (a transport-level blank-line keepalive that never becomes a relay line). Added buildLivenessChunk/LivenessDataChunk to packages/harness's liveness-heartbeat.ts (additive) as the single wire-shape source of truth so this can't drift from T5's own hand-copy in with-liveness-heartbeat.ts — both emit byte-for-byte identical {type:"data-liveness", data:{t}, transient:true}. Version-skew note (documented in both module docs): an already-deployed daemon predating this change never emits these — the 10-minute RUN_IDLE_TIMEOUT_MS stays as-is until fleet adoption. This only adds emission, no threshold change. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(decopilot): stop cancels the detached hosted child Verified the wiring already existed at HEAD (PR #4179's `cancelHostedHarness`, refactored by T3 to derive through `hostedChildWorkflowId`) — this task's remaining work was documenting the DBOS `cancelWorkflow` running-workflow semantics (pure DB status flip, checked only at step boundaries — does not abort an in-flight `runHostedHarness` step; belt-and-suspenders for the ENQUEUED window and post-crash recovery, while nats-cancel-broadcast's run-registry AbortController is the real-time abort for an already-running turn) and adding regression coverage that was missing (routes.test.ts source-text assertions locking in cancelActiveThreadRun's fence-guarded, best-effort cancelHostedHarness call). Co-Authored-By: Claude Fable 5 <[email protected]> * refactor(decopilot): single heartbeat source — remove hosted tapProgress buildAgentSandboxUiStream's returned ReadableStream never calls controller.enqueue() — it only close()s or error()s, since raw chunks are routed to JetStream via ingestRun internally. tapProgress's TransformStream.transform() therefore never fired on the hosted path; its last_progress_at bump was dead code (T5's finding, verified by tracing the stream's construction). The projector's tapProgressStream (progress-bump.ts, driven by projector-workflow.ts's JetStream-sourced chunk consumption) is the sole liveness heartbeat for both hosted and desktop runs — this removes the no-op duplicate. Co-Authored-By: Claude Fable 5 <[email protected]> * test(decopilot): unified control plane proofs Proof suite for the unified-control-plane work (T1-T8): a co-located unit test for the hosted child's half-terminal invariant (done never published when the error-terminal publish itself fails; the outer catch swallows, never rethrows), plus two new e2e specs — hosted setup-failure surfacing as a real (non-masked) stream event via a dummy AI_PROVIDER_KEY_CREATE pointed at a closed port, and executor death mid-run reaching a liveness terminal via a fake daemon that goes silent mid-stream. RUN_IDLE_TIMEOUT_MS is now env-overridable (read once at module load) so the liveness proof doesn't block CI for a real 10 minutes; packages/e2e/playwright.config.ts shortens it to 120s for the e2e webServer only. Also extends the multi-pod suite's existing hosted streaming-turn scenario (attach-cross-pod.test.ts) to assert in_progress-while-streaming, terminal completed, and parts persisted exactly once. Co-Authored-By: Claude Fable 5 <[email protected]> --------- Co-authored-by: Claude Fable 5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Replaces the standalone decopilot projector with a per-run consume step folded into the dispatch workflow, and unifies hosted and desktop runs so they take the same path. One workflow owns each run end-to-end; NATS is a pure transport; projection is reliable and the terminal status has a single writer.
New flow (identical for both topologies): parent dispatch workflow =
dispatch (start a producer that streams to NATS) → consume.hostedHarnessWorkflow,HOSTED_HARNESS_QUEUE) that runs the agent loop. No longer runs inline.consume-run-projection.ts) binds a per-run durable NATS consumer, projects incrementally (checkpoints) + terminally ({done}) by reusing the existing fold engine, and is the sole terminal-status writer, mapping finish-reason →completed | requires_action | failed.Key changes
setRunFence) hoisted to the gate for both topologies, sorun_fence_tokenis written before the consumer reads it.run-reactor.ts handleTerminalStatusdeleted → consume is the only writer ofcompleted/requires_action(SSE/metrics kept). This makes the simpleif terminal → returnentry guard correct.markRunRequiresActionruntime method added; finish-reason → status via existingresolveThreadStatus.projectRunWorkflow/projectCheckpointWorkflow+ startup) deleted.PROJECTOR_QUEUEremoved;HOSTED_HARNESS_QUEUEadded toinitDbos(partition bythreadId, concurrency 1) andRUN_QUEUES— both parent and child run on worker pods.DBOS_WORKFLOW_VERSIONbumped to"2"(parent step sequence changed + new registered workflow).Design + plan:
docs/superpowers/specs/2026-06-26-decopilot-projection-single-workflow-design.md,docs/superpowers/plans/2026-06-26-decopilot-projection-single-workflow.md.Testing
tsctypecheck green across the branch; pure-logic unit tests pass (consume-run-projection.test.ts7/7); each task's relevant unit/integration tests passed at implementation time.packages/e2e/tests/decopilot-projection.spec.ts) could not run locally (no Postgres/NATS/dev-server in the dev sandbox) — please ensure CI runs the full e2e stack. 3 live cases (desktop happy-path, entry-guard, hosted gated onE2E_ANTHROPIC_KEY); 5 casestest.skipwith precise TODOs naming the missing test-injection hooks.Affected areas
apps/meshdispatch-queue (thread-gate + new hosted-harness workflow), decopilot projection (consume step, projector-workflow primitives), run-reactor, storage/threads, app.ts DBOS wiring, index.ts RUN_QUEUES.Follow-ups (non-blocking)
RUN_FAILEDpurges the stream while consume may project the same in-band-error run. Bounded + self-correcting (DB alreadyfailed,markRunFailedidempotent); worst case is truncated failed-run parts or a consume idle-timeout holding the per-thread slot up to 30 min. Not a regression (old poll cap was 1h). Fix: pass an abort signal toconsumeRunProjectionon terminal-failure and/or defer theRUN_FAILEDpurge to consume'spurgeRun.idleTimeoutMsoverride, a raw-publish dedup bypass, and multi-pod kill controls).🤖 Generated with Claude Code
Summary by cubic
Unifies decopilot runs behind a per‑run consume step that reads JetStream and is the only writer of terminal status for both hosted and desktop paths. Also fixes tool‑approval resumes so switching to auto‑approve mid‑pending still honors the original approval request and doesn’t deny the tool.
New Features
consume-run-projection.ts: per‑run durable consumer and sole writer ofcompleted | requires_action | failed(guarded byisTerminalStatus).hostedHarnessWorkflow) onHOSTED_HARNESS_QUEUE(partitioned bythreadId, concurrency 1); parent enqueues child, starts producer, then runs consume; cancel path best‑effort cancels the child.start.messageIdvia@decocms/harness/message-id; producers/consumers use@decocms/harness/run-stream-codecfor subject/msgId, JSON envelopes, fragmentation, and decode.publishRawChunknow takes{ fenceToken, seq }for dedup./streamis a pure NATS pass‑through.{done}and persists final requires‑action tool states and request‑message snapshots. Thread gate mints a fresh fence and re‑armsstatus=in_progressper turn; the live reactor no longer writes terminal status.Migration
HOSTED_HARNESS_QUEUE, removePROJECTOR_QUEUE.threads.projected_seq.DBOS_WORKFLOW_VERSIONto "3" and redeploy all workers.publishRawChunk(runId, chunk, { fenceToken, seq })shape.Written for commit 91bdd78. Summary will update on new commits.