Skip to content

feat(mocactl): spawn --async, a subagent backed by a turn record (#381) - #922

Merged
cwiklik merged 3 commits into
rossoctl:mainfrom
cwiklik:feat/381-spawn-async
Nov 19, 2026
Merged

cwiklik merged 3 commits into
rossoctl:mainfrom
cwiklik:feat/381-spawn-async

Conversation

@cwiklik

@cwiklik cwiklik commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

Summary

Epic #378 step 1 (child issue #381): give a spawned subagent a turn record, so it becomes cancellable (#391/B-M1) and A4/#383 clears.

spawn has only ever had one backend — a detached local worker holding a synchronous POST /v1/runs. That leaf has no turn id, so there is nothing to cancel, and killing the local pid leaves the server-side leaf running (the A1 contract #380 pinned). This adds the async-turn backend transport/leaf-turn.ts:3 was written to be replaced by.

Two commits, deliberately separate.

1. control plane: serve an async turn's reply as a text artifact

A blocker for the CLI change, and independently a completion of #390: projectLeafResult drops text from the polled status body and pickArtifact served only patch, so all that survived of a prompt leaf's reply was result.summary — clipped to MOCA_TURN_SUMMARY_BYTES (2048). --kind prompt is spawn's default, so dispatching async without this would have turned "writes the full reply to <sid>.text" into "writes a 2 KB summary".

describeArtifacts now appends { kind: 'text', bytes } beside the patch entry, and pickArtifact serves it as text/plain; charset=utf-8. The route's existing hash fallback supplies the ETag, text carrying no stored digest. #390 moved the assistant's text out of the polled body but gave it no route; this is that route.

API contract: control plane 1.32.0. Additive, but artifacts[0] can no longer be assumed to be the patch.

2. mocactl: spawn --async

spawn --async creates the session as before, then queues the leaf with POST /v1/sessions/{id}/turns and records the turn id on the ledger row. No fork — the turn record is the subagent, so nothing on this machine has to survive the command, which is the whole point.

subagents and get route per row: a row with a turnId reads GET …/turns/{turnId} with the API token the command already holds (no session-token mint, no mid-wait re-mint), and get fetches the reply and the patch from the turn's artifact routes once there is a result. Everything they print and write is unchanged, because transport/async-turn.ts answers in the same LeafResultBody the sync transport does — mapHonestState/terminalFromBody and all of cmdGet's file writing are untouched.

Opt-in rather than a swap, because the server-side drain is off by default: armAsyncLeafWorker (packages/server/src/worker.ts:396) returns null unless SH_ASYNC_DRAIN is set, and no deploy target sets it (deploy/vm has it commented out, deploy/compose passes ${SH_ASYNC_DRAIN:-}, deploy/k8s reads an optional ConfigMap key). Making --async the only path would submit turns nothing dequeues — queued until the reaper calls them lost. Arming the deploy targets is an operator-facing default across three targets plus setup.sh validation, so it is not folded into a CLI change.

Three smaller consequences, each with its reason in the code:

  • --async --workload is refused client-side, exit 2: the control plane answers a workload on the async path with 501 workload_runs_unavailable, so there is no point creating a session for it.
  • the --max-concurrent preflight counts an async row as holding a slot without probing a pid — it has no child. The slot clears when subagents or get reads the turn and records a terminal state.
  • noResultComing skips its dead-pid branch for an async row: the turn state the caller just read is that row's liveness, and a turn going nowhere ends as lost rather than as a dead pid.

LedgerRecord.turnId is written once, at append, and its presence is the backend marker — no second column, no migration, old rows keep working.

Known limit, documented

An async row spawned on another machine is invisible to this one's get: no ledger row, no turn id, so it falls back to the sync read and finds nothing. The same "one machine's ledger" shortcut --max-concurrent already carries. get --turn ID would close it.

Deliberately not here

  • mocactl cancel — epic step 2, a small change on top of record.turnId, but a separate one.
  • Arming SH_ASYNC_DRAIN by default in deploy/vm|compose|k8s.

Not verified

The end-to-end run on deploy/compose with SH_ASYNC_DRAIN=1, including the byte-compare of <sid>.text with and without --async. That byte-compare is the real proof the text artifact closed the data loss; everything here is unit-level against the spec.

Refs #381, #378, #390

Checklist

  • Commits are signed off (git commit -s).
  • make lint and the tests for the touched packages pass. packages/control-plane:
    turn-result, turn-handlers, openapi-contract — 82 passed. packages/mocactl: 222 passed
    across subagent-get, subagent-spawn, subagent-list, transport-async-turn (new),
    contract, cli and mocactl-reference, plus the whole suite green. 23 of those tests are
    new, covering the state mapping (lost, cancelled, result-status-over-turn-state,
    artifacts-as-kinds), that a status read carries no bytes, that collect asks only for declared
    kinds, that spawn --async never forks and writes no row on a refused submission, that an
    async row holds a --max-concurrent slot, and that --wait on an async row ignores a dead
    pid. make typecheck clean. make lint is clean except hadolint-docker, which needs a
    Docker daemon I do not have running locally.
  • Docs: docs/harness/reference/cli-mocactl.md (regenerated usage plus what --async buys, its
    SH_ASYNC_DRAIN precondition, the --json shape and the cross-machine limit),
    docs/harness/reference/http-api.md, docs/api/openapi.yaml (1.32.0),
    docs/api/CHANGELOG.md and docs/reference/change-policy.md.
  • Docs: make check-links passes (236 files, 0 broken links).
  • A new spec or ADR is registered — n/a, no new spec or ADR.

Assisted-By: Claude Code

rossoctl#390 moved the assistant's text out of the polled status body but gave it no
route: `pickArtifact` served only `patch`, so all that survived a prompt turn
was `result.summary`, clipped to MOCA_TURN_SUMMARY_BYTES (2048). A longer reply
could not be read back at all.

`text` is now a second artifact kind, symmetric with `patch`: described in
`result.artifacts` (after the patch, with no `sha256` — nothing hashes the reply
on the way in, and the fetch route already hashes what it serves for the ETag)
and served whole as `text/plain; charset=utf-8`.

A record whose patch capture was refused for size gains its `text`, which is the
only thing such a record can serve. The artifact descriptor survives a summary
cap of 0, as the patch's does: naming what can be fetched is not model prose.

Contract 1.32.0, additive.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
`spawn` has only ever had one backend: a detached local worker holding a
synchronous `POST /v1/runs`. That leaf has no turn id, so there is nothing
to cancel, and killing the local pid leaves the server-side leaf running
(rossoctl#380). This adds the async-turn backend `transport/leaf-turn.ts` was
written to be replaced by.

`spawn --async` creates the session as before, then queues the leaf with
`POST /v1/sessions/{id}/turns` and records the turn id on the ledger row.
No fork: the turn record IS the subagent, so nothing on this machine has
to survive the command. `subagents` and `get` route per row — a row with
a `turnId` reads `GET …/turns/{turnId}` with the API token the command
already holds, and `get` fetches the reply and the patch from the turn's
artifact routes once there is a result. Everything they print and write
is unchanged, because the transport answers in the same `LeafResultBody`
the sync one does.

Opt-in rather than a swap, because the server-side drain is off by
default: `armAsyncLeafWorker` returns null unless `SH_ASYNC_DRAIN` is
set, and no deploy target sets it. Making `--async` the only path would
submit turns nothing dequeues, queued until the reaper calls them `lost`.
Arming the deploy targets is an operator-facing default, not part of a
CLI change.

Three smaller consequences, each with its reason in the code:

- `--async --workload` is refused client-side, exit 2: the control plane
  answers a workload on the async path with 501, so there is no point
  creating a session for it.
- the `--max-concurrent` preflight counts an async row as holding a slot
  without probing a pid; it has no child. The slot clears when
  `subagents` or `get` reads the turn and records a terminal state.
- `noResultComing` skips its dead-pid branch for an async row: the turn
  state the caller just read is that row's liveness, and a turn going
  nowhere ends as `lost` rather than as a dead pid.

Known limit, documented: an async row spawned on another machine is
invisible to this one's `get` — no ledger row, no turn id. The same "one
machine's ledger" shortcut `--max-concurrent` already carries.

Refs rossoctl#381, rossoctl#378
Assisted-By: Claude (Anthropic AI) <[email protected]>

Signed-off-by: cwiklik <[email protected]>
@cwiklik
cwiklik requested a review from pdettori as a code owner November 19, 2026 16:06
@cwiklik cwiklik added the ready-for-ai-review Request automated AI code review from clawgenti label Nov 19, 2026

@ingpaolodettori-dev ingpaolodettori-dev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review — feat(mocactl): spawn --async, a subagent backed by a turn record (#381)

Both halves are careful work; the mapping onto the sync LeafResultBody is what makes it small, and it holds.

Control plane (1.32.0)

  • describeArtifacts lists patch first, then text, and omits text when the record has none; the refused-capture case now advertises only text, which is exactly right (the patch bytes never left the sandbox).
  • pickArtifact serves text/plain; charset=utf-8 and returns null for an absent/empty reply. The ETag fallback is real — turn-handlers.ts:262-266 hashes when sha256 is missing — so the "no stored digest" choice is honest.
  • The projection change at cap 0 (a descriptor survives, model prose does not) is a sensible distinction and the tests pin both it and the patch-first order.
  • Version bump 1.31.0 → 1.32.0 is correct against main, and this is the only open PR touching docs/api/openapi.yaml; the openapi, http-api.md, CHANGELOG and change-policy edits agree with each other and with the code.

mocactl

  • bodyFromTurn covers every terminal state: queued/running → 'queued', lost → failed/lost, cancelled → aborted/cancelled, a terminal turn with no result → its own state, and a result's finer status otherwise. mapHonestState/terminalFromBody need no new case, as claimed.
  • collect fetches exactly the advertised kinds, once, and only on a read that found a result; the get test asserts one collect and no mintSessionToken for an async row.
  • --async --config works, and for a non-obvious reason worth keeping: submit deliberately sends no configRef, but the turn record copies the session's (turn-handlers.ts:147, cfg: rec.configRef ?? '') and spawn binds configRef when it creates the session (createSession, subagent.ts:305-308).
  • --async --workload is refused before the session exists (the control plane's 501 is at turn-handlers.ts:105), and solve fields are carried and run by the same runLeaf the sync route uses (async-worker.ts:340-343).
  • LedgerRecord.turnId optional and written once at append keeps old rows working; noResultComing correctly skips the dead-pid branch (a lost turn is already terminal in the read).

One suggestion inline about the --max-concurrent slot of a finished async row, and a body note on the same point: the description says "subagents or get reads the turn and records a terminal state", but only cmdSubagents calls ledger.updateState (:576-580); cmdGet/readLeafResult never write the ledger. The code's own comment at :172 says subagents only, so the implementation is what the comment describes — the description overstates it.

Tests: three get cases (collect+write, sync routing, cancelled, no dead-pid grace), five spawn --async cases (submit/no-fork, workload refusal before a session, no row on refusal, cap counting, solve fields) and a 124-line transport test. CI 18/18 green.

Author: cwiklik (MEMBER — maintainer). Commits: 2, both signed off.

Comment thread packages/mocactl/src/subagent.ts Outdated
// Liveness-gated, not a bare non-terminal count: a stale `running` or `unknown` row — exactly
// what an unreconciled crash leaves behind — would otherwise hold a slot for good and wedge
// `spawn` permanently. A child that is gone holds nothing.
// shortcut: an async row has no child to probe, so it holds its slot until `subagents` reads the

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: this comment is accurate — but the consequence is a small wedge worth closing. cmdGet/readLeafResult never call ledger.updateState, so collecting a finished async subagent with get leaves its row non-terminal and it keeps holding a --max-concurrent slot. The natural workflow (spawn --async ×N, get each, spawn more) then refuses at the cap with "N subagents are already running" while every one of them is done, until the user happens to run subagents (its persist loop at :576-580 is the only writer). Two cheap options: have cmdGet record the terminal state it just read (it already opened the row), or reconcile only on the refusal path — read the non-terminal async rows' turns there, which costs a round trip only when the command is about to fail anyway. The PR description already says "subagents or get … records a terminal state"; this is what would make that true.

…c row

`cmdSubagents`'s persist loop was the only writer of a turn's state, so
an async subagent collected with `get` kept its row non-terminal and went
on holding a `--max-concurrent` slot. The natural workflow — `spawn
--async` xN, `get` each, spawn more — then refused at the cap with every
one of those subagents already done, until the user happened to run
`subagents`.

`readLeafResult` already opens the ledger row to pick its backend, so it
writes the state back when the read is terminal and differs from the row.
The sync path needs none of this: its detached worker records its own
outcome.

Refs rossoctl#381
Assisted-By: Claude (Anthropic AI) <[email protected]>

Signed-off-by: cwiklik <[email protected]>
@cwiklik

cwiklik commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

Addressed in 6472077 — took the first option: readLeafResult already opens the ledger row to pick its backend, so it now writes the terminal state back when the read is terminal and differs from the row. Scoped to async rows (record.turnId !== undefined); the sync path's detached worker still records its own outcome.

That also makes the PR description's "the slot clears when subagents or get reads the turn" true — it was only subagents before. Two tests added: that get on an async row writes {failed, caps_exceeded} once, and that a sync row gets no write.

@cwiklik
cwiklik merged commit 1d36881 into rossoctl:main Nov 19, 2026
18 checks passed
@pdettori pdettori added this to the v0.11.0 milestone Nov 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-ai-review Request automated AI code review from clawgenti

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants