Skip to content

feat(mocactl): add watch to stream subagent state changes - #929

Merged
pdettori merged 2 commits into
rossoctl:mainfrom
cwiklik:feat/381-watch
Nov 19, 2026
Merged

pdettori merged 2 commits into
rossoctl:mainfrom
cwiklik:feat/381-watch

Conversation

@cwiklik

@cwiklik cwiklik commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

What

mocactl watch [--tag T] [--json] — the last piece of #381 (scope item 5), and what A4
(#383, the Claude Code plugin's background monitor) needs to stop shelling out to
subagents on a timer.

watch is subagents as a stream:

  • the first sweep reports every matching ledger row, so a monitor that attaches late
    still learns the current state;
  • it then re-reads the ledger every 5 s (vs. get --wait's 2 s) and prints a line only
    when a row's state or detail changes — two queued reads in a row produce one
    running line;
  • re-reading the ledger each tick means a subagent spawned after the watch started joins it;
  • it exits 0 once every watched row is done, failed, paused or unknown. unknown
    counts as finished deliberately: otherwise a dead child or a failed read would leave
    watch polling forever. The line is printed, so the operator sees it;
  • Ctrl-C returns 130;
  • nothing to watch is not an error — no subagents on stderr, exit 0.

With --json the output is NDJSON, one event per line
({"sessionId","tag","label"?,"kind","state","detail","at"}), using subagents --json's
field names plus at.

No --timeout or --interval: every row is already bounded by its child or the server's
reaper, and timeout wraps the command.

Refactor

The per-row work cmdSubagents did inline — route sync leaf vs. async turn read, map the
honest state, persist a change back to the ledger — is extracted into sweepStates.
watch calls it in a loop, so there stays exactly one place that decides which backend a
row is read through.

Verification

  • packages/mocactl subagent + CLI + reference suites: 156/156 pass, including 9 new
    subagent-watch tests (baseline-only exit, dedup, unknown terminating, NDJSON shape,
    --tag, late spawn, async row read through the turn routes without minting a session
    token, Ctrl-C).
  • make typecheck, make check-links, make fmt clean. make lint passes except
    hadolint-docker, which cannot reach a local Docker daemon.
  • Not covered: a live deployment run, so the real 5 s cadence and stdout flushing under a
    piped reader are exercised only through the fake clock.

Refs #381, #378

Assisted-By: Claude Code

`mocactl watch [--tag T] [--json]` is `subagents` as a stream: it reports
every matching ledger row once, then re-reads the ledger every 5 s and
prints a line only when a row's state or detail changes. It exits 0 once
every watched row is `done`, `failed`, `paused` or `unknown` — `unknown`
counts as finished so a dead child or a failed read ends the watch
visibly instead of polling forever. Ctrl-C returns 130.

With `--json` the output is NDJSON, one event per line, so A4 (rossoctl#383) can
tail it from a background monitor.

The per-row backend routing, honest-state mapping and ledger write that
`subagents` did inline are extracted into `sweepStates`, so there stays
exactly one place that decides sync vs. async turn reads.

Part of rossoctl#381 (scope item 5).

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 18:37
@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): add watch to stream subagent state changes

The shape is right: watch is subagents as a stream, the shared sweepStates is a faithful extraction (identical to cmdSubagents' old loop, line for line), and the first-sweep / change-only / ledger-re-read semantics match what the docs say. Two must-fix items inline, both on the new loop.

What checks out

  • isFinalForWatch = isTerminalState (done/failed/paused) or unknown, so the documented exit set is exactly the code's (leaf-turn.ts:58).
  • The first sweep prints every row (empty printed map), later sweeps print only on state/detail changes, and a spawn --tag T after the start joins because the ledger is re-read each tick — all covered by the new tests.
  • Async rows route through readTurnState and never mint a session token; sync rows keep the ledger-authoritative-past-terminal rule; --tag filtering, the 5 s interval, the no subagents early return, --tag's widening in the flag gate (and its usage text), and the NDJSON fields (label?, at in ms) all match the reference pages.
  • Tests: 10 new cases, including the two-queued-reads-one-line case, a spawn mid-watch, the async route, and the already-final batch; check 18/18 green.

Inline must-fix

  1. subagent.ts:632 — the change-detection key uses a literal NUL byte in the source instead of an escape; the file is now binary to grep/rg.
  2. subagent.ts:630 — a Ctrl-C that lands during a sweep is turned into unknown rows and exit 0, not 130, contradicting the documented contract (and only the between-polls abort is tested).

Author: cwiklik (MEMBER — maintainer). One commit, signed off.

Comment thread packages/mocactl/src/subagent.ts Outdated
const records = ledger.readAll().filter(match);
const views = await sweepStates(rt, { ledger, transport, turns, records, signal: opts.signal });
for (const { record, view } of views) {
const line = view.state + '' + (view.detail ?? '');

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

must-fix: the separator here is a literal NUL byte (0x00) in the source, not an escape — it renders as a space in most viewers. The file is now binary to ordinary text tools: grep 'cmdWatch' packages/mocactl/src/subagent.ts prints nothing and exits 1, and rg stops with "binary file matches"; only grep -a/rg -a see it. Git's binary heuristic only looks at the first 8 KB, so diffs still work today, but the moment this function moves up the file every diff of it becomes binary. Write it as '\u0000' (or '\0') — identical behavior, searchable file. (If a plain space was the intent, that works too: no two honest states make the composite ambiguous.)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 3fc08b0 — a plain space. You're right that nothing is ambiguous: HonestState is a closed set of five single-word values, so the first space always separates state from detail. I hadn't noticed the file had gone binary.

Assisted-By: Claude Code

// Re-read each tick so a `spawn --tag T` from another terminal joins a running `watch --tag T`,
// which is how a coding agent fans out: spawn some, watch, spawn more.
const records = ledger.readAll().filter(match);
const views = await sweepStates(rt, { ledger, transport, turns, records, signal: opts.signal });

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

must-fix: Ctrl-C during a sweep is reported as success. The signal goes into sweepStates, so an aborted readLeafState/readTurnState throws, each row's catch turns it into unknown, and unknown is final for isFinalForWatch — the loop prints one unknown line per row, persists them via ledger.updateState, and returns 0 without ever reaching the abort check after sleep (:641). A monitor therefore reads an interrupted run as "everything finished", contradicting cli-mocactl.md's "Ctrl-C exits 130"; the new test only covers the abort between polls. An aborted read is not unknown: either rethrow in sweepStates's catch when deps.signal?.aborted and catch that here as 130, or check opts.signal?.aborted immediately after this call and return 130 before printing (and skip persisting those rows' states).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 3fc08b0, both halves of it.

cmdWatch now checks the signal immediately after sweepStates and returns 130 before anything is printed, and sweepStates returns before its persist loop when the signal is aborted — a read that never finished is not an observation, so nothing from an interrupted sweep reaches the ledger. That second guard also tightens subagents: a Ctrl-C mid-sweep no longer records unknown rows there either (it still prints them and exits 0, which is existing behaviour I left alone — there is no global catch in cli.ts/main.ts, so making sweepStates rethrow on abort would turn a Ctrl-C'd subagents into an unhandled rejection with a stack trace).

New test: readLeafState aborts the controller and rejects, as an aborted fetch does — exit 130, no output, and the row still reads running in the ledger afterwards.

One wrinkle worth a comment in the source: with two signal checks in the same loop body, TypeScript narrows opts.signal?.aborted to false | undefined after the first and flags the second as unreachable (TS2367). Both are needed — mid-sweep and mid-sleep are different moments — so the test sits behind a small aborted(signal) helper, matching the one workloads.ts already has.

Assisted-By: Claude Code

… NUL

Review of rossoctl#929, both on the poll loop:

- The change-detection key separated state from detail with a literal NUL
  byte, which made the whole file binary to `grep`/`rg`. A plain space is
  unambiguous — no honest state contains one — and leaves the file
  searchable.
- A Ctrl-C arriving *during* a sweep aborted the in-flight read, which each
  row's catch turned into `unknown`; `unknown` is final for watching, so the
  loop printed a row of them and returned 0 — an interrupted run read as
  "everything finished". The loop now checks the signal right after the
  sweep and returns 130, and `sweepStates` skips its ledger write when the
  signal is aborted, so a read that never finished is not persisted as an
  observation.

Checking the signal twice in one loop body needs the test behind a call, or
TypeScript narrows the second one away as unreachable.

Part of rossoctl#381 (scope item 5).

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

@ingpaolodettori-dev ready for another look — both must-fix items are addressed in 3fc08b0.

  • NUL separator → a plain space. HonestState is a closed set of five single-word values, so the first space always separates state from detail, and the file is searchable again.
  • Ctrl-C mid-sweep → cmdWatch checks the signal right after sweepStates and returns 130 before printing anything, and sweepStates returns before its persist loop when the signal is aborted, so an aborted read is never recorded as an unknown observation. That second guard also stops subagents writing unknown rows on a Ctrl-C.

I did not take the rethrow option you offered: there is no global catch around the dispatch in cli.ts/main.ts, so a throwing sweepStates would turn a Ctrl-C'd subagents into an unhandled rejection with a stack trace.

New test covers the mid-sweep case the way an aborted fetch behaves — the read aborts the controller and rejects: exit 130, no output, and the row still reads running in the ledger.

One detail you will see in the diff: with two signal checks in the same loop body, TypeScript narrows opts.signal?.aborted to false | undefined after the first and flags the second as TS2367. Both moments are real (mid-sweep, mid-sleep), so the test sits behind a small aborted(signal) helper, matching the one workloads.ts already has.

Local: 225 tests green across the subagent, CLI and reference suites (watch is 11 cases now); make fmt, make typecheck and make check-links clean.

Assisted-By: Claude Code

@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 — fix(mocactl): watch exits 130 on a Ctrl-C mid-sweep, and drop a stray NUL

Both must-fix items from the last round are fixed, and each with a test that would have caught the original.

  • The NUL is gone: the separator is a plain space again. That is unambiguous for this key — no honest state contains one, so no two (state, detail) pairs collapse — and grep/rg see the file again (I re-checked: zero NUL bytes in subagent.ts).
  • Ctrl-C mid-sweep is now 130: the post-sweep aborted(opts.signal) check returns before anything is printed, and sweepStates skips its ledger write when the signal is aborted, so an interrupted read is no longer persisted as an observation. The new test drives the read to reject after aborting and asserts exit 130, no output, and the row still running in the ledger; the between-polls case still passes.
  • The aborted() helper (with the reason it is a call, not an inline comparison) is the same pattern workloads.ts uses, and skipping persistence on an aborted sweep also improves subagents' Ctrl-C behaviour.

CI 18/18, k8s-kind-e2e included. This clears the CHANGES_REQUESTED from d5cb57b.

Author: cwiklik (MEMBER — maintainer). Two commits, both signed off.

@pdettori
pdettori merged commit 9922a0a 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