Skip to content

feat(native-chat): Claude sessions write their subagents into the host status store - #22536

Merged
brennanb2025 merged 22 commits into
mainfrom
brennanb2025/c3-claude-producer
Sep 25, 2026
Merged

brennanb2025 merged 22 commits into
mainfrom
brennanb2025/c3-claude-producer

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 14 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1827 $\color{#cf222e}{\Huge{\mathbf{−}}}$​22 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1805
Prod 41 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​2901 $\color{#cf222e}{\Huge{\mathbf{−}}}$​207 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​2694

ELI5

When a Claude chat starts a subagent or a background shell, Orca now keeps one record for it on the machine running the chat. The record says what kind of work it is, whether it is still running, what tool it is using right now, how it ended (finished, failed, stopped, or "ended, reason not reported"), and when. A record ends only when that piece of work itself says it ended: not when the chat's own turn ends, not when Claude's list of background work stops mentioning it, and not when the call that started it returns. Nothing on screen reads these records yet, so this PR changes nothing you can see. The switch is #22614, at the top of this stack (this PR → #22553, the Codex producer → #22565, the shared row → #22614), which points the sidebar and the chat strip at these records and deletes the legacy background-task path. Because the sidebar will read these records directly, a record that ended early would show Done while work still runs; this PR makes sure that cannot happen.

Supersedes #21279. #22521 (the child-record contract) has merged, so this PR's base is now main.

Merge order

What Changed

The path from a Claude frame to a record, hop by hop

  1. Claude adapter emit (claude-structured-session-adapter.ts). A new per-session decoder (claude-child-work-decoder.ts) reads the frame's task fields. The background-task tracker observes the frame exactly as on main. The journal translator writes the frame's rows. The legacy background-task state is republished (so the parent's own status row lands first). Only after all of that, drainClaudeChildWork (claude-child-work-evidence.ts) collects the decoder's edges, names each child's owner, adds the child's own open tool call, and calls onChildWorkEvidence(sessionId, evidence). A close clears the decoder outside emit, so closeSession and releaseAcquisition drain it afterwards too.
  2. Runtime (structured-agent-session-runtime.ts → structured-claude-runtime-adapter.ts) routes it to host.publishChildWorkEvidence.
  3. Host → client delivery → status feed (publishChildWork) looks up the session's provider.
  4. Status ownership (structured-agent-session-status-ownership.ts) forwards it only under the subject the session's parent row actually landed under. If that publish threw, it forwards nothing.
  5. Status sink (orcad-entry.ts, main-process-runtime-service.ts): publishChildWork → agentHookServer.ingestStructuredChildWork.
  6. Ingest (server-ingest-structured-children.ts, in the server class chain) refuses a subject whose parent row the store does not hold. Otherwise it runs the reducer against the host's canonical store.
  7. Reducer (agent-status-child-work-reconciliation.ts, plus …-evidence-admission.ts and …-evidence-resolution.ts) turns each edge into feat(agent-status): child work records say what the child is doing, how it ended, and when #22521's admission calls (announce / adopt / resume). Records live in memory only and are never persisted or transmitted.

What the producer writes, and from which frame

Claude frame Evidence edge Record effect
task_started (not ambient, not hidden from the transcript) live (task id + spawn call, kind, residency from is_backgrounded, name/agent type, description) created live, fence {spawn call, 1}, aliases task_id + tool_use_id
task_started for a task id that already ended, under a different spawn call live with restart: true and the new spawn call resumed: same childWorkId, generation + 1, the prior run's outcome kept in previousInvocations. This is how Claude resumes a finished background agent that is sent a message (captured)
task_started for an ended task id under the spawn call it ended with none a late start of the run that ended, not a new run
task_updated with live content (is_backgrounded: true, a name, a description, a running status, a known type) live kind, residency and labels updated (reclassification goes through adopt). An agent the user moves to the background becomes background here
task_progress (foreground or background) live with operation {toolName: last_tool_name, basis: 'reported'}, summary as last message, usage as tokens operation, last message and tokens updated
a foreground child's own tool_use (frames carrying its parent_tool_use_id) operation {toolName, input: hook-lane preview, basis: 'open'} "Bash: npm test", the same preview a CLI row shows
that call's tool_result operation: null open operation cleared (a reported one stays)
task_notification ended (completed→succeeded, failed→failed, killed/stopped→cancelled, unreadable→unknown), summary, usage, and its tool_use_id as the run that ended settled, or an unknown ending refined to the reported outcome. An ending from a run that is already over is ignored; a run id the record never saw still ends the current run
terminal task_updated ended with the same mapping; patch.error as last message same
background_tasks_changed none nothing
result, or a new turn starting none nothing
a spawn call's tool_result none nothing
session ended / close session-ended every record still live settles unknown; settled records keep their outcome. The records go when the host drops the parent row on close or release

Owner (parentChildWorkId). A child-launched shell or a nested agent is owned by the agent whose own traffic made the launching call. The journal translator's read-only childToolOwner(toolUseId) query answers through the same tool-origin registry and linkage that stamp journal rows.

Only a child's own frame ends it. In every captured run (a foreground agent that finishes, two interrupts in different orders, an agent moved to the background with its own shell still running, a background agent resumed by a message), every child gets its own terminal frame: a terminal task_updated, a task_notification, or both. So the roster, the turn boundary and the spawn result are never needed to end a child, and each of them ends one too early in a real capture:

  • The turn boundary: an agent moved to the background keeps its own 45-second shell running. The parent's result arrives at +12.6 s; the shell's own notification arrives at +51.3 s. The turn-end sweep settled the shell unknown 39 s early.
  • The spawn result: replay the same capture with the spawn call's result ahead of the roster and the move, and the spawn-result rule settled the agent as a success while it was still running, then the roster revived it as a second run that never existed.
  • The roster: Claude drops a finished task from background_tasks_changed before its outcome frame. Settling on that omission only ever produced an unknown that the outcome frame refined, and it would settle a child the roster forgot while it still ran.

The tracker (legacy row unchanged)

ClaudeBackgroundTaskTracker, claude-settled-background-tasks.ts and the frame readers are exactly what main has: git diff origin/main -- src/main/claude/claude-background-task-tracker.ts src/main/claude/claude-settled-background-tasks.ts src/main/claude/claude-background-task-frames.ts is empty, and the earlier aggregate-roster split and restart holding map are deleted. The legacy row is unchanged by construction, and every existing tracker test passes unmodified. The evidence path differs from the legacy row in these deliberate ways:

  • It ends a child only on the child's own terminal frame. The legacy row still retires foreground work at result and drops background work a roster omits.
  • It keeps a foreground child's task_progress. The legacy row still keeps usage only for background tasks.
  • It reports outcomes in the outcome vocabulary. The legacy row still maps failed→blocked and killed/stopped→idle.
  • It reports a restart when a finished task starts again. The legacy row still ignores a start for a task that ended and waits for a roster to list it.
  • It records a background start after a roster has been seen. The legacy row still drops such a start unless the roster already listed the task.

The store: a write costs what it touches

Child records share the host store with every parent status row, and before this PR each mutation copied all five store maps and re-validated every record, and reads scanned every child and alias. With child records on the host, every child edge and every unrelated parent status publish paid for every child in the store. This PR changes the store's internals and keeps its existing API (it adds two reads, getParents() and getRevision(), so parent listing and the structured row's revision stamp no longer build a snapshot of every child):

  • A mutation writes into drafts over the committed maps and lands in place; a refused one is dropped with nothing to undo. The drafts reproduce the exact map order a copy would have (snapshot order and tombstone compaction depend on it).
  • Only what a mutation touched is re-validated: touched parents, children, aliases, facts and tombstones, every alias of a touched child, and whatever a removed parent owned. The full validation stays for snapshot restore.
  • The snapshot byte budget is a running total.
  • Children by parent, facts by parent, aliases by child, aliases by identity and retired aliases are indexed. Reads return the stored (already parsed, frozen) records instead of re-parsing them.
  • Two memoized keys added earlier in this PR (alias identity, tombstone-key validity) are gone: the indexes derive them once per record.

Bounds

At most 256 live children per session, in both the decoder and the reducer. The decoder remembers at most 256 ended task ids (oldest first) to recognise a restart. At most 32 settled children per session: the oldest are removed first, never one that owns live work. Labels go to admission raw: admission owns label clean-up (the one-line fold, the length bounds, dropping a malformed label).

Ported from #21279 (pin 0565294472)

  • The subject-gated ingest that refuses an unknown parent.
  • Children riding the address the parent landed under.
  • Producer-owned-only changes.
  • Ambiguity rejection.
  • Bounded ingestion.
  • Retired alias bindings fencing a finished lifetime, with the id reusable at a higher generation.
  • A monotonic per-child clock.

Tests for each are included.

Dropped:

  • the legacy-projection module;
  • the parity/agreement gates, which are void on main;
  • the lossy DTO decoder as the evidence source;
  • the constant invocationId;
  • the stop-capability facts, since nothing consumes them yet;
  • settling on a roster omission or a turn boundary, which feat(agent-status): host-owned child producer for structured sessions #21279 and earlier heads of this PR both did.

Why

A child is materialised three times today: the tracker's DTO, a renderer-side conversion, and the hook roster. Each hop loses a fact. This PR gives the host the one record per child that #22614 (the reader switch at the top of this stack) will make every surface read. The record is fed from provider frames, not from the lossy summary, so it keeps what the DTO drops: foreground progress, the tool a child is running, and failed as distinct from blocked. Once the sidebar reads these records, a record that settles early is a sidebar that says Done while work runs, so liveness comes only from each child's own frames.

Alternatives considered:

  • Queue evidence at the legacy tracker's own decisions (earlier heads of this PR). It kept the legacy row and the records trivially in step, but it made display rules the source of truth: the turn-end sweep, the roster-omission settle and the spawn-result ending each end a child early in a real capture.
  • Snapshot reconciliation of the whole roster per frame, as feat(agent-status): host-owned child producer for structured sessions #21279 did. It heals itself, but it rewrites every child per frame and settles on omission. Edges carry the full descriptive state instead, so an edge the host could not admit is healed by that child's next one.
  • Keep a roster listing as a revival signal. Unneeded: a message to a finished background agent produces a task_started for the same task id under the message call (captured with the real CLI), which the restart rule covers.
  • Store: copy only the maps a mutation touches, instead of drafts. Simpler, but a child edge would still copy the children and alias maps, so its cost would still grow with every other session's children. The drafts land in place and keep a refused mutation free.

Linked Issue

None — part of the structured chat status/orchestration program.

Visual Proof

Nothing on screen reads the records yet, so the expected visible result is no change: the chat's tool rows, the background-task strip and the sidebar behave as on main. Checked live in a background-launched dev build of this head (94e5159f52) with a fresh profile, a real structured Claude chat in a folder workspace, and the host's child records read from the running main process after each step:

Moment Screenshot Host records at that moment
Foreground subagent running its own Bash 01-fg-running agent live, current tool Bash: sleep 8 && echo done-fg; its shell live, owned by the agent. Both succeeded after the turn
Background agent's own shell still running after the parent's turn ended 03-bg-agent-shell-midrun the parent's reply had landed; the agent and its 40-second shell were both still live. Both settled succeeded on their own frames about 30 s later
Foreground subagent before Stop 05-before-stop agent and its shell live
After Stop 06-after-stop agent and shell both cancelled (not failed); a follow-up message got a normal reply
Background shell plus background agent, sidebar reading "Monitoring background tasks" 08-bg-running-sidebar shell live, agent succeeded; shell succeeded 20 s later, nothing left live

Every child got exactly one record and nothing settled early. The main-process log had no child-work, ingest or status errors. The interrupted turn's tool row reads "Ran 1 subagent failed": that row comes from the journal translator, which this PR does not change, and it reads the same on main.

Testing

  • pnpm tc:node, pnpm tc:web and pnpm tc:cli all exit 0.
  • New tests in this revision:
    • claude-structured-child-work-captures.test.ts (8): scrubbed cuts of five real Claude CLI 2.1.280 stream-json captures (ids, paths and prompts replaced; frame order and relative clock kept), replayed through the real adapter into a real AgentHookServer.
    • claude-child-work-decoder.test.ts (9): the decoder frame by frame.
    • agent-status-store-in-place.test.ts (7 cases): two seeded cases hold every running index and the byte total equal to a rebuild from the maps after every step, refusals included (breaking the byte math turns both red; the fuzz alone stays green); a seeded, deterministic fuzz of 1,500 mixed mutations for each of four seeds, held to the old copy-and-validate-everything path (kept as a test oracle): the same accept/reject decision, the same snapshot, the same getChildren, getAliasesForChild and resolveChildAliases results, and a full validation passing after every step; a replica fed the envelopes ends identical. A 5,000-step run past the tombstone retention window checks compaction.
    • agent-status-store-scaling.test.ts (2): a parent publish and a child update at 4,000 children each cost under 4x their cost at 40 (interleaved medians of 350 repeats, so load slows both).
    • agent-status-child-work-reconciliation.test.ts: restart edge, ending under an unseen run id, session end settling instead of removing, and a removed lifetime's fence, replacing the inventory and turn-end cases.
  • Frame script. A frame-by-frame script through the real adapter (foreground agent, its own Bash call and background shell, foreground progress, spawn result, background agent, result, roster eviction before the outcome, notification, kill, restart under a message call, close) now asserts literal record expectations at each frame and for the whole record set after close. The earlier check that the parent state folded from the records equals the one folded from the legacy row is retired: feat(native-chat): the chat strip and the sidebar read the host's child records #22614 folds the parent from the records and deletes the legacy row, so matching the legacy fold is no longer the contract, and it pinned the roster-omission settle this PR removes.
  • Red before, green after. Run against the previous head's production code (tests and fixtures from this revision): the moved-agent shell settles at the parent's turn end, the reordered spawn result produces generation 2, the roster omission settles the child, session end leaves no records, and the resumed agent's first run is keyed by its task id because a roster named it before its start. The store scaling test fails at 60x and 51x against the previous store.
  • Admission ordering. For a task_started frame, every journal row and the legacy republish precede the evidence delivery.
  • Ablations at the final head, each an exactly-once edit asserted by the script, restored from HEAD:
Deleted (or reverted) Red
Decoder restart rule (a start for an ended task ignored, as the legacy row does) 4: resumed agent's second run; decoder restart; run-count parity; frame script
Session end settles live children 5: session end keeps records; per-session isolation; producer-owned; frame script; reducer session end
Reducer restart flag 1: restart under the same run handle
An unseen run id still ends the current run (reverted to "only the current run") 1: ending under an unseen run handle
Decoder late-start guard 1: a late start of the ended run is nothing
Notification's run id 1: ending names the run that ended
Residency from task_updated.is_backgrounded 2: moved agent reads background; decoder move
Close-path session end 2: session end keeps records; frame script
Owner enrichment 3: moved agent's shell owner; interrupted agent's shell owner; frame script
Child's own tool call decode 1: frame script (Bash: npm test open operation)
Store: re-validating every alias of a touched child 4: every fuzz seed (a mutation the old path refuses is accepted)
Store: draft re-append order 4: every fuzz seed (snapshot order differs)
  • Per-frame cost, measured with children spread 40 per session (median of 150):
Children in the store Parent publish, before after Child edge through the reducer, before after
40 0.073 ms 0.019 ms 0.184 ms 0.083 ms
1,000 2.51 ms 0.012 ms 3.58 ms 0.054 ms
4,000 10.2 ms 0.011 ms 12.8 ms 0.047 ms
  • Regression. Every test file under src/shared/agent-status*, src/main/agent-hooks, src/main/native-chat/agent-session-wire, src/main/orcad, the Claude structured, background-task and child-work files, the runtime structured and Claude files, the relay store context and the renderer agent-status IPC files: 407 files, 3,823 tests: 3,808 passed, 1 expected-fail, 12 skipped, 2 failed. Both failures (refusal-retry host oracle's 90-second timeout, and one renderer SSH-authority snapshot test) pass when rerun alone (9/9). Real-binary suites (*real-cli*, *real-binary*) were excluded.

  • pnpm run check:code-quality:changed: 0 new findings. oxlint on all changed files: clean. pnpm-lock.yaml is absent from the branch range, and there are no new docs.

  • Platforms: tests ran on macOS; the code is platform-independent (host-clock stamps, no paths, no shell).

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

Review

Not verified:

  • Live check covers the records, not a reader. The Electron run above proves no visible change and correct records; how the sidebar and strip render the records is feat(native-chat): the chat strip and the sidebar read the host's child records #22614's check.
  • Captured, and what the captures do not cover. Frame orders now come from real Claude CLI 2.1.280 runs: a foreground agent that finishes, interrupts in two orders, an agent moved to the background with its own shell, and a finished background agent resumed by a message. That task_notification.tool_use_id names the current run is captured (the resumed run's notification carries the message call's id). Not captured: a workflow or monitor task, a nested agent inside an agent, a message sent to a background agent that is still running, and a restart under the same spawn call (the restart flag covers it, unevidenced).
  • Waiting and blocked children are not produced. How a child's permission request is attributed in the SDK lane is untraced. task_updated.patch.error on a live child is not mapped to blocked. Both read working. Producing them belongs to this producer lane, not to the reader switch (feat(native-chat): the chat strip and the sidebar read the host's child records #22614), and is deferred to a follow-up PR at the top of the stack: the state will be produced only once a captured transcript proves the attribution (the query it would use, childToolOwner(toolUseId), already ships here). Until then the child row reads working while the pane-level permission prompt, an untouched separate path, still surfaces.
  • A backgrounded child's own tool calls. The resume capture shows a background agent's own traffic does reach the parent stream, tagged with its original spawn call. Its open tool call is recorded the same way as a foreground child's; a shell such a child starts is attributed only if its launching call reaches the stream, which is not captured for a background agent.
  • The published observedAt/firstObservedAt use the adapter's host clock at drain, not the tracker's startedAt. The two differ by microseconds.
  • Relay typecheck and mobile were not run. The relay store context test ran; no mobile module imports these files.

Decisions and deviations from the plan:

  • Invocation generation. It counts runs. It goes up when a spawn call differs from the current run's registered spawn alias (the same event that advances the journal roster's attempt), or when the producer reports a restart of a settled child. invocationId is the first run's spawn call, or the task id when the child is named before its spawn call is known.
  • A late start under the spawn call a run ended with is ignored, not treated as a restart. No capture shows one; treating it as a restart would leave a finished child live with nothing to end it but the session's end.
  • An ending under a run id the record never saw ends the current run. Only a run the record knows is over is fenced, so an ending is never lost to a spawn call the host missed.
  • The task_progress.description activity sentence ("Running Bash") is not stored. It restates the tool, the contract has no activity field, and operation.input is the tool-argument preview.
  • The 32-settled cap is enforced here so memory stays bounded now. Removing settled children when the next turn starts is product retention, left to feat(native-chat): the chat strip and the sidebar read the host's child records #22614.

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • Contract changes the stacked PRs adapt to:
    • The inventory and turn-ended evidence edges are deleted, with their settle rules.
    • session-ended settles every live record unknown and keeps settled ones, instead of removing the session's records.
    • A live edge may carry restart: true.
    • An ended edge under a run id the record never saw now ends the current run (only a known previous run is fenced).
    • The store's existing API is unchanged; it gains two reads, getParents() and getRevision(). getChildren and getAliasesForChild return the stored frozen records.
  • Wire / mixed versions: no wire change, no new opcode, no new published field. The records stay in the host's in-memory store, which has no production reader and is never persisted. Restart forgets them, per the decision that child records live in memory.
  • SSH / WSL / folder workspaces: evidence is decoded where the Claude session runs (the execution host) and ingested in the same process (desktop main or orcad), under the parent's full execution scope. The ingest test uses an SSH host and a folder workspace.
  • Mobile: nothing reads the records; subagents is unchanged.
  • Boundary with the main-agent status lane: structured-agent-session-agent-status.ts, the fold and the renderer bridge are not touched. server-ingest-structured.ts (the row's revision stamp) and server-listeners.ts (parent listing) each change one line to read the new getRevision() / getParents() instead of building a full snapshot that would include every child record.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important

The reducer drops a task_updated-driven resume. The tracker revives a settled background child on an edge-only task_updated patch and queues a plain live edge, but the reducer treats it as late evidence and leaves the record settled — the legacy row and the record disagree on the same frame. It is conditional (only reachable before the first background_tasks_changed), so I have flagged it rather than blocked, but C5 will read these records and this reintroduces exactly the stale-settled class of bug this stack exists to remove.

Reviewed changes

  • Claude producer — claude-child-work-evidence.ts decodes task frames into live / ended / inventory / turn-ended / session-ended / restart edges; the tracker queues one at each decision it already makes and drains them after the journal and the legacy republish. The journal translator gains read-only childToolOwner/childActivity.
  • Host delivery — a subject-gated ingestStructuredChildWork on a new server class link, reached through the feed's publishChildWork and the ownership landed gate from both main-process-runtime-service.ts and orcad-entry.ts.
  • Reducer — reconcileAgentChildWorkEvidence folds the edges into the canonical store through C2 admission, with 256-live / 32-settled caps and per-producer ownership.
  • Tests — 8 files; the producer test shadow-checks the parent state folded from records against the legacy backgroundTasks DTO frame by frame.

ℹ️ The unproven-exit window has no child-record consequence

session-ended is only ever produced from backgroundTasks.clear(), which the close ladder reaches only after connection.close() proves the child gone. On an unexpected exit whose tree proof fails, no ended event is emitted, so no edge reaches the store and the run's children stay live under the session's subject. If a replacement is then acquired under the same session id, those records outlive the dead provider session until the replacement ends and removes them with its own session-ended. This may be the intended reading of "loss of contact is never evidence of process death", but C5 will render these records, so it is worth an explicit decision plus a test.

Technical details
# Children of an unproven-exit session stay live across a same-id reacquire

## Affected sites
- `src/main/claude/claude-structured-session-adapter.ts:130-161` — `settleUnexpectedExit` emits the `ended` event (and therefore `session-ended`) only after `close()` returns true.
- `src/main/claude/claude-structured-session-close.ts:100-115` — `finalizeClaudePublishedSession` calls `backgroundTasks.clear()` only when `connectionClosed === true`.
- `src/main/claude/claude-structured-session-recovery.test.ts:402-418` — pins that an unproven exit produces no `ended` event.

## Required outcome
A decision (and a test) on what the child records of an unproven-exit session should read once a replacement is acquired under the same session id: remain `live` until the replacement ends, or settle to `unknown`/be removed when the old provider session is superseded.

## Open questions for the human
- Is a stale-`live` record under a reacquired session id acceptable until the replacement ends, or should the host settle the old subject's children when the provider session is proven gone?

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

const existing = resolution.child
const request = { parent: ctx.parent, provider: ctx.provider }
const aliases = agentChildWorkHandleAliases(handle)
if (!existing) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This is the only check of STRUCTURED_CHILD_WORK_MAX_LIVE, so the advertised 256-live bound holds only for brand-new children. The resume branch below (a new spawn call, or an inventory re-listing a settled child) moves a settled record back to live with no capacity check, so a session can run past 256 live records — e.g. settle 32 of 256 live children, admit 32 fresh ids, then resume the settled 32 under new spawn calls. The provider trackers never carry those resumed runs, so nothing else bounds the live count. Computing the live count before both branches, rather than only the create path, keeps the documented bound honest.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No new issues in this incremental delta. The restarted-run fix is correct and its tests pass, but two findings from the previous review remain open and unaddressed, so this is not an approval.

Reviewed changes

Only fc7fd5d8ab ("a Claude child restarted under a new spawn call keeps reporting to its record") landed since the prior pullfrog review — 6 files.

  • New ClaudeTaskRestarts store — a task that ended under one spawn call and starts again under another is held in a bounded (256-entry) map, with take/get/clear wired into the tracker's finish, clear, roster replacement, task_progress, and spawn-result lookups.
  • Restarted-run evidence — task_progress resolves a restarted run through this.restarts.get(id), and a foreground restart's own spawn tool_result resolves through restarts.tasks, so that run's operation, usage, and ending reach the record before any roster lists it.
  • Roster hand-back — replaceClaudeAggregateRoster takes the restarted task so a listing resumes it under the new spawn call instead of the stale settled one.
  • Tests — two tracker tests (restart progress before a roster; a restarted foreground run ends on its own spawn result) and a producer run-count parity test asserting the record's invocation.generation matches the journal roster's attempt.

I traced the restart path through task_progress, its own spawn result, repeated restarts, roster hand-back, and turn boundaries; the record tracks the legacy row as the PR body documents (the record hears the restart at once, the legacy row waits for a roster — a deliberate divergence). The two earlier inline findings live in code this delta does not touch and remain open.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No critical issues. The new commit is a retention refactor; one edge case is worth a decision inline. The two findings from the earlier review are in code this commit does not touch and remain open.

Reviewed changes

Only eada18c2 landed since the prior pullfrog review (the branch was replayed onto a newer c2-child-record-contract, so the earlier commits are unchanged in content).

  • Retention moved into admission — liveFields and settleAgentChildWork now send only the facts the edge observed, delegating labels, model, owner, residency, last message and monotonic tokens to retainedFacts. Verified equivalent on the announce, adopt and resume paths, each of which passes the stored record as prior.
  • Token source narrowed — claudeTaskObservation now reads only facts.totalTokens, dropping the tracked task's task.totalTokens fallback.

Verified locally: claude-child-work-evidence (8), agent-status-child-work-reconciliation (16) and claude-structured-child-work-producer (3) all pass.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

// The published row names a task's type as both its name and its agent type.
...(task.name ? { name: task.name, agentType: task.name } : {}),
...(task.description ? { description: task.description } : {}),
...(facts.totalTokens !== undefined ? { totalTokens: facts.totalTokens } : {}),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

With the task.totalTokens fallback gone, a child's token count survives only while its record does — retainedFacts can retain from a prior record but cannot recreate one. The 32-settled cap in trimSettled can evict a settled record while the tracker still holds the task, so a child re-listed by a roster or restarted under a new spawn call is admitted proven-new with no prior and loses the count (these edges pass no facts). The tracked task still carries it here, so the legacy row and the record diverge until the next task_progress. Worth a decision: accept the gap, or carry the task's count on those edges.

Technical details
# An evicted-then-revived child loses its token count

## Affected sites
- `src/main/claude/claude-child-work-evidence.ts:80` — only `facts.totalTokens` is read now; the inventory, `upsert` and restart edges pass no `facts`.
- `src/shared/agent-status-child-work-reconciliation.ts:129-148` — `trimSettled` removes settled records past 32, leaving the tracker's task in `ClaudeSettledBackgroundTasks` / `ClaudeTaskRestarts`.
- `src/shared/agent-status-child-work-evidence-admission.ts:156-177` — a handle whose record is gone is admitted `proven-new`, calling `liveFields(..., null, null)`, so no prior exists to retain from.

## Required outcome
A revived child carries the same token count the legacy row does. Either keep the tracked task's `totalTokens` on the inventory / restart edge, or record a decision that the count may read absent until the next `task_progress`.

## Open question for the human
Is losing the count acceptable here, given #22614 renders tokens from these records?

@brennanb2025
brennanb2025 force-pushed the brennanb2025/c2-child-record-contract branch from 6de7f20 to 41d814b Compare September 24, 2026 23:22
@brennanb2025
brennanb2025 force-pushed the brennanb2025/c3-claude-producer branch from eada18c to 503eb83 Compare September 24, 2026 23:28
…bscriptions as they are

subscribeStatus and subscribeTurnCompletions wrapped client delivery's bound
methods in forwarding lambdas; they are now the same members, the way
waitForSendSettlement already is. The host is at its size limit, and the
next channel it hands out needs the line.
…t status store

The Claude background-task tracker queues child-work evidence at each decision it
already makes (start, update, progress, terminal frame, roster replacement, turn
end, session end), plus the two facts its legacy row ignores: a foreground child's
progress and a foreground spawn call's result. The adapter drains that evidence
after the journal handled the frame and the parent row was republished, and the
host folds it into one record per child in its canonical store.

Nothing reads the records yet; the strip and sidebar keep their current sources.
…child record

The adapter delivers evidence after the frame's journal rows and the parent's
republished row; the frame script keeps the parent state today reads while the
records add outcome and activity; the runtime hands the evidence to the status sink
under the session's own address; both entry points wire the sink to the ingest.
…its record says it is doing

A child's tool traffic reaches the parent stream only for a foreground child. Read
after the journal handled the frame, the child's newest call still awaiting a result
becomes its open operation, previewed the way a hook-reported row previews its own
tool; the result closes it. The open call is derived from the journal's own
bookkeeping, not held a second time.
…ps reporting to its record

A task that ended and starts again stays hidden from the legacy row until a roster
lists it, so the tracker held no run for it: the new run's progress reached nothing
and a foreground re-run's own spawn result settled nothing. The run is now held
beside the live map, where the legacy row never reads it, until a roster hands it
back or it ends. A parity test pins the record's run count to the journal roster's
attempt on a new spawn call, the one event both count.
…ontract get their own homes

The translator's child-tool queries move into claude-child-tool-queries.ts and its contract
type into claude-journal-translator-contract.ts. Brings the translator back under the size
limit.
…e's facts

Admission now keeps what a child's record already knows: labels, model,
owner, residency, the last message within an invocation, and a token count
that never shrinks. The evidence side copied all of those forward itself, a
second owner of the same rule. It now sends only what this edge observed,
and a task's token count comes from the frame that reported it.
…labels

Admission now folds provider text to one line and drops a malformed fact
instead of refusing the record, so the evidence side no longer folds labels
itself. The description keeps admission's longer bound.
@brennanb2025
brennanb2025 force-pushed the brennanb2025/c3-claude-producer branch from 503eb83 to fa71175 Compare September 25, 2026 04:50
@brennanb2025
brennanb2025 changed the base branch from brennanb2025/c2-child-record-contract to main September 25, 2026 04:50
@coderabbitai

coderabbitai Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The change adds structured child-work evidence types, reconciliation, and bounded record retention. Claude task events produce live, operation, terminal, and inventory evidence, which the structured-session runtime forwards through status ownership to canonical ingestion. Ingestion requires a valid structured-session subject and stored parent. Store helpers support alias and tombstone lookup. Tests cover event handling, reconciliation, forwarding, and session isolation.

Priority: ➖ Normal

Merge Risk: 🟡 Moderate · up to 7efdd

The child-work path may become slower as alias history grows. Resolve or explicitly accept that risk before merging; also strengthen the new test to verify settlement before notification enrichment.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to 7efdd

A delayed tool event from an earlier run may be recorded as the current run’s activity after a child restarts. The effect is limited to status data for that child and session, but it weakens the accuracy of records intended for later display.

Retained concerns

  • Medium · security · inferred: A late tool-use or tool-result event associated with an earlier spawn call can be applied to the replacement live invocation of the same child, overwriting or clearing its current operation without checking the event’s run identity.
Security review details

Security Blast Radius

  • inferred — The identified misattribution affects operation facts on an owned child record within one structured session. The checked ownership and parent controls do not support a cross-session mutation or privilege-escalation claim.

Security Findings and Attack Paths

  • inferred — After a task restarts under a new spawn call, delayed tool traffic naming the old call can resolve to the same stable child ID. The host then uses that child’s current aliases when applying the operation, so an old preview or clearing event can appear as current activity.

Trust Boundaries and Controls

  • observed — Publication requires a landed session subject, host ingestion requires an existing structured-session parent, and reconciliation scopes aliases to owned records. Unlike operation evidence, ended evidence checks whether its run is current before settlement.

Resilience and Maintainability Implications

  • observed — Admission limits live children to 256; the store limits aliases and tombstones, and reconciliation trims settled history. These bound retained state but do not make each alias lookup constant-cost.

Hardening Proposals

  • proposed — Carry the originating run identity on operation evidence and reject an operation whose run is no longer current. Exercise delayed old-run tool-use and tool-result events after restart.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 37.84% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 74 functions across 39 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the main change: Claude sessions write subagent records to the host status store.
Description check ✅ Passed The description is comprehensive and covers the change, rationale, implementation flow, testing, limitations, compatibility, and checklist. The Linked Issue section incorrectly states “None” despite t…
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
src/shared/agent-status-child-work-evidence-resolution.ts (1)

155-157: 🚀 Performance & Scalability | 🔵 Trivial | ⚖️ Poor tradeoff

Avoid full alias scans for child lookups.

getAliasesForChild scans every stored alias before filtering by childWorkId. The lookup at src/shared/agent-status-child-work-evidence-resolution.ts:155-157 therefore has linear cost in the alias count. If this path is hot, maintain an index keyed by childWorkId.

The alias-retention claim is not valid: removing a child also removes its aliases, and AGENT_STATUS_STORE_LIMITS.aliases bounds the total alias count.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: b2049632-a4c3-4743-961e-35f553080726

📥 Commits

Reviewing files that changed from the base of the PR and between f559c05 and fa71175.

📒 Files selected for processing (32)
  • src/main/agent-hooks/server-ingest-structured-children.test.ts
  • src/main/agent-hooks/server/server-ingest-remote.ts
  • src/main/agent-hooks/server/server-ingest-structured-children.ts
  • src/main/claude/claude-background-task-aggregate-roster.ts
  • src/main/claude/claude-background-task-restarts.ts
  • src/main/claude/claude-background-task-tracker.ts
  • src/main/claude/claude-child-tool-queries.ts
  • src/main/claude/claude-child-work-evidence.test.ts
  • src/main/claude/claude-child-work-evidence.ts
  • src/main/claude/claude-journal-translator-contract.ts
  • src/main/claude/claude-settled-background-tasks.ts
  • src/main/claude/claude-structured-child-work-producer.test.ts
  • src/main/claude/claude-structured-journal-translation.ts
  • src/main/claude/claude-structured-session-adapter.ts
  • src/main/claude/claude-structured-session-state.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-client-delivery.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-host.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-status-feed-child-work.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-status-feed.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-status-ownership.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-status-ownership.ts
  • src/main/orcad/orcad-entry.ts
  • src/main/runtime/claude-structured-session-integration.test.ts
  • src/main/runtime/orca-runtime-structured-status-sink-wiring.test.ts
  • src/main/runtime/structured-agent-session-runtime.ts
  • src/main/runtime/structured-claude-runtime-adapter.ts
  • src/main/startup/main-process-runtime-service.ts
  • src/shared/agent-status-child-work-evidence-admission.ts
  • src/shared/agent-status-child-work-evidence-resolution.ts
  • src/shared/agent-status-child-work-evidence.ts
  • src/shared/agent-status-child-work-reconciliation.test.ts
  • src/shared/agent-status-child-work-reconciliation.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No new issues in this incremental delta. The one new commit is a behavior-preserving refactor; the three earlier findings remain open, so this is not an approval.

Reviewed changes

Only fa71175a68 ("Claude child evidence hands admission its raw labels") landed since the prior pullfrog review — 2 files, +6/-27.

  • Label folding moved into admission — liveFields now passes child.name/description/agentType through raw; parseObservationFacts folds them with normalizeChildWorkText (control chars and line separators to spaces, trimmed) before the codec sees them, so the producer no longer owns that rule.
  • Description keeps admission's longer bound — the removed childWorkLabel capped every label at 512; description now uses AGENT_CHILD_WORK_DESCRIPTION_MAX_LENGTH (8,000), while name/agentType stay at 512.
  • Dead helper removed — childWorkLabel, its normalizeOptionalField import, and the label-bound constants are gone.
  • Test renamed — the reconciliation test now states that admission owns the folding.

This also closes a latent edge the old helper left open: childWorkLabel folded only C0/DEL, so a label containing U+0085/U+2028/U+2029 would have failed the codec's isChildWorkText check and refused the whole record. Delegating to normalizeChildWorkText folds those too, so the value always satisfies the codec. Verified pnpm test on the reconciliation (16) and evidence (8) files and pnpm tc:node, all green.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

…nding

The reconciliation returned before admission whenever a record had already
settled with a definite outcome. That dropped the evidence an `unknown` ending
carries (its last message and tokens), which admission's refine-only rule keeps,
so that rule never ran for the structured producers.

The latch goes. Admission keeps the definite outcome, lands the late evidence,
and refuses a conflicting definite ending as `stale-invocation`, which the host
ingest already counts as the fence doing its job, not a fault.

Pinned through the real Claude producer and the host's own ingest.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No new issues in this incremental delta. The new commit is a small behavioral fix whose tests can fail; the three earlier findings remain open, so this is not an approval.

Reviewed changes

Only bf82728df6 ("admission alone decides a settled child's second ending") landed since the prior pullfrog review — 2 files.

  • Second-ending ownership moved into admission — applyEnded no longer returns early once a settled child has a definite outcome. Every current ending now reaches settleAgentChildWork, and admission's conflictsWithSettled decides: an unknown ending keeps the stored definite outcome while still landing its last message and monotonic tokens, and a conflicting definite ending is refused as stale-invocation.
  • Tests — the producer harness can now route evidence through a real AgentHookServer. A settled foreground child is sent an unclassified task_notification (asserts its summary and usage land while the outcome stays succeeded) and a conflicting failed notification (asserts settled: 0, a stale-invocation refusal, and no console.warn/error).

I traced the removed latch through settleAgentChildWork → updateExistingAgentChildWork → conflictsWithSettled and mergeObservationFacts: the new comment matches the code, server-ingest-structured-children.ts already treats stale-invocation as an expected fence refusal, and both new tests would fail under the old early return. The three earlier inline findings (agent-status-child-work-evidence-admission.ts revive/cap and the claude-child-work-evidence.ts token gap) sit in files this commit does not touch and remain open.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: c506d7e3-3703-41b4-88cf-f4ab9b02e077

📥 Commits

Reviewing files that changed from the base of the PR and between fa71175 and bf82728.

📒 Files selected for processing (2)
  • src/main/claude/claude-structured-child-work-producer.test.ts
  • src/shared/agent-status-child-work-reconciliation.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.

Comment on lines +52 to +59
if (agentChildWorkRunVerdict(ctx, existing, edge.handle.runId) !== 'current') {
return
}
// Admission owns what a second ending may change: an `unknown` one keeps a definite outcome and
// lands its evidence; a conflicting definite one is refused as `stale-invocation`.
settleAgentChildWork(ctx, existing, edge.outcome, edge.observedAt, {
...(edge.lastMessage !== undefined ? { lastMessage: edge.lastMessage } : {}),
...(edge.totalTokens !== undefined ? { totalTokens: edge.totalTokens } : {})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '130,235p' src/main/claude/claude-background-task-tracker.ts
sed -n '185,230p' src/shared/agent-status-child-work-evidence-admission.ts
sed -n '240,270p' src/main/claude/claude-child-work-evidence.test.ts

Repository: stablyai/orca

Length of output: 6991


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- tracker symbols and notification construction ---'
rg -n -C 8 'pendingClaudeNotification|restarts|terminalTaskIds|task_notification|observeSystemFrame|finish\(|spawnResult|runId' src/main/claude/claude-background-task-tracker.ts src/main/claude src/shared
printf '%s\n' '--- reconciliation implementation and classifier ---'
rg -n -C 12 'agentChildWorkRunVerdict|runId|settleAgentChildWork|reconcileAgentChildWorkEvidence|task_notification|unknown|current|stale-invocation' src/shared/agent-status-child-work-reconciliation.ts src/shared/agent-status-child-work-evidence-admission.ts
printf '%s\n' '--- relevant tests ---'
rg -n -C 12 'status-less|notification|restarted|restart|runId|toolu_fg|agent-fg|lastMessage|totalTokens' src/main/claude/claude-child-work-evidence.test.ts src/main/claude src/shared --glob '*test*'

Repository: stablyai/orca

Length of output: 45659


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- tracker core ---'
sed -n '1,125p' src/main/claude/claude-background-task-tracker.ts
sed -n '175,325p' src/main/claude/claude-background-task-tracker.ts
printf '%s\n' '--- restart implementation ---'
cat -n src/main/claude/claude-background-task-restarts.ts
printf '%s\n' '--- notification producer ---'
rg -n -C 20 'function pendingClaudeNotification|pendingClaudeNotification|runId|invocation' src/main/claude/claude-child-work-evidence.ts
printf '%s\n' '--- reconciliation implementation ---'
rg -n -C 18 'agentChildWorkRunVerdict|reconcileAgentChildWorkEvidence|settleAgentChildWork|runId' src/shared/agent-status-child-work-reconciliation.ts
printf '%s\n' '--- producer restart test ---'
sed -n '330,430p' src/main/claude/claude-structured-child-work-producer.test.ts

Repository: stablyai/orca

Length of output: 29223


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- run verdict and admission ---'
rg -n -C 25 'function agentChildWorkRunVerdict|agentChildWorkRunVerdict|lifetime|stale-invocation|outcome|lastMessage|totalTokens' src/shared/agent-status-child-work-evidence-admission.ts
printf '%s\n' '--- second-ending tests ---'
sed -n '400,560p' src/main/claude/claude-structured-child-work-producer.test.ts
printf '%s\n' '--- notification and run-id tests ---'
rg -n -C 18 'task_notification|pendingClaudeNotification|runId.*undefined|undefined.*current|second ending|stale-invocation|lastMessage.*totalTokens' src/main/claude/*test.ts src/shared/*test.ts

Repository: stablyai/orca

Length of output: 45663


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- spawn result and handle construction ---'
sed -n '90,220p' src/main/claude/claude-child-work-evidence.ts
printf '%s\n' '--- tracker ordering tests ---'
rg -n -C 20 'task_started|task_notification|tool_use_id|delayed|late|notification' src/main/claude/claude-background-task-tracker.test.ts src/main/claude/claude-child-work-evidence.test.ts src/main/claude/claude-structured-child-work-producer.test.ts
printf '%s\n' '--- changed reconciliation diff ---'
git diff 58ba75b5a5fc762e64073b51e481f1832242aa09 bf82728df66ed17e1b0ebab9ae3f43de42ef7a80 -- src/shared/agent-status-child-work-reconciliation.ts src/shared/agent-status-child-work-evidence-admission.ts src/main/claude/claude-child-work-evidence.ts src/main/claude/claude-background-task-tracker.ts
printf '%s\n' '--- notification payload/tool-use fields ---'
rg -n -C 8 \"task_notification|tool_use_id|task_id.*summary|summary.*usage\" src/main/claude src/shared --glob '*.ts' --glob '*.json'

Repository: stablyai/orca

Length of output: 40402


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- notification payloads with tool-use fields ---'
rg -n -C 5 'task_notification' src/main/claude src/shared --glob '*.ts' | rg -n -C 3 'task_notification|tool_use_id|summary|usage'
printf '%s\n' '--- tracker update path ---'
sed -n '140,215p' src/main/claude/claude-background-task-tracker.ts
printf '%s\n' '--- task-id/run-id helpers ---'
rg -n -C 10 'function taskId|function taskAliasId|const taskId|const taskAliasId' src/main/claude/claude-background-task-frames.ts

Repository: stablyai/orca

Length of output: 41867


🏁 Script executed:

#!/bin/bash
set -e
sed -n '1,70p' src/main/claude/claude-child-work-evidence.ts
sed -n '136,150p' src/main/claude/claude-child-work-evidence.ts

Repository: stablyai/orca

Length of output: 3540


Preserve the notification run ID.

Real Claude notifications can include tool_use_id, but pendingClaudeNotification drops it. A delayed notification from toolu_old is then classified as current and can overwrite the newer run's lastMessage and totalTokens.

Suggested fix
-import { record, taskText, taskUsageTotalTokens } from './claude-background-task-frames'
+import { record, taskAliasId, taskText, taskUsageTotalTokens } from './claude-background-task-frames'
...
   return pendingClaudeTaskEnded(id, claudeChildWorkOutcome(message.status), {
     lastMessage: taskText(message.summary),
-    totalTokens: taskUsageTotalTokens(message)
+    totalTokens: taskUsageTotalTokens(message),
+    toolUseId: taskAliasId(message.tool_use_id)
   })

Notifications without tool_use_id remain unclassified and retain the existing same-run behavior.

Child records made every store write and every status notification scale with the
whole store. Each Claude child progress frame cost about 2 ms with 5 chats holding
~200 child records (about 14 ms at ~1,400), and every status change on any lane
re-parsed every child record just to list parent rows.

- The store derives each frozen record's key once instead of re-parsing it on every
  mutation's validation and every alias lookup.
- Settled history is trimmed only when a batch settles something.
- Parent listing and the structured row's revision stamp read the parents and the
  revision directly instead of building a full snapshot.

A progress frame now costs about 0.3 ms at the same size, and listing parent rows no
longer depends on how many child records the store holds.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No new issues in this incremental delta. The performance commit is behavior-preserving; three earlier findings remain open in code it does not touch, so this is not an approval.

Reviewed changes

Only 4f4885a0d8 ("perf(agent-status): keep child records off the status hot paths") landed since the prior pullfrog review — 8 files, +107/-22, no tests. The motivation is that child records made every store write and every status listing scale with the entire store.

  • Frozen-record key memoization — a new agent-status-store-record-keys.ts caches each frozen record's derived key in module WeakMaps (storedAliasKey, storedBindingKey, storedRetiredAlias, storedTombstoneKeyIsValid), and store validation plus alias lookup now use it. Stored records are deep-frozen at insertion, so the cache premise holds; each site is otherwise byte-equivalent to its former inline derivation.
  • Subject serialization memoized — serializeAgentStatusSubject caches by frozen-subject identity and only for frozen inputs.
  • Direct parent listing and revision stamp — getParents()/getRevision() avoid materializing a full snapshot; the listener's listing and the structured row's revision stamp use them.
  • Gated settled trim — trimSettled runs only when a batch actually settled something; only an accepted settle raises that counter, so the 32-settled cap still holds on every batch.

I traced the new fast paths against the prior behavior: the memoized keys are only cached for immutable records, getParents() returns the same frozen records the snapshot parsed, getRevision() supplies exactly the epoch/revision the stamp consumed, and no other AgentStatusStore implementor needed the new methods. Verified pnpm test on the six store/ingest suites (50 passed, 1 expected fail).

ℹ️ Nitpicks

  • server-ingest-structured.ts:64 — const snapshot = …getRevision() now holds a { epoch, revision } pair, not a snapshot. Renaming it (revision) would keep the code honest about what the perf change intentionally avoided building.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

…w the child ended

Interrupting a foreground Claude agent while it runs a tool delivers the spawn call's errored
result before the child's own killed/stopped frames. The spawn result settled the record
`failed` first, and admission then refused the later `cancelled` as a conflicting ending, so an
interrupted child read as a failure.

An errored spawn result now settles the child `unknown`; the child's own terminal frame refines
it to `cancelled` or `failed`. A successful spawn result still settles `succeeded`. The test
replays both frame orders the real CLI produced when interrupted.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No new issues in this incremental delta. The new commit corrects an interrupted foreground child's ending; the three earlier findings remain open, so this is not an approval.

Reviewed changes

Only a366ecca ("an errored Claude spawn result no longer decides how the child ended") landed since the prior pullfrog review — 3 files, +56/-5.

  • Errored spawn results settle unknown — claudeSpawnResults now maps a foreground spawn call's errored tool_result to unknown instead of failed. is_error cannot separate an interrupt (the user's stop is delivered as an errored result, the same conflation claude-result-outcome.ts documents) from a genuine fault, so the child's own terminal frame is left to say which.
  • Tests — the evidence test's expectations move to unknown; the producer test sends a task_notification status: failed after an errored spawn result to prove refinement to failed, and a new it.each replays both frame orders the real CLI produces when interrupting a foreground agent, asserting cancelled.

The bug: the errored spawn result settled the record failed first, and admission's conflictsWithSettled refuses a definite ending that conflicts with a stored definite one, so the later cancelled was rejected as stale-invocation and an interrupted child read as a failure. An unknown ending is refine-only in mergeObservationFacts (keeps a definite outcome while landing last message/tokens) and conflictsWithSettled never rejects it, so the terminal frame now lands the right outcome. applyEnded's agentChildWorkRunVerdict !== 'current' guard still drops a previous run's spawn result, so this does not reach across runs.

Verified: pnpm test on claude-structured-child-work-producer.test.ts and claude-child-work-evidence.test.ts — 15 passed.

ℹ️ Nitpicks

  • The PR description's "What the producer writes" table still documents the spawn-result row as "succeeded, or failed when is_error", which this commit changes to unknown. Worth updating so the stack's contract description matches the code.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

The real CLI ends a foreground agent with its own completed update, then a notification
carrying the final summary and usage, and only then the spawn call's result. Existing tests
modeled the spawn result arriving first, so nothing checked that the notification's summary
and tokens still land on a record the update already settled.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
src/main/claude/claude-structured-child-work-producer.test.ts (1)

550-550: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Assert settlement before the notification.

task_updated queues a successful terminal edge, but the later task_notification also queues a successful terminal edge with the final summary and usage. If the first edge is ignored, the final assertion can still pass. Add the intermediate assertion.

Suggested assertion
    send(system('task_updated', { task_id: 'agent-fg', patch: { status: 'completed' } }))
+   expect(byDescription('Run echo hi command')).toMatchObject({
+     membership: 'settled',
+     outcome: 'succeeded'
+   })

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 70062209-7cdb-45c5-b8e6-9ba8ec582291

📥 Commits

Reviewing files that changed from the base of the PR and between a366ecc and 7efdd97.

📒 Files selected for processing (1)
  • src/main/claude/claude-structured-child-work-producer.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 1 remains after this review.

…e store

With child records on the host, every mutation copied all five store maps and re-validated
every record, and reads scanned every child and alias. A parent status publish cost about
10 ms with 4,000 child records in the store, and a child update about 13 ms.

- A mutation writes into drafts over the committed maps and lands in place; a refused one
  is dropped with nothing to undo. The drafts keep the exact map order a copy would have.
- Only what a mutation touched is re-validated: touched parents, children, aliases, facts
  and tombstones, plus every alias of a touched child and whatever a removed parent owned.
  The full validation stays for snapshot restore.
- The snapshot byte budget is a running total instead of a re-measure.
- Children by parent, facts by parent, aliases by child, aliases by identity and retired
  aliases are indexed, so reads return stored records without scanning or re-parsing.
- The memoized alias identity and tombstone-key checks are gone: indexes derive them once.

A parent publish now costs about 0.015 ms and a child update about 0.06 ms at 40, 1,000 and
4,000 children alike. A seeded fuzz holds the store to the copy-and-validate-everything
path decision for decision, snapshot for snapshot and read for read, and a replica fed the
envelopes ends identical.
The child records were fed from the legacy background-task tracker's display decisions, so
they inherited rules that are not truth: a turn ending swept foreground children, a roster
omitting a background child settled it, a foreground spawn call's result ended the child,
and a new background start after any roster produced no record. Captured from the real CLI,
an agent moved to the background keeps its own shell running for 40 s after the parent's
turn ends, and that shell was settled `unknown` at the parent's `result`. Replayed with the
spawn result ahead of the roster, the same agent settled as a false success and was then
revived as a spurious second run.

A new decoder reads the task frames directly. `task_started` opens a child (a start for an
ended task id is a restart, the way messaging a finished agent resumes it), progress and a
live `task_updated` update it, and a terminal `task_updated` or `task_notification` ends it.
Rosters, turn ends and spawn results say nothing about a child. Every child in every capture
gets its own terminal frame, so no evidenced ending is lost. The notification's `tool_use_id`
names the run that ended (captured on a resumed agent's second run), so an ending from a run
that is already over no longer ends the current one; a run id the record never saw still
ends it, so nothing strands.

The tracker, its settled-task retention and the frame readers are back to exactly what main
has: the aggregate-roster split and the restart holding map are deleted, and the legacy row is
unchanged by construction.
…of erasing them

When a structured session ended, the reducer removed every child record it held, finished
or not, so a reader could no longer tell how the session's work had ended. Now a child still
live when its session ends settles `unknown` (nothing reported how it ended), and a child that
had already ended keeps its outcome. The records still die with their parent: closing or
releasing the session drops the parent row, and the store drops its children with it. A
child's own outcome arriving after the session ended still refines the `unknown`.

The `inventory` and `turn-ended` edges, and the rules that settled children on a roster
omission or at a turn boundary, are deleted: no producer sends them any more. A restart is
now its own flag on a live edge, which is what a producer reports when a finished child
starts again under the same run handle.
…eal host

Scrubbed cuts of five Claude CLI 2.1.280 stream-json captures (ids, paths and prompts replaced,
frame order and relative clock kept), replayed through the adapter into a hook server:

- an agent moved to the background keeps its own shell live past the parent's turn, and the
  shell settles at its own notification's time;
- the same capture with the spawn result ahead of the move ends the agent once, from its own
  notification, with no second run;
- a roster that omits a background child without its own ending leaves it live;
- a session that ends settles what still runs `unknown` and keeps every record;
- messaging a finished background agent opens its second run, which ends from its own frame;
- interrupts in both captured orders end `cancelled`, and a finished foreground agent keeps
  its summary and usage.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No new code issues in this incremental delta. The producer rearchitecture and the in-place store rewrite are coherent and strongly tested; two earlier findings remain open in code this delta does not touch, and the PR description no longer matches the producer it now ships.

Reviewed changes

Since the prior review baseline (7efdd97), four commits landed:

  • Producer rearchitecture — the tracker no longer feeds child records. A standalone ClaudeChildWorkDecoder reads task frames and queues live / ended / session-ended edges; a child is live from task_started until its own terminal frame, so a roster, a turn ending, or a spawn call's result no longer settles one. inventory and turn-ended edges are deleted from the contract, replaced by a restart flag for a start reported on an ended child. ClaudeBackgroundTaskTracker reverts to its base legacy-only shape, and the restarts / aggregate-roster modules are removed.
  • Session end settles instead of erasing — session-ended now settles the session's still-live children unknown (a later definite ending still refines it) and keeps them under the 32-settled cap; the reducer's settleLive replaces the old removal.
  • Store writes in place — mutations draft over the committed maps, revalidate only touched records and their dependents, enforce the byte budget from tracked per-record sizes, then commit drafts and indexes. getChildren / getAliasesForChild / alias resolution read the new indexes. A copying-store oracle holds the in-place store to the prior decisions and snapshots, decision for decision.
  • Tests — real Claude CLI 2.1.280 captured frame orders replayed through the adapter into a real hook server (interrupt orders, foreground success, moved-to-background, message-resumed agent, session close), plus decoder, reducer, and store equivalence / bounds / scaling suites.

ℹ️ The PR description still documents the removed producer

The body's "What Changed" producer sections and Testing tables describe code that no longer exists at this head: tracker-queued evidence, the inventory and turn-ended edges, claude-background-task-restarts.ts, "the session's records are removed" on ended, and the frame-by-frame shadow check with its ablation table. Downstream PRs (#22553, #22614) read this description as the producer contract, so it should be refreshed.

Technical details
# PR description no longer matches the shipped producer

## Affected sites
- PR body `### The path from a Claude frame to a record, hop by hop` — still routes evidence through the tracker's `drainClaudeChildWork`; it now comes from `ClaudeChildWorkDecoder`.
- PR body `### What the producer writes` table — lists `inventory` (`background_tasks_changed`) and `turn-ended` (`result` / new turn) rows and "session `ended` / close → the session's records are removed". Both edge types were deleted; a restart is now a `restart: true` live edge, and session end settles live children `unknown` and keeps them.
- PR body `### The tracker (legacy row unchanged)` / `### Ported from #21279` — describes `claude-background-task-restarts.ts` and `claude-background-task-aggregate-roster.ts`, both deleted; the tracker is back to its base shape and carries no `toolUseId`.
- PR body `## Testing` — the shadow check and the per-ablation table reference `foldAgentLeadStatus` parity and inventory/turn-ended ablations; that harness was replaced by the captured-frame replay tests.

## Required outcome
The description's mechanism, edge vocabulary, and testing sections reflect the decoder model: own-frame endings only, no inventory/turn-ended edges, session-end settles, one decoder state, and the captured-frame replay tests.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

…o a rebuild

The copying-store fuzz never reaches the snapshot byte budget, so a drift in
the running byte total (or any index the public reads do not surface) passed
it. After every fuzzed step, including refusals, compare every index with one
rebuilt from the committed maps.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No new issues in this incremental delta. The one commit since the prior review is test-only and the added test is discriminating; two earlier findings remain open in code it does not touch, so this is not an approval.

Reviewed changes

Since the prior review baseline (ed592e8a83), one commit landed: 94e5159f52 (test-only, +53/-1).

  • Index-equivalence fuzz test — src/shared/agent-status-store-in-place.test.ts now drives commitAgentStatusStoreMutation over 1,500 mutations at seeds 3 and 99 and, after every step, asserts the running AgentStatusStoreIndexes (the per-parent / per-child / per-identity sets, each table's map order, and recordBytes) equals indexAgentStatusStoreState rebuilt from the committed maps. Both committed and refused mutations are exercised.

I ran pnpm test src/shared/agent-status-store-in-place.test.ts: 7 passed (45s). The new case is not vacuous — the sibling oracle case on the same mutations() builder asserts accepted > 300 of 1,500 at its seeds, so commits reach the index path under check.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status: ready for review at 94e5159f52

Five review loops plus an independent architecture review ran on this PR. The final loop came back clean, the readiness checklist passes at the start and the end, CI is green, and a live Electron check of this head shows no visible change and correct host records.

What changed during review

  • Store writes cost what they touch (4f4885a0d8, c8a1f37e04, 94e5159f52). Every store mutation used to copy and re-validate the whole store, so once child records were on the host, every child update and every unrelated parent status publish paid for every child. A parent publish at 4,000 children went from 10.2 ms to 0.011 ms. The store now applies drafts in place, validates only what a mutation touched, keeps indexes and a running byte total. It adds two reads, getParents() and getRevision(), and its existing API is unchanged. A seeded fuzz holds it to the old copy-and-validate path, and a test pins the indexes and byte total against a rebuild.
  • A child ends only on its own frame (a366eccad5, 368ea4db3c, 35f97191b5, ed592e8a83). Real Claude CLI captures showed three rules settling children early: the turn-end sweep ended a subagent's own shell 39 s before it finished, the spawn result produced a false success and a phantom second run, and the roster omission only ever duplicated the child's own ending. A new standalone decoder now ends a child only on its own terminal task_updated or task_notification, or when the session ends. The legacy tracker is byte-identical to main again, and session end now settles live records unknown instead of deleting them.
  • Interrupts read cancelled. An interrupt delivers the spawn call's errored result before the child's own stop, which used to record the child as failed.

Verification

  • pnpm tc:node, tc:web, tc:cli; oxlint on every changed file; check:code-quality:changed with 0 findings; CI 26 passed, 0 failed.
  • Scrubbed replays of five real CLI captures run through the real adapter into a real hook server. They cover a normal foreground finish, interrupts in two frame orders, an agent moved to the background with its own shell, and a finished background agent resumed by a message. Each new mechanism has a red-without-it test.
  • Live Electron check at this head, with screenshots in the PR body: foreground subagent, a background agent whose shell outlives the parent's turn, Stop mid-shell (records read cancelled), and background shell plus agent. Every child got exactly one record, nothing settled early, and the log had no errors.

Known limits (not regressions)

  • A child that dies without any terminal frame stays live until the session ends. No capture shows one.
  • The interrupted turn's tool row reads "Ran 1 subagent failed". That row comes from the journal translator, which this PR does not change, and it reads the same on main.
  • Not captured yet: workflow or monitor tasks, nested agents, and a message to a background agent that is still running.
  • Waiting and blocked children are still not produced, as the PR body describes.

For the stacked PRs

#22553, #22619, #22565, #22614 and #22634 need a rebase:

  • the inventory and turn-ended evidence edges are gone;
  • session-ended settles and keeps records instead of removing them;
  • a live edge can carry restart: true;
  • the tracker's evidence helpers and the restarts map are deleted.

The full list is in the PR body's Notes.

Resolve conflicts with the terminal-handoff removal (#22783): take main's runtime wiring and integration test, and re-apply this branch's Claude child-work evidence wiring and the status-sink child-work test.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No new issues in this merge-only delta — two earlier findings remain open, so this is not an approval.

Reviewed changes

Only 1a9c5ee42e (a merge of origin/main into the branch) landed since the prior pullfrog review (94e5159f52). main had meanwhile removed the unused terminal handoff and advanced the model-catalog work, so the merge reconciles this PR against that base.

  • Claude integration test realigned — the suite dropped its handoffTransport scaffolding for a host statusSink; publishChildWork now collects into childWork, and the assertion proves a task_started frame reaches the sink under the session's own address.
  • Adapter deps merged — structured-claude-runtime-adapter.ts now carries main's modelCatalog alongside this PR's onChildWorkEvidence, and structured-agent-session-runtime.ts keeps the onChildWorkEvidence wiring.
  • Base alignment — 686 files of main content brought in; no conflict-resolution bug found in the files this PR owns.

Verified at this head: pnpm tc:node exits 0, and 6 focused suites (Claude integration, status-feed child work, ownership, sink wiring, runtime, host) — 77 tests — pass.

The two open findings from earlier reviews live in code the merge does not touch: the 256-live cap is still enforced only on the create path in agent-status-child-work-evidence-admission.ts, and an evicted-then-revived child can still lose its token count until the next task_progress.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@brennanb2025
brennanb2025 merged commit acf8e67 into main Sep 25, 2026
38 checks passed
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