Skip to content

refactor(decopilot): narrow dispatch wire contract (v3) and remove desktop runtime - #4183

Merged
tlgimenes merged 27 commits into
mainfrom
psi-fornacis
Jun 28, 2026
Merged

tlgimenes merged 27 commits into
mainfrom
psi-fornacis

Conversation

@tlgimenes

@tlgimenes tlgimenes commented Jun 28, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Refactors the decopilot/harness/sandbox dispatch path around a narrowed v3 wire contract, removing the legacy desktop runtime entirely and feeding CLI harnesses a single wire-ready user message.

Highlights

  • Remove the desktop runtime path from decopilot — drops desktop-runtime, desktop-prompt, desktop-tool-ctx, desktop-sandbox-fs(-registry) and their tests; decopilot now owns history-context loading and the agent loop stays cluster-hosted for desktop runs.
  • Narrow the dispatch wire contract (v3) — shrink/tighten the stream-input contract, carry the dispatch run id outside the harness input, type envelope rebasing, and make the rebased workspace cwd explicit.
  • One wire-ready user message — dispatch and CLI harnesses now send a single user message; decopilot context is kept off the wire.
  • Move shared helpers out of decopilot — stream-error, title-generator relocated to packages/harness/src/; simplified decopilot exports.
  • Desktop CLI models marked vision-capable; e2e/test coverage aligned with the v3 contract.

Request flow

How a chat message travels from the HTTP edge to an agent loop:

  1. POST /:org/decopilot/threads/:threadId/messages receives the request, resolves the harness, and enqueues the run — starting a DBOS workflow via enqueueThreadRun() → DBOS.startWorkflow(threadGateWorkflow) (apps/mesh/src/api/routes/decopilot/routes.ts:552,697, apps/mesh/src/dispatch-queue/thread-gate-workflow.ts:569). The thread-gate queue serializes runs per thread (concurrency = 1).
  2. The worker grabs the work item and calls dispatch in dispatchRunAndWaitStep(), which branches on the harness id via resolveHarnessExecutionSite() (apps/mesh/src/dispatch-queue/thread-gate-workflow.ts:256,135).
  3. harness_id === "decopilot" → run the agent loop inline in the cluster worker (in-process via dispatchRunAndWait() → sandboxClient.dispatch()).
  4. harness_id === "claude_code" | "codex" → run the agent loop on the sandbox.
    • On a user-desktop sandbox, the run is published as a work item over the link tunnel and the desktop daemon pulls it and runs the harness locally (prepareLinkWorkDispatch() → workPublisher.publish()).
    • On a cluster agent-sandbox, it runs inline in the cluster like decopilot (default execution site).

Testing

  • bun test (unit) over the touched harness/sandbox/dispatch suites
  • e2e suites updated to assert v3 harness work items

🤖 Generated with Claude Code

tlgimenes and others added 25 commits June 28, 2026 17:31
…runs

decideLinkDispatch routed every user-desktop run through the link tunnel,
which forced decopilot onto the daemon and failed in prepareLinkWorkDispatch.
Decopilot's streamText loop must always run in the cluster — only its tool
calls travel to the sandbox (desktop via the NATS downlink, cloud via the
agent-sandbox provider).

Rename decideLinkDispatch -> resolveHarnessExecutionSite, returning a typed
"cluster" | "sandbox" site keyed off the (harnessId, sandboxProviderKind)
tuple, and refresh the stale "every user-desktop -> link" comments across
the gate and dispatch-run.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ent-sandbox)

A claude-code/codex run targeting a cluster agent-sandbox has no host yet.
Instead of silently falling through to the cluster local-dispatch path (which
would ignore the requested sandbox), resolveHarnessExecutionSite now throws
"not implemented" for that tuple. Desktop CLI (user-desktop) and decopilot
(any sandbox) are unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@tlgimenes
tlgimenes enabled auto-merge (squash) June 28, 2026 20:55
tlgimenes and others added 2 commits June 28, 2026 18:05
…riant

Now that a CLI harness on an agent-sandbox is rejected at the gate
(resolveHarnessExecutionSite throws "not implemented"), the cluster-only
lazy dispatch generator in dispatchRunAndWait can only ever successfully run
decopilot: CLI on user-desktop takes the link transport, CLI on agent-sandbox
throws upstream. The only residual way a CLI harness reaches the generator is a
link-incapable runtime.

Collapse the two separate guards (the `if (harnessId === "decopilot")` context
gate plus the `user-desktop && !decopilot` throw) into a single decopilot-only
invariant at the top of the generator, set the decopilot run context
unconditionally, and refresh the now-stale comments (hosted-CLI cwd note and the
"runs CLI on agent-sandbox/legacy" description). No behavior change for real
paths: a non-decopilot harness reaching here still throws.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The thread-gate routing change (decideLinkDispatch ->
resolveHarnessExecutionSite) edits logic INSIDE the dispatchRunAndWait
step; the workflow step sequence (trackMessageStarted -> dispatchRunAndWait
-> trackMessageFailed) and recorded step I/O are unchanged, so it is
recovery-compatible. Re-baseline the snapshot without bumping
DBOS_WORKFLOW_VERSION.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@tlgimenes
tlgimenes merged commit 36ff63e into main Jun 28, 2026
15 checks passed
@tlgimenes
tlgimenes deleted the psi-fornacis branch June 28, 2026 21:19
tlgimenes added a commit that referenced this pull request Jun 29, 2026
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]>
tlgimenes added a commit that referenced this pull request Jun 29, 2026
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]>
tlgimenes added a commit that referenced this pull request Jun 30, 2026
…hosted child harness) (#4179)

* refactor(decopilot): consume-step projection architecture on v3 contract

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]>

* fix(decopilot): re-arm run status on turn-start so a 2nd turn isn't dropped

`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]>

* fix(decopilot): persist checkpoint parts for single-step (CLI) harness 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]>

* chore(decopilot): checkpoint projection WIP before message-id unification

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]>

* docs(decopilot): message-id unification spec + implementation plan

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(harness): share one message-id generator and stamp start.messageId in all harnesses

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* feat(decopilot): consume harness message id verbatim + continuation merge in fold

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* fix(decopilot): terminal projector persists harness message id, merge from originalMessages

* refactor(decopilot): drop deterministic assistant-id generator from checkpoint + live ingest

* test(decopilot): two-turns id test verifies verbatim harness start.messageId flow-through

* refactor(decopilot): add shared nats-chunk-source skeleton (types + source)

* refactor(decopilot): add shared reassembleFragments transform

* refactor(decopilot): add shared unwrapPayload transform

* test(decopilot): verify approval continuation merges onto proposal (no duplicate message)

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* refactor(decopilot): add projector fenceFilter transform

* refactor(decopilot): add projector assertContiguousAndDedup transform

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* test(decopilot): assert continuation content merged onto proposal (harden Layer 2 gate)

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* refactor(decopilot): add projectorChunkStream terminal stage

* docs(decopilot): note single-message invariant behind the continuation-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).

* fix(decopilot): test projectorChunkStream cancel cascade via infinite source; revert natsChunkSource exhaustion hack

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* refactor(decopilot): compose projector chunk stream from shared transforms

* fix(decopilot): satisfy tsc strict-null in nats-chunk-source tests

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]>

* docs(decopilot): align comments with the unified message-id architecture

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.

* docs(decopilot): document widened onDone trigger; drop stray path comment

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]>

* refactor(decopilot): compose live tail stream from shared nats-chunk-source decode

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* refactor(decopilot): harden live-tail cleanup (guard releaseLock, restore 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]>

* fix(decopilot): stop the subscription on projector error exits too

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]>

* refactor(decopilot): import shared FRAG_* header constants

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]>

* fix(decopilot): mint a fresh run fence per turn so approval continuations 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]>

* refactor(decopilot): delete dead checkpoint projector + projector-run-log

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* refactor(decopilot): drop dead projected_seq thread column

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* refactor(decopilot): drop the checkpoint event kind from the shared decode

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* refactor(decopilot): remove checkpoint publication + wire helpers

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* fix(decopilot): restore mid-stream outbox-truncation report dropped with checkpoint debounce

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* refactor(decopilot): remove orphaned projectRun left dead by checkpoint removal

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* refactor(decopilot): remove dead checkpoint e2e stub routes + vacuous 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]>

* refactor(decopilot): add run-stream codec (serialize side) in @decocms/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]>

* refactor(decopilot): move run-stream decode into the codec; parse path 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]>

* refactor(decopilot): hosted produce path serializes via the codec

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]>

* fix(decopilot): preserve metrics on oversized drop + silent unfenced-done sentinel

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* feat(decopilot): desktop relay fragments large chunks via the codec

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]>

* refactor(decopilot): codec is the single source of truth for run-stream 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]>

* docs(decopilot): fix stale codec comments (re-export note + unwrapPayload ref)

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* docs(decopilot): codec header reflects both serialize + decode sides

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* refactor(decopilot): drop resume debug log + dead checkpoint-pass residue

- 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]>

* fix(decopilot): fence-filter /stream tail + simplify to NATS pass-through

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]>

* fix(decopilot): seed reassembly for tool-approval continuations

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]>

* fix(decopilot): /stream pure NATS pass-through (drop fence-filter)

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]>

* chore(decopilot): clear CI blockers (knip, workflow snapshot, e2e seed)

- 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]>

* fix(decopilot): honor pending approval when switching to auto-approve

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]>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant