Skip to content

feat(decopilot)!: unified run control plane — executors publish, the projector consumes - #4409

Merged
tlgimenes merged 9 commits into
mainfrom
feat/unified-control-plane
Jul 9, 2026
Merged

tlgimenes merged 9 commits into
mainfrom
feat/unified-control-plane

Conversation

@tlgimenes

@tlgimenes tlgimenes commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Unifies the hosted and desktop run control planes into one flow: executors publish to the run's NATS subject; the gate live-tails it via the projector, which is the sole completion authority. No more topology fork in the gate, no more child-await, one liveness rule for everything.

Spec: three user-settled pillars — (1) errors-as-stream-events (the hosted child catches its own failures and publishes an error terminal, exactly like the desktop daemon), (2) executors heartbeat on the subject (transient data-liveness chunks; one rule: no subject events for RUN_IDLE_TIMEOUT_MS = 10 min ⇒ liveness terminal with a real failure_reason), (3) hard cut with a DBOS_WORKFLOW_VERSION 3→4 bump.

⚠️ Deploy runbook (why automerge is OFF)

The gate's recorded step sequence changed → version pin bumped "3" → "4" (the branch's one deliberate bump, commit feat(decopilot)!: unified gate control plane…). At rollout, in-flight v3 gate workflows strand (version-scoped recovery — by design). Recovery is user-actionable: a stranded thread's Stop button cancels the zombie gate head and frees the thread; the user re-sends. Recommended: deploy stg first and dogfood a few streaming turns (hosted + desktop), then prod at low traffic. Merge timing is a human call.

Changes (9 commits, one per task)

  1. Hosted child self-terminal — catches all failures → publishes fenced error chunk + {done} (real error text on the subject; masking stays a wire concern). Deterministic error-message id converges with the projector's synthesized-error dedup.
  2. Projector = single side-effect site — usage/posthog/SSE fire once, from the projector, both topologies. Closed the pump-swallow gap (mid-stream hosted failures now produce a fenced terminal with the true next seq via .lastAckSeq error-stamping). retriesAllowed: false on the agent-loop step (review-caught: rejection would otherwise re-run the whole loop 3× and could splice divergent generations into one message).
  3. Gate v4 — hosted child started, never awaited (hostedChildWorkflowId extracted as single source of truth); consume runs unconditionally for both topologies; start-failure keeps fast-fail semantics (analytics + rethrow → DBOS recovery; review-caught regression fixed).
  4. Liveness terminal — typed StreamIdleTimeoutError → kind:"liveness" with honest reason; RUN_IDLE_TIMEOUT_MS is the one constant (the divergent 30-min default was provably dead — the per-pod reaper already enforced 10 min).
  5. Hosted heartbeats — data-liveness every 30s of silence, injected pre-seq-wrapper (real seqs, dedup contract); verified ignored by both the client fold and the projector's persisting fold ([email protected] transient-chunk semantics, source-verified).
  6. Daemon heartbeats — same shared emitter + wire shape (single source of truth), wired in the relay pump's seq/outbox path; transport keepalives deliberately do NOT reset the liveness window. Version-skew note: old daemons don't emit — the 10-min window doesn't tighten until fleet adoption.
  7. Stop cancels the detached child — wiring pre-existed (feat(decopilot): unified per-run projection workflow (consume step + hosted child harness) #4179); SDK-verified semantics documented (workflow-cancel = boundary-checked DB flip → covers the enqueued window + blocks recovery resurrection; the NATS broadcast remains the real-time abort) + mutation-verified regression tests.
  8. Deleted the dead hosted tapProgress (provably never fired), the gate's topology fork, and ingestRun's duplicate hooks.
  9. Proofs — half-terminal invariant units; e2e: hosted setup-failure surfaces the real reason (dummy-provider-key pattern), executor-death → liveness terminal (env-shortened window, e2e-only); multi-pod hosted v4 streaming assertions; fence/queue suites byte-identical.

Verification

  • Every task independently reviewed (opus on the high-stakes ones); 2 Important findings caught and fixed pre-merge (retry-splice, swallowed start-failure); all claims verified against installed SDK sources where load-bearing.
  • check / lint / knip / fmt / snapshot-guard clean. Full unit scope: 3908 pass / 244 env-dependent fails vs main's 3846 / 245 on the identical scope (branch strictly better; the fail class is the known no-local-PG/NATS set).
  • T9's e2e/multi-pod proofs execute for the first time in THIS PR's CI — treat that job as part of review.

🤖 Generated with Claude Code


Summary by cubic

Unifies hosted and desktop run control into one path: executors publish to each run’s NATS subject, and the projector live-tails it as the single completion authority. Adds liveness heartbeats and a stream-silence terminal, and bumps the DBOS workflow version to "4".

  • New Features

    • Projector is authoritative for completion and side effects (usage, chat_message_*, SSE) across both topologies.
    • Hosted child catches its own failures and publishes fenced {type:"error"} + {done} with the real error message; Stop also cancels the detached hosted child.
    • Liveness: a silent subject for RUN_IDLE_TIMEOUT_MS (10m) yields failure_kind: "liveness" via a StreamIdleTimeoutError; same window used by the reaper and the consume path.
    • Heartbeats: inject data-liveness every 30s during silent phases in both hosted (with-liveness-heartbeat) and desktop relay (chunk-relay) paths; they consume real seqs, reset the idle window, and are transient (not persisted or rendered).
    • Reliability: NatsStreamBuffer.pump() returns a promise (propagates mid-stream errors after still publishing a done sentinel); ingestRun surfaces lastAckSeq on failure for correct terminal sequencing; removed the dead hosted tapProgress.
    • Tests: new unit and e2e proofs (hosted setup failure surfaces on-stream; executor death → liveness terminal; multi-pod streaming assertions). RUN_IDLE_TIMEOUT_MS is env-overridable for CI; packages/e2e/playwright.config.ts sets a shorter window.
  • Migration

    • DBOS workflow version pinned to "4". Any in-flight v3 gate workflows will strand at rollout; recover by using Stop to cancel the gate and hosted child, then re-send. Deploy to staging first, then roll out to production.

Written for commit e746eaa. Summary will update on new commits.

Review in cubic

tlgimenes and others added 9 commits July 9, 2026 15:39
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]>
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]>
…e 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]>
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]>
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]>
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]>
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]>
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]>
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]>
@tlgimenes
tlgimenes merged commit 31e5c99 into main Jul 9, 2026
15 checks passed
@tlgimenes
tlgimenes deleted the feat/unified-control-plane branch July 9, 2026 23:52
decocms Bot pushed a commit that referenced this pull request Jul 9, 2026
PR: #4409 feat(decopilot)!: unified run control plane — executors publish, the projector consumes
Bump type: major

- decocms (apps/mesh/package.json): 3.116.1 -> 4.0.0
- @decocms/e2e (packages/e2e/package.json): 0.10.0 -> 1.0.0
- @decocms/harness (packages/harness/package.json): 1.11.1 -> 2.0.0

Deploy-Scope: server
tlgimenes pushed a commit that referenced this pull request Jul 16, 2026
…TS.md (#4475)

Mined ~300 merged PRs for the delta between the first PR proposal and the
work added before merge. The dominant shape: a first draft ships the happy
path, then a hardening pass (often a different engineer who takes over the
branch and merges — the vibecoder→engineer handoff) adds the same categories
every time. Encoded those 9 categories as an actionable first-pass checklist,
each citing a real PR (#4008, #4230, #4365, #4409, #4426, #4445, #4357, #4355,
#4449, #4350, #4373, #4416, #4446, #4461, #4134, #4469).

Covers: variant/edge-case handling, tenant/permission scoping, concurrency &
silent-data-loss, test-per-fix + invert-bug-tests + real-PG, dead-code/knip,
lifecycle symmetry + state reset, kill-switch/GC/git-exclude for risky infra,
input validation vs over-engineering, compile-time type-safety.

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