Repository navigation
feat(mocactl): approve and reject a subagent's gate (#381) - #1010
Conversation
`mocactl approve SESSIONID` and `mocactl reject SESSIONID [--feedback TEXT]`
answer the gate a spawned subagent is parked at, so it carries on. `--gate N`
is optional: at most one gate of a session is pending at a time, so the number
is read off the paused result, and the flag is only for a session this client
cannot read. `--feedback` reaches the model verbatim, capped locally at the
control plane's 4096 bytes because the sync harness bounds it nowhere.
Two resume paths, chosen by the ledger row, because the two dispatch backends
park a gate in different places:
- an async row (`spawn --async`) has a turn record, so
`POST /v1/sessions/{id}/decision` resolves it server-side;
- a sync row re-sends its stored envelope with the decision inline (ADR-0020)
from a fresh detached worker, since the decision route reads the turn store
that a sync `/runs` leaf never writes to.
Three additions the feature needs to be reachable at all:
- `spawn --require-approval`. `run-leaf.ts` arms the gate path only for
`requireApproval` or `decision`, so without this mocactl could never produce
a gated session for `approve` to answer. No server change: `/v1/runs` hands
the body straight to `runLeaf`, and `SubmitTurnRequest` already has the field.
- `get` now reports the gate: its number, its summary and the proposed action,
on `--json` as `gate` and otherwise as three lines ending in the command that
answers it. A caller that cannot see what was asked cannot answer it.
- the async transport stops dropping `result.gateId`, and a ledger row's
`turnId` is now replaced on a decision. Either omission would have shipped a
row that reports `paused` for good after a decision that worked.
The contract test's `sends` check now resolves a `$ref`'d request body, which
`GateDecision` is -- unresolved it would have passed vacuously.
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
clawgenti
left a comment
There was a problem hiding this comment.
Summary
Client half of #393: mocactl approve | reject answers a subagent's gate, spawn --require-approval is what produces one, and get shows its number, summary and proposed action. The dispatch split is drawn in the right place — the ledger row picks the route, not a flag — and the requireApproval vs decision handling was checked against the harness rather than assumed: planLeafGate arms on either (harness/src/run-leaf.ts:692) and registers request_approval for either (:983), so dropping requireApproval on the sync resume is correct and a rejected leaf really can park again.
One must-fix: on the sync path the decision is re-sent without ever checking that the gate it names is still pending, and the harness answers a decision for an already-answered gate by re-deriving the stored decision's continuation — so a repeat or a contradicting answer runs the wrong continuation while the command reports the new one, which the docs added here say exits 1. The rest are test-coverage points on the two async-transport fields this PR adds.
Author: cwiklik (CONTRIBUTOR — returning external)
Areas reviewed: TypeScript (mocactl CLI, subagent, transports, ledger), docs, tests, control-plane contract test
Agent/IDE config (.claude/.vscode): none
Commits: 1 commit, all signed-off: yes
CI status: passing (18 checks)
Generated by RepoMan github-pr-review@235a7f7 (https://github.com/rossoctl/agent-skills/blob/235a7f7620139ee3e4ab0872b8439591fe52e8c1/skills/github-pr-review/SKILL.md).
| ...(opts.feedback !== undefined ? { feedback: opts.feedback } : {}), | ||
| }; | ||
|
|
||
| if (record !== undefined && record.turnId === undefined) { |
There was a problem hiding this comment.
must-fix — on the sync path a decision is re-sent without ever checking that the gate it names is still pending.
The harness has no guard for that case. gateShortCircuit (harness/src/gate.ts:167-190) returns paused/abort only when the decision matches the pending gate; otherwise it returns null, so decideSeed falls through to lastDecision (harness/src/gate.ts:216-219) and planLeafGate hands that to the leaf as the continuation (harness/src/run-leaf.ts:727). With a sync row:
mocactl reject SID --gate 0 --feedback "open a PR instead", thenmocactl approve SID --gate 0: the second printsapproved gate 0 on SID, and the leaf runs the REJECT continuation;mocactl approve SID --gate 0twice: the approved continuation runs twice — a side effect the gate existed to make a human authorise.
The async path is covered twice over by the control plane (gate_not_pending on a gate-id mismatch, packages/control-plane/src/turn-handlers.ts:517, plus the sessionId:gate:N idempotency key at :171). The sync path has neither, so this is the one backend where the docs added in this PR ("Answering a gate that is not pending — already answered, or answered by the deadline sweep — exits 1", docs/harness/how-to/use-mocactl.md:178) is not true.
Suggested fix: guard this branch on the row you already hold. The detached worker writes paused when the leaf parks (runSpawnWorker → terminalFromBody), and both resume paths set it back to running, so record.lastKnownState separates "still parked here" from "already answered from this machine" for free:
if (record.lastKnownState !== 'paused') {
io.err(`the ledger says this subagent is ${record.lastKnownState}, so gate ${gateId} is not pending`);
return 1;
}A row left running by a worker that died before writing paused is the one case --gate legitimately covers, so it needs an escape (skip the guard for unknown only, or an explicit --force). Either way, a test for the refusal belongs beside the others in test/subagent-decide.test.ts.
There was a problem hiding this comment.
Fixed in f25e893 — confirmed real before fixing it: with no pending gate gateShortCircuit returns null, and decideSeed's tail then re-runs the stored decision's continuation, so the leaf acted on the old answer while this command printed the new one.
I took a different fix from the one suggested. record.lastKnownState !== 'paused' is a local proxy that falsely refuses a legitimate decision when the worker died before writing paused. Instead the sync path now always reads the live result, even when --gate names the gate, and --gate becomes a cross-check there: a mismatch is refused with the control plane's own wording (gate 9 is not pending; this session is paused at gate 3), so both backends refuse a stale number alike. The async path still skips the read — the control plane compares the id itself and 409s.
Cost: one extra HTTP read on a human-driven command. Known limit, marked with a shortcut: comment — a sync row whose result has aged out of the store can no longer be answered via --gate, because that read is what makes the number trustworthy. Two tests added: a stale --gate on a sync row, and a --gate decision after the gate was answered (which also asserts the refusal does not offer --gate as an escape hatch there). use-mocactl.md corrected to match.
| ...(result.gate ? { gate: result.gate as LeafResultBody['gate'] } : {}), | ||
| // Carried, not dropped: the id is what a decision must name, and `approve` with no `--gate` | ||
| // reads it from here. Without it an async row's gate could only be answered by guessing. | ||
| ...(typeof result.gateId === 'number' ? { gateId: result.gateId } : {}), |
There was a problem hiding this comment.
suggestion — both fields this PR adds to this file are untested, and one of them is a fix the body calls out.
test/transport-async-turn.test.ts:62 asserts the mapped paused body with toEqual against a fixture whose result carries no gateId, so bodyFromTurn dropping this spread again would pass every suite: the new fakeTurns helper in test/subagent-decide.test.ts stubs readTurnState and never reaches bodyFromTurn. Adding gateId to that fixture's result — and to the expected object — pins the one field approve without --gate depends on for an async row.
Same gap one line up, at line 48 of this file: test/transport-async-turn.test.ts:18-31 asserts submitTurn was called with exactly { async: true, kind: 'prompt', prompt: 'hi' }, and the fixture sets no requireApproval, so a regression that drops that spread submits an ungated async turn — spawn --async --require-approval would run without ever asking. Two words in that fixture make the gate unforgeable there.
There was a problem hiding this comment.
Done in f25e893. submit now sends requireApproval: true in the fixture and the expected body pins it, and the paused-result case carries gateId: 4 through readTurnState — the field approve reads when --gate is omitted, so it was the load-bearing one.
| // same text must be refused on both backends or `--feedback` means two different things. | ||
| if ( | ||
| opts.feedback !== undefined && | ||
| Buffer.byteLength(opts.feedback, 'utf8') > GATE_FEEDBACK_BYTES |
There was a problem hiding this comment.
nit — the bound test next door uses 'x'.repeat(GATE_FEEDBACK_BYTES + 1), where one character is one byte, so it cannot tell this byte check from a feedback.length check. The difference is reachable: 'é'.repeat(2049) is 2049 characters and 4098 bytes, so a character check would let it through to a control plane that answers 400 invalid_request (docs/api/openapi.yaml:339: "The server's bound is 4096 BYTES, not characters"). A second case at 2049 × 'é' pins the unit.
There was a problem hiding this comment.
Done in f25e893: a 'é'.repeat(2049) case — 2049 characters, 4098 bytes — so it is under the bound counted in characters and over it counted in bytes. A character-counting implementation now fails the suite.
clawgenti
left a comment
There was a problem hiding this comment.
Summary
Client half of #393: mocactl approve | reject answers a subagent's gate, spawn --require-approval is what produces one, and get shows its number, summary and proposed action. The dispatch split is drawn in the right place — the ledger row picks the route, not a flag — and the requireApproval vs decision handling was checked against the harness rather than assumed: planLeafGate arms on either (harness/src/run-leaf.ts:692) and registers request_approval for either (:983), so dropping requireApproval on the sync resume is correct and a rejected leaf really can park again.
One must-fix: on the sync path the decision is re-sent without ever checking that the gate it names is still pending, and the harness answers a decision for an already-answered gate by re-deriving the stored decision's continuation — so a repeat or a contradicting answer runs the wrong continuation while the command reports the new one, which the docs added here say exits 1. The rest are test-coverage points on the two async-transport fields this PR adds.
Author: cwiklik (CONTRIBUTOR — returning external)
Areas reviewed: TypeScript (mocactl CLI, subagent, transports, ledger), docs, tests, control-plane contract test
Agent/IDE config (.claude/.vscode): none
Commits: 1 commit, all signed-off: yes
CI status: passing (18 checks)
Generated by RepoMan github-pr-review@235a7f7 (https://github.com/rossoctl/agent-skills/blob/235a7f7620139ee3e4ab0872b8439591fe52e8c1/skills/github-pr-review/SKILL.md).
| ...(opts.feedback !== undefined ? { feedback: opts.feedback } : {}), | ||
| }; | ||
|
|
||
| if (record !== undefined && record.turnId === undefined) { |
There was a problem hiding this comment.
must-fix — on the sync path a decision is re-sent without ever checking that the gate it names is still pending.
The harness has no guard for that case. gateShortCircuit (harness/src/gate.ts:167-190) returns paused/abort only when the decision matches the pending gate; otherwise it returns null, so decideSeed falls through to lastDecision (harness/src/gate.ts:216-219) and planLeafGate hands that to the leaf as the continuation (harness/src/run-leaf.ts:727). With a sync row:
mocactl reject SID --gate 0 --feedback "open a PR instead", thenmocactl approve SID --gate 0: the second printsapproved gate 0 on SID, and the leaf runs the REJECT continuation;mocactl approve SID --gate 0twice: the approved continuation runs twice — a side effect the gate existed to make a human authorise.
The async path is covered twice over by the control plane (gate_not_pending on a gate-id mismatch, packages/control-plane/src/turn-handlers.ts:517, plus the sessionId:gate:N idempotency key at :171). The sync path has neither, so this is the one backend where the docs added in this PR ("Answering a gate that is not pending — already answered, or answered by the deadline sweep — exits 1", docs/harness/how-to/use-mocactl.md:178) is not true.
Suggested fix: guard this branch on the row you already hold. The detached worker writes paused when the leaf parks (runSpawnWorker → terminalFromBody), and both resume paths set it back to running, so record.lastKnownState separates "still parked here" from "already answered from this machine" for free:
if (record.lastKnownState !== 'paused') {
io.err(`the ledger says this subagent is ${record.lastKnownState}, so gate ${gateId} is not pending`);
return 1;
}A row left running by a worker that died before writing paused is the one case --gate legitimately covers, so it needs an escape (skip the guard for unknown only, or an explicit --force). Either way, a test for the refusal belongs beside the others in test/subagent-decide.test.ts.
There was a problem hiding this comment.
Fixed in f25e893 — confirmed real before fixing it: with no pending gate gateShortCircuit returns null, and decideSeed's tail then re-runs the stored decision's continuation, so the leaf acted on the old answer while this command printed the new one.
I took a different fix from the one suggested. record.lastKnownState !== 'paused' is a local proxy that falsely refuses a legitimate decision when the worker died before writing paused. Instead the sync path now always reads the live result, even when --gate names the gate, and --gate becomes a cross-check there: a mismatch is refused with the control plane's own wording (gate 9 is not pending; this session is paused at gate 3), so both backends refuse a stale number alike. The async path still skips the read — the control plane compares the id itself and 409s.
Cost: one extra HTTP read on a human-driven command. Known limit, marked with a shortcut: comment — a sync row whose result has aged out of the store can no longer be answered via --gate, because that read is what makes the number trustworthy. Two tests added: a stale --gate on a sync row, and a --gate decision after the gate was answered (which also asserts the refusal does not offer --gate as an escape hatch there). use-mocactl.md corrected to match.
| ...(result.gate ? { gate: result.gate as LeafResultBody['gate'] } : {}), | ||
| // Carried, not dropped: the id is what a decision must name, and `approve` with no `--gate` | ||
| // reads it from here. Without it an async row's gate could only be answered by guessing. | ||
| ...(typeof result.gateId === 'number' ? { gateId: result.gateId } : {}), |
There was a problem hiding this comment.
suggestion — both fields this PR adds to this file are untested, and one of them is a fix the body calls out.
test/transport-async-turn.test.ts:62 asserts the mapped paused body with toEqual against a fixture whose result carries no gateId, so bodyFromTurn dropping this spread again would pass every suite: the new fakeTurns helper in test/subagent-decide.test.ts stubs readTurnState and never reaches bodyFromTurn. Adding gateId to that fixture's result — and to the expected object — pins the one field approve without --gate depends on for an async row.
Same gap one line up, at line 48 of this file: test/transport-async-turn.test.ts:18-31 asserts submitTurn was called with exactly { async: true, kind: 'prompt', prompt: 'hi' }, and the fixture sets no requireApproval, so a regression that drops that spread submits an ungated async turn — spawn --async --require-approval would run without ever asking. Two words in that fixture make the gate unforgeable there.
There was a problem hiding this comment.
Done in f25e893. submit now sends requireApproval: true in the fixture and the expected body pins it, and the paused-result case carries gateId: 4 through readTurnState — the field approve reads when --gate is omitted, so it was the load-bearing one.
| // same text must be refused on both backends or `--feedback` means two different things. | ||
| if ( | ||
| opts.feedback !== undefined && | ||
| Buffer.byteLength(opts.feedback, 'utf8') > GATE_FEEDBACK_BYTES |
There was a problem hiding this comment.
nit — the bound test next door uses 'x'.repeat(GATE_FEEDBACK_BYTES + 1), where one character is one byte, so it cannot tell this byte check from a feedback.length check. The difference is reachable: 'é'.repeat(2049) is 2049 characters and 4098 bytes, so a character check would let it through to a control plane that answers 400 invalid_request (docs/api/openapi.yaml:339: "The server's bound is 4096 BYTES, not characters"). A second case at 2049 × 'é' pins the unit.
There was a problem hiding this comment.
Done in f25e893: a 'é'.repeat(2049) case — 2049 characters, 4098 bytes — so it is under the bound counted in characters and over it counted in bytes. A character-counting implementation now fails the suite.
`--gate N` skipped the live read, and the sync resume path has nothing behind it that checks the number: `gate.ts`'s `decideSeed` answers a decision for an already-answered gate by re-running the STORED decision's continuation. So `mocactl reject SID --gate 3` after an approve printed "rejected gate 3" while the leaf went ahead with what it had been approved for. On a sync row the paused result is now always read and `--gate` is a cross-check, refused on a mismatch with the same wording the control plane's 409 uses. The async path still skips the read: the control plane compares the id with the pending one itself. Also pin `requireApproval` and the paused result's `gateId` in the async transport test, and count feedback bytes with a multibyte case. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
clawgenti
left a comment
There was a problem hiding this comment.
Summary
The delta at f25e893 is a direct response to the previous pass, and it is the right shape: the sync path now reads the pending gate even when --gate is given, refuses a wrong id in the control plane's own wording, and the byte-bound and async-transport tests that were asked for are there and bite — I mutation-checked both guards at head (dropping || syncRow !== undefined fails both new sync tests; dropping the id comparison fails the stale-gate test). One must-fix remains, and it is the same property the previous pass raised: the value being read is not live. /runs/status serves the last terminal record, which stays paused at the same gate id until the resumed run parks or finishes, so an already-answered gate is still accepted for the whole life of the resume, not just a race window. The rest is a docs inconsistency the delta left behind.
The PR-body sentence "the flag is only for a session this client cannot read (one spawned on another machine, or whose result has aged out)" is stale after f25e893: on a sync row an unreadable result can no longer be answered with --gate at all. Worth folding the how-to's wording into the body so the description matches the code.
Author: cwiklik (CONTRIBUTOR — returning external)
Areas reviewed: TypeScript (mocactl CLI, subagent, transports, ledger, API types), docs, tests
Agent/IDE config (.claude/.vscode): none
Commits: 2 commits, all signed-off: yes
CI status: passing (18 checks)
Verified at f25e893 in a worktree: test/subagent-decide.test.ts + test/transport-async-turn.test.ts 26/26; full mocactl suite 2198 passed / 7 skipped with 2 failures in test/sbx-up.test.ts plus a file-level failure in test/sbx-exec.test.ts; the rm/chmod failure and the sbx-exec file failure reproduce at origin/main 3b53f157, and the push-subdirectory failure did not recur on the base run (root/environment-shaped, not this PR); tsc --noEmit clean for the package; prettier clean. The double-approve probe and both mutations were reverted and deleted.
Generated by RepoMan github-pr-review@235a7f7 (https://github.com/rossoctl/agent-skills/blob/235a7f7620139ee3e4ab0872b8439591fe52e8c1/skills/github-pr-review/SKILL.md).
| if (typeof read === 'number') return read; | ||
| const status = read === 'queued' ? 'queued' : read.status; | ||
| const pending = read === 'queued' ? undefined : read.gateId; | ||
| if (status !== 'paused' || typeof pending !== 'number') { |
There was a problem hiding this comment.
must-fix — the read this branch adds is not live on a sync row, so an already-answered gate is still accepted while the resumed run is in flight.
GET /runs/status answers from the Redis result record (packages/server/src/server.ts:1247-1277), and that record is written only after runLeaf returns (server.ts:1219). A sync resume is a new /v1/runs invocation, so from the moment mocactl approve forks the worker until the resumed run parks or finishes, the record still says paused at the same gate id. The read therefore passes this guard for the whole resumed run: mocactl approve SID a second time (or a shell retry of the first, or the answer mocactl approve SID hint get prints from the same stale record) forks a second worker, and the harness re-derives the stored decision's continuation when the gate is no longer pending — decideSeed's lastDecision branch (harness/src/gate.ts:216-219), pinned by "already-decided this gate (double resume) → seed continuation" (harness/test/gate.test.ts:181-190). So the approved action runs twice, and docs/harness/how-to/use-mocactl.md:181-183 ("Answering a gate that is not pending — already answered ... exits 1") is still not true in that window. The test added here covers only the state after the resumed run has finished (transport returns responded).
Probe (throwaway, deleted): two cmdDecide calls on one sync row whose reader returns the stale paused record printed PROBE r1=0 r2=0 forks=2 ledger-state-after-first=running childPid=1002; the same second call once the record had flipped to responded was refused (CONTROL r3=1).
Suggested fix: add the ledger check alongside the read — for a sync row the ledger is on this machine by definition, and resumeSyncRow flips the row to running before the command returns (packages/mocactl/src/subagent.ts:1256):
if (syncRow !== undefined && syncRow.lastKnownState !== 'paused') {
io.err(`the ledger says this subagent is ${syncRow.lastKnownState}, so gate ${gateId} is not pending`);
return 1;
}Keep the read for the id — it is what refuses a --gate naming another gate. The escape case is a row stranded running by a worker that died before writing paused: skip the guard when record.childPid is set but the process is gone (or offer --force), and put a test for the refusal and for the escape beside the others.
There was a problem hiding this comment.
Right, and the window is the whole resume, not a race — fixed in 2c16bc6. writeResult on the sync path runs only after runLeaf returns (packages/server/src/server.ts:1219), so the store keeps serving the paused record for as long as the resume takes.
The local row is the one thing that does know, which is where the previous pass's suggestion was pointing: resumeSyncRow re-points the row at the resume's worker. So a sync row is now refused when it is not paused and its child is alive — session 'X' has a run in flight (pid N); a gate can only be answered while the subagent is parked at it. Gating on liveness rather than on the row's state alone keeps the false-refusal case out: a worker that died before writing a result leaves running behind, and that row still falls through to the read, so its gate stays answerable. Two tests, one for each side of that.
Also covers the first-run case for free: a spawn that has not reached its gate yet is refused by the same check rather than by a "not paused" message a few lines later.
| let a subagent paused for approval go ahead; prints | ||
| the turn it resumed as ('mocactl get SESSIONID' | ||
| shows what it proposed and the number --gate takes, | ||
| needed only when this client cannot read that; |
There was a problem hiding this comment.
nit — this usage line still says --gate is "needed only when this client cannot read that", which the change makes false on a sync row: there the read is mandatory, so a result that cannot be read can no longer be answered with --gate at all. The how-to now says exactly that (docs/harness/how-to/use-mocactl.md:176-178), and this string is copied verbatim into docs/harness/reference/cli-mocactl.md:119. Suggested: "...needed only for an --async row whose result this client cannot read; on a sync row it is checked against the live gate".
There was a problem hiding this comment.
Fixed in 2cd1326: the line now says the number "is read off the paused run when the flag is left out" rather than claiming the flag is only for an unreadable session. Reference doc regenerated with UPDATE_MOCACTL_REFERENCE=1, and the PR body's matching sentence is updated too.
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
Summary
Re-review at f25e8938, one commit past e8a2aabd. That commit closes the sync-path finding from the last review properly: the paused result is now always read on a sync row, --gate is a cross-check refused with the control plane's own wording (gate 9 is not pending; this session is paused at gate 3), and the two new tests cover a stale --gate and a decision against an already-answered gate. The ledger turnId replacement, the 409 hint naming the spawning machine, and the 4096-byte feedback bound (turn-record.ts:536) all check out.
One must-fix, unchanged by that commit and now harder to see: the async reader takes the gate id from result.gateId, but the turn-status route nests it at result.gate.gateId. The async worker persists through toResultRecord (harness/src/leaf-result-store.ts:77-87, called at harness/src/leaf-job-runner.ts:435-438), which copies the id into gate: { gateId, ... } and writes no top-level one; projectLeafResult passes that record through with only the gate's two strings clipped. The control plane's own pausedGateId says so explicitly (turn-handlers.ts:131-143: "gate.gateId and NOT a top-level gateId"), and /runs/status (packages/server/src/server.ts:1262-1265) is the only place the flat field exists — which is why the sync read added here works. So for a spawn --async row, mocactl get prints no gate and mocactl approve SESS without --gate exits 1 ("not paused at a gate") — the documented primary flow for the backend the PR body says any logged-in machine can answer. --gate N works, because the control plane compares the id itself. The test added in f25e8938 pins the flat shape, so CI is green against the bug.
No prompt-injection attempts found in the PR title, body, diff, commit messages, comments or file contents.
Author: cwiklik (MEMBER — maintainer)
Areas reviewed: TypeScript (mocactl CLI, subagent, transports, ledger), docs, tests, control-plane contract test
Agent/IDE config (.claude/.vscode): none
Commits: 2 commits, all signed-off: yes
CI status: 15 passing, 3 pending (check, k8s-kind-e2e, deploy-scripts)
| ...(result.gate ? { gate: result.gate as LeafResultBody['gate'] } : {}), | ||
| // Carried, not dropped: the id is what a decision must name, and `approve` with no `--gate` | ||
| // reads it from here. Without it an async row's gate could only be answered by guessing. | ||
| ...(typeof result.gateId === 'number' ? { gateId: result.gateId } : {}), |
There was a problem hiding this comment.
must-fix — the async row's gate id is nested under gate, so get and approve never see it.
GET /v1/sessions/{id}/turns/{turnId} returns the stored leaf result, and the async worker stores it through toResultRecord (harness/src/leaf-result-store.ts:41-90, called at harness/src/leaf-job-runner.ts:435-438). For a paused result that builds gate: { gateId: result.gateId, summary, proposed_action } and copies no top-level gateId; projectLeafResult (packages/control-plane/src/turn-result.ts) then passes the record through, clipping only the gate's two strings. The control plane's own pausedGateId documents the shape in so many words (packages/control-plane/src/turn-handlers.ts:131-143): "gate.gateId and NOT a top-level gateId ... that shape exists only on the in-process LeafResult a synchronous /runs caller is handed back" — and /runs/status is that caller (packages/server/src/server.ts:1262-1265), which is why the sync read added in this PR works.
So on a real spawn --async row this spread never fires, bodyFromTurn returns gate with no sibling id, and:
mocactl get SESSprints no gate lines and emits nogateon--json(cmdGetrequirestypeof raw.gateId === 'number',src/subagent.ts:947-953);mocactl approve SESS/reject SESSwithout--gateexits 1 ("is paused, not paused at a gate",src/subagent.ts:1163-1168) — the flowdocs/harness/how-to/use-mocactl.mddocuments as the normal one.
--gate N is unaffected (the control plane compares the id itself), so the feature works, but the advertised read-it-off-the-result path does not.
Suggest reading the id where it lives, keeping the flat fallback for the sync body:
const g = result.gate as { gateId?: unknown } | undefined;
const gateId =
typeof result.gateId === 'number'
? result.gateId
: typeof g?.gateId === 'number'
? g.gateId
: undefined;The test added in f25e8938 (test/transport-async-turn.test.ts:74-92) puts gateId at the top level of result, so the suite now actively pins the shape the server never sends — the trap packages/control-plane/test/helpers/deps.ts:19-24 calls out by name.
There was a problem hiding this comment.
Confirmed and fixed in 2c16bc6. I had checked /runs/status (server.ts:1267), found the flat field there, and wrongly concluded both paths served it — the async path never does. pausedGateId's comment and docs/api/openapi.yaml:323 both say result.gate.gateId, so the spec was right and the client was wrong.
bodyFromTurn now lifts the id out of gate into the flat field the sync body has, so one LeafResultBody shape still covers both backends and cmdGet/cmdDecide need no per-path branch. With it, mocactl get prints the gate and mocactl approve SESS works without --gate on an async row.
| workspace?: Record<string, unknown>; | ||
| gate?: Record<string, unknown>; | ||
| /** The pending gate's id, which a decision must name. Beside `gate`, not inside it. */ | ||
| gateId?: number; |
There was a problem hiding this comment.
suggestion — this field is not part of the turn-status contract.
TurnStatus['result'].gate is typed Record<string, unknown>, and the new sibling gateId?: number declares a field no writer sends on that route (see the comment on async-turn.ts:117). Because the real id sits inside the loosely-typed gate, the compiler cannot point at the mistake. Typing it as gate?: { gateId: number; summary: string; proposed_action: string } would make async-turn.ts:117 fail to compile until it reads the right place. Drop gateId here, or keep it only on LeafResultBody, which is the sync shape leaf-turn.ts already declares.
There was a problem hiding this comment.
Removed in 2c16bc6. gate is now typed { gateId?: number; summary?: string; proposed_action?: string } with a comment saying the id is nested there and that the flat field exists only on the sync /runs/status body — so the next reader finds the shape in the type rather than the wrong one.
| status: 'paused', | ||
| reason: 'gate', | ||
| // `approve` reads the id from here when `--gate` is omitted, so it must survive. | ||
| gateId: 4, |
There was a problem hiding this comment.
suggestion — the fixture matches the bug, not the server.
This result object is fed straight to bodyFromTurn, but getTurn never returns a top-level gateId: the stored record has gate: { gateId, summary, proposed_action }. Move gateId: 4 inside gate (and keep the expectation's top-level gateId: 4 only if the mapping is fixed to hoist it, per the comment on async-turn.ts:117). As written the two tests agree with each other and neither agrees with the API.
There was a problem hiding this comment.
…ision mid-resume Two holes the last pass left, both found by review of f25e893. The async reader took the gate id from `result.gateId`, which no writer sets: `toResultRecord` nests it (`gate.gateId`) and `projectLeafResult` passes that through, as `pausedGateId` and openapi both say. The flat field exists only on the sync `/runs/status` body. So `mocactl get` printed no gate for an `--async` row and `mocactl approve SESS` exited 1 — the documented primary flow for that backend. The id is now lifted out of `gate` into the flat field the sync body has, so one shape still covers both paths, and the type says where it lives. The sync cross-check read a result that is not live: `/runs/status` serves the paused record for the whole life of a resume, because the worker writes its own result only when the leaf returns. A second, contradicting decision was accepted for that whole window. A live child is the signal that can tell, so a sync row with one is refused and names the pid. Gated on liveness rather than on the row's state alone, so a worker that died before writing a result still falls through and leaves the gate answerable. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
It said the number was "needed only when this client cannot read that", which has not been true on the sync path since f25e893: the paused run is read either way and the flag is a cross-check. Say what it does instead. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
clawgenti
left a comment
There was a problem hiding this comment.
Summary
The two commits since the last pass close both findings from it. 2c16bc6b reads the async gate id from result.gate.gateId, which is where toResultRecord actually nests it (harness/src/leaf-result-store.ts:81-88) and where projectLeafResult leaves it (packages/control-plane/src/turn-result.ts:129-130), so get and approve without --gate now work on an async row, and the TurnStatus type says the same thing. syncRow's new guard refuses a decision while a resume is in flight — the one case /runs/status cannot show, because it serves the paused record for the whole life of the resume — and the two tests cover both sides of it (live child refused, dead child falls through). I re-ran the two touched suites at head: 28/28 pass.
One must-fix, newly reachable from the async fix: at MOCA_TURN_SUMMARY_BYTES=0 the projection keeps gate.gateId and drops the gate's two strings, cmdGet now renders the gate, and it throws a TypeError instead of reporting the session.
Author: cwiklik (CONTRIBUTOR — returning external)
Areas reviewed: TypeScript (mocactl: subagent.ts, transport/async-turn.ts, api/types.ts), docs, tests
Agent/IDE config (.claude/.vscode): none (checked the PR's changed-file list)
Commits: 4 in the PR, all signed off: yes
CI status: pending at 2cd13269 — DCO passed, 15 queued, no Go/TS job finished
Not checked:
- The full mocactl suite,
make lintand the Docker lint job — I ran only the two touched test files plustsc --noEmit(no errors inpackages/mocactl; the five it reports are inpackages/sandbox-client, whosenode_modulesI did not link into the worktree) - A live sync/async deployment —
deploy/composeneeds a Docker daemon this sandbox does not have
Verified by: vitest run test/subagent-decide.test.ts test/transport-async-turn.test.ts at 2cd13269 (28/28); tsc --noEmit; a throwaway cap-0 probe (below), run and then deleted, with the worktree removed afterwards.
Generated by repoman github-pr-review@af425c8.
| raw.gate && typeof raw.gateId === 'number' | ||
| ? { | ||
| gateId: raw.gateId, | ||
| summary: sanitizeRemote(raw.gate.summary), |
There was a problem hiding this comment.
must-fix — At MOCA_TURN_SUMMARY_BYTES=0 — a supported setting (docs/reference/configuration.md: "0 omits all four keys") — projectLeafResult keeps gate.gateId and deletes summary and proposed_action (packages/control-plane/src/turn-result.ts:146-152). This block now renders the gate, which is what the async id lift buys, and sanitizeRemote(undefined) throws:
TypeError: The "str" argument must be of type string. Received undefined
Probe at 2cd13269 (deleted after): projectLeafResult(pausedRecord, 0) fed through bodyFromTurn's shape into cmdGet threw the TypeError. Positive control, same probe at 2048: status paused | gate 4 wants to push | propose git push origin main | answer mocactl approve sess-abc. Before 2c16bc6b there was no flat gateId on an async row, so this expression was never reached; the fix makes the crash reachable — mocactl get is the documented way to see what a gate is asking.
Suggested fix: treat the two strings as optional, which is what api/types.ts now declares:
summary: typeof raw.gate.summary === 'string' ? sanitizeRemote(raw.gate.summary) : '',Why it matters now: bodyFromTurn's result.gate as LeafResultBody['gate'] cast re-asserts the two fields as required, so the compiler cannot flag this dereference — the type change and the consumer disagree at runtime instead.
There was a problem hiding this comment.
Confirmed and fixed in 7d4224f. You are right that 2c16bc6 is what made it reachable: before the id lift there was no flat gateId on an async row, so the raw.gate && typeof raw.gateId === 'number' arm never ran, and clipFields keeps gateId while deleting both strings at maxBytes === 0.
The strings are now optional on LeafResultBody.gate, read as raw.gate.summary ?? '', and the human output drops the summary and the whole propose line when they are empty — the id is the part a decision needs, so the gate is still reported rather than hidden. --json keeps stable keys. New test in subagent-get.test.ts: a paused body with gate: {} and gateId: 7 prints gate 7, no propose line, and the answer hint, exit 1.
| // before writing a result still falls through and leaves the gate answerable. | ||
| if ( | ||
| syncRow !== undefined && | ||
| syncRow.lastKnownState !== 'paused' && |
There was a problem hiding this comment.
suggestion — This guard is a read-then-act on a lock-free ledger, and the row only becomes running inside resumeSyncRow, after the fork (subagent.ts:1275-1279). Between this check and that write is a /runs/status round trip, so two decisions started in that window both pass — each sees either paused (guard skipped) or a dead childPid (skipped) — and both fork a resume and exit 0. The harness answers an already-answered gate from the stored decision's continuation (harness/src/gate.ts decideSeed), so the losing decision is not applied while its command reports success: the shape the last two passes were about, now confined to concurrent invocation. Concrete case: mocactl approve S & mocactl approve S in one shell.
Suggested fix: write the answer into the row before forking — a running update whose stateDetail names the gate being answered — and have this guard refuse when that marker is present and the row has not returned to paused. Otherwise, the how-to's "a second decision ... is refused" sentence should say it holds only once the first decision's row write has landed.
There was a problem hiding this comment.
Real, and I took the second option you offered. Moving the row write before the fork would only shrink the window — the status read and the token mint stay inside it — so it would trade a correct description for a narrower race. Closing it properly needs either a lock file here or gate idempotency on the sync path in the harness (the async path already keys on ${sessionId}:gate:${gateId}), and neither belongs in this PR.
So in 7d4224f the guard carries a shortcut: comment naming the trigger (mocactl approve S & mocactl approve S), what it does cover (the sequential case, which is the one a human hits), and the upgrade. The how-to now says the refusal holds once the first decision's run has started, and spells out that two decisions started at the same instant can both get through.
At `MOCA_TURN_SUMMARY_BYTES=0` the control plane keeps `gate.gateId` and deletes `summary` and `proposed_action` (`clipFields`), so `cmdGet` reached `sanitizeRemote(undefined)` and threw a TypeError instead of printing the gate. Reachable only since 2c16bc6, which is what started lifting the async id onto the body. The strings are now optional on `LeafResultBody.gate`, default to empty, and the human output drops the summary and the whole `propose` line when they are absent. `--json` keeps stable keys. Also names the concurrent-decision window at the in-flight guard with a `shortcut:` comment, and corrects the how-to: the refusal holds once the first decision's row write has landed, not for two decisions started at the same instant. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
clawgenti
left a comment
There was a problem hiding this comment.
Summary
The head adds one commit (7d4224ff) over 2cd13269, and it closes the must-fix from the last pass: at MOCA_TURN_SUMMARY_BYTES=0 the projection deletes the gate's two strings and keeps gate.gateId (packages/control-plane/src/turn-result.ts:141-160), and cmdGet now renders the gate from the id alone instead of handing sanitizeRemote an undefined. The runtime lines (gate 7, no propose line) and the --json shape match that, and the new test pins exactly the cap-0 body.
Verified at 7d4224ff: vitest run test/subagent-get.test.ts test/subagent-decide.test.ts — 44/44 pass; tsc --noEmit clean in packages/mocactl; read of clipFields and bodyFromTurn for the two claims. The async gate id still comes from result.gate.gateId (src/transport/async-turn.ts:118), and the documented two-decisions race is now stated at the guard and in the how-to (docs/harness/how-to/use-mocactl.md:183-186), which matches the read-then-act on the ledger.
One nit inline. Nothing blocking.
Author: cwiklik (CONTRIBUTOR — returning external)
Areas reviewed: TypeScript (mocactl subagent.ts, transport/async-turn.ts, control-plane turn-result.ts), docs, tests
Agent/IDE config (.claude/.vscode): none (no matches in the PR diff, renames included)
Commits: 5 in the PR, all signed off: yes (DCO passes)
CI status: queued at 7d4224ff — DCO passed, 15 jobs still queued (dependency-review, docs, lint, k8s-kind-e2e, …)
Not checked:
make lintand the Docker lint job — not run here; no Dockerfile is touched- A live sync/async deployment —
deploy/composeneeds a Docker daemon this sandbox does not have
Verified by: the two vitest suites at head (44/44), tsc --noEmit, and a read of clipFields/bodyFromTurn. The worktree was removed afterwards.
Generated by repoman github-pr-review@af425c8.
| // Both strings can be absent: at `MOCA_TURN_SUMMARY_BYTES=0` the control plane drops them | ||
| // and keeps the id. The id is the part a decision needs, so report the gate either way | ||
| // rather than hide it -- and never hand `sanitizeRemote` an undefined. | ||
| summary: sanitizeRemote(raw.gate.summary ?? ''), |
There was a problem hiding this comment.
nit — --json always carries both strings, empty when the projection dropped them.
The text output drops the line when the string is empty (line 975), but the JSON object keeps "summary": "" and "proposed_action": "". LeafResultBody.gate marks both optional (src/transport/leaf-turn.ts:46), so a consumer cannot tell "the control plane dropped it" from "the gate said nothing".
Suggested fix: spread them only when non-empty, the same way reason/message are spread two lines above:
gateId: raw.gateId,
...(raw.gate.summary ? { summary: sanitizeRemote(raw.gate.summary) } : {}),
...(raw.gate.proposed_action ? { proposed_action: sanitizeRemote(raw.gate.proposed_action) } : {}),No behaviour change for the CLI itself; it keeps the JSON shape honest against the type.
There was a problem hiding this comment.
Taken as suggested, in b7895c2. You are right that the type and the body disagreed: with both strings optional on LeafResultBody.gate, "summary": "" reads as "the gate said nothing" rather than "the projection dropped it", and the two lines above already spread reason/message conditionally.
So both are now spread only when non-empty, which also makes the text output's checks read off presence rather than emptiness. New test: gate: { proposed_action: 'push' } with gateId: 7 yields exactly { gateId: 7, proposed_action: 'push' } on --json. Text output unchanged; make typecheck clean, 27/27 in subagent-get.
`LeafResultBody.gate` marks both strings optional, so an empty one in the JSON reads as "the gate said nothing" rather than "the projection dropped it". Spread them only when present, as `reason` and `message` already are two lines above. Text output is unchanged. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
Re-review at b7895c24, two commits past the 2cd13269 head. They close both open items and the one new nit.
clawgenti's must-fix (MOCA_TURN_SUMMARY_BYTES=0crash):clipFieldsdeletes the gate's two model-written strings at a 0 cap and keepsgate.gateId(packages/control-plane/src/turn-result.ts:116), and every status read goes throughprojectLeafResult(turn-handlers.ts:585). Since2c16bc6blifted the id out ofresult.gate.gateId, the oldsanitizeRemote(undefined)became reachable.LeafResultBody.gatenow declares both strings optional (transport/leaf-turn.ts:43-47);cmdGetnever handssanitizeRemotean undefined, because the two strings are spread only when present (subagent.ts:949-960); the human output drops the summary and theproposeline when they are empty while still printing the id and theanswerhint (:974-978); and--jsonleaves a dropped string out entirely rather than emitting"", asreason/messagealready do two lines above.b7895c24makes that last part true and pins it with a new case (subagent-get.test.ts:426-437:{status:'paused', gateId:7, gate:{proposed_action:'push'}}→{gateId:7, proposed_action:'push'}), which is exactlyclawgenti's nit at7d4224ff. The original repro test still holds ({…, gate:{}}→gate 7, nopropose, answer hint, exit 1). No other client code dereferences those two strings.- The check-then-act suggestion: resolved by documenting the residual race rather than moving the row write — the
shortcut:comment names the trigger and the upgrade (subagent.ts:1138-1145) and the how-to says two simultaneous decisions can both get through (docs/harness/how-to/use-mocactl.md:182-188). I verified the row turnsrunningonly insideresumeSyncRow, after the fork (subagent.ts:1275-1280), so the wording is accurate. The real fix needs harness-side idempotency, out of scope here.
The rest of the branch is unchanged from the verified 2cd13269 round: the async id lift in bodyFromTurn (transport/async-turn.ts:112-118) matches toResultRecord's nested record (harness/src/leaf-result-store.ts:77-87), and the sync liveness guard and its two tests still hold. No further comments.
Author: cwiklik (MEMBER — maintainer)
Areas reviewed: TypeScript (packages/mocactl CLI, subagent, transports, ledger), tests, docs
Agent/IDE config (.claude/.vscode): none
Commits: 6 commits, all signed off
CI status: DCO passing; the other 15 checks queued at this head (pushed 14:34 UTC), none failing
Closes scope item 6 of #381.
mocactl approve SESSIONIDandmocactl reject SESSIONID [--feedback TEXT]answer the gate aspawned subagent is parked at, so it carries on.
--gate Nis optional: at most one gate of a session is pending at a time, so the number is readoff the paused result. On an async row the flag is a short cut for a session this client cannot
read (one spawned on another machine, or whose result has aged out) and the control plane checks
the number itself. On a sync row it is a cross-check, not a short cut: the paused result is
still read, because nothing behind the command would catch a stale number -- the harness answers a
decision for an already-answered gate by re-running the stored decision's continuation. A sync row
whose result has aged out therefore cannot be answered with
--gateat all, and a second decisiontaken once the first one's run has started is refused and names the pid (two started at the same
instant can both get through -- a documented limit, marked at the guard).
--feedbackreaches the model verbatim, cappedlocally at the control plane's
GATE_FEEDBACK_BYTES(4096) because the sync harness'svalidateDecisionbounds it nowhere -- the same text must be refused on both backends or the flagmeans two different things. Exit
0answered,1refused,2usage.Two resume paths, chosen by the ledger row
The two dispatch backends park a gate in different places and neither route resolves the other's:
spawn --async) has a turn record, soPOST /v1/sessions/{id}/decisionresolves it: the control plane copies the envelope and queues the resume;
decisioninline (ADR-0020) from a freshdetached worker, because the decision route reads the turn store that a sync
/runsleaf neverwrites to. On a deployment without
SH_ASYNC_DRAIN-- which is every deploy target today -- anasync-only command would 409 on every real session.
A sync row is therefore resumed only from the machine that spawned it, which holds its envelope.
The 409 handler says so when there is no local row, since that is the commonest way to hit it.
Three additions the feature needs to be reachable
spawn --require-approval.harness/src/run-leaf.ts:692arms the gate path only forrequireApprovalordecision, so before this mocactl could not produce a gated session at alland
approvewould have had no input. No server change:/v1/runshands the body straight torunLeaf, andSubmitTurnRequestalready carried the field.getreports the gate -- its number, its summary and the proposed action; on--jsonasgate, otherwise three lines ending in the command that answers it. A caller that cannot seewhat was asked cannot answer it. At
MOCA_TURN_SUMMARY_BYTES=0the projection keepsonly the id, so both gate strings are optional: the lines they would fill are dropped, and on
--jsonthe keys are left out rather than emitted empty.bodyFromTurnreads the gate id out ofresult.gate.gateId,where the stored record nests it, and lifts it to the flat field the sync body has -- without
that an async row's gate could only be answered by guessing; and
LedgerRecord.turnIdwaswrite-once, so an approved async row would have reported
pausedfor good after a decision thatworked.
Also
The contract test's
sendscheck now resolves a$ref'd request body, whichGateDecisionis --unresolved it passed vacuously. The deref breaks no other route, so nothing else was relying on it.
abortis deliberately not a third verb: ending a subagent ismocactl cancel's job.Verification
make typecheckclean;make lintclean exceptLint Dockerfiles, which needs a Docker daemonthis machine does not have running (no Dockerfile touched).
including 18 new
subagent-decidetests(both backends, the inferred gate, a
gate_not_pendingrefusal leaving the row alone, feedbackrefused at the bound and accepted on it in bytes rather than characters, an unrebuildable
envelope, a failed fork leaving the row
paused, a stale--gate, a decision against ananswered gate, a decision refused mid-resume and one let through when the stale row's worker is
gone, a gate reported with no summary, a dropped string left out of
--json) and 3 newCLI-routing tests (
--gate 0surviving the parse, the flag guards).deploy/composeneeds Docker, so the sync resume's continuation is verified byunit tests and by reading
run-leaf.ts, not observed end to end.Docs:
docs/harness/how-to/use-mocactl.mdgains the gate flow, the two resume paths and the--jsonshapes;docs/harness/reference/cli-mocactl.mdregenerated.Assisted-By: Claude Code