Skip to content

feat(agent-status): add the canonical store and child-work contract - #20717

Merged
brennanb2025 merged 3 commits into
mainfrom
brennanb2025/pr2a-2-canonical-store-contract
Sep 15, 2026
Merged

brennanb2025 merged 3 commits into
mainfrom
brennanb2025/pr2a-2-canonical-store-contract

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 9 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1533 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1533
Prod 22 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​3134 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​3133

ELI5

Adds the new store's contract — the canonical row shape, the child-work record, and the transport
envelope — as new files. Nothing imports them yet. Pure addition: 25 files, +4079, zero deletions.

Why this exists

This is the contract the rest of the migration is built against: a status row keyed by an
Orca-minted runId rather than by its pane, with the provider's own session id kept as an alias that
may legitimately point at more than one live run.

That alias is a set, not a single value, and that is not a style choice — it was measured. Two
concurrent claude --resume <same id> executions both report that id and write divergent branches, so
a provider id does not uniquely name a live agent. A single-valued alias would be silently wrong on
exactly that case.

It also lands Amendment A's child-work record: one collection owning all five kinds
(agent | workflow | command | monitor | unknown), each child keyed by a host-minted childWorkId.
The earlier design kept an agent-only canonical collection plus a separate background-task state —
but the chat strip renders agent-kind tasks too, so that split would have represented the same task
canonically twice.

What a reviewer should check first

Whether these are the shapes you want frozen, since three later PRs build on them — particularly the
alias-set cardinality and the child-work state vocabulary, which must be able to express
unverifiable so a child on a host we cannot reach is never reported as idle.

Second: this PR's ablation is weak by nature. Reverting brand-new modules makes their suites fail to
import, which proves the tests exercise the code but little else. There is no prior behavior to ablate
against in a contract-only change; the real test is the PR that consumes it.

Scope

Second of three, stacked on #20716. Nothing consumes these types yet — that is the next PR.

Post-review hardening

The review pass added focused reliability fixes without adding consumers: delayed observations are fenced after resume, bounded invocation aliases can be safely reused, snapshot admission accounts aggregate UTF-8 bytes with immutable-record caching, and batch child removal cleans aliases in one pass.

Validation at commit a90aacd83e: 9 focused contract suites passed (83 tests plus 1 intentional expected-failure for the deferred epoch-ordering integration gate), pnpm tc:node, changed-code quality, formatting, and pre-commit checks passed; selective ablation made the four new regression tests fail when the corresponding production fixes were reverted, then pass after restoration. The all-new-files-reverted arm only reports missing test files because this PR intentionally has no production consumers yet.

The remaining integration gate is binding A→B→delayed-A ordering to the trusted connection before the consuming PR wires these modules; loss of contact remains unverifiable, never death.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Electron smoke screenshot at d94b0d1: an isolated, hidden/background Orca dev instance rendering the Workspace board with a disposable QA Sandbox folder workspace. The canonical contracts in this PR are not imported or wired to the UI; this image verifies only existing app rendering, not canonical-store behavior.

Full Orca workspace board screenshot

@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

Two fail-closed gaps are worth resolving before these shapes are frozen: a mutation can commit a store that its own snapshot then rejects, and proven-new can take over a still-live child's alias. Details inline; two design questions and a nit below.

Reviewed changes

Reviewed the full 25-file, +4079/−0 diff at d94b0d1 — the second of three stacked PRs, adding the canonical agent-status store, the child-work record/admission contract, and the transport envelope. Ran the 7 new suites (45 pass), pnpm tc:node, and the changed-code quality gate (all clean). Most of the review went to the admission state machine and the store's commit/validate/persist invariants.

  • Child-work vocabulary + codec (agent-status-child-work.ts, -codec.ts) — one record owning all five kinds, a state vocabulary that can express unverifiable, bounded invocation history, fail-closed parsing.
  • Admission state machine (agent-status-child-work-admission*.ts) — identity is an Orca-minted childWorkId; aliases are keyed by parent/provider/segment/kind/aliasKind/alias and carry an invocation fence.
  • Store (agent-status-store*.ts) — revisioned immutable state, clone-validate-commit mutations, tombstone removals, bounded snapshot persistence, and a replica that replays only contiguous same-epoch mutations.
  • Relay-context guard (src/relay/agent-status-store-relay-context.test.ts) — asserts the shared core imports no main/renderer/electron.

ℹ️ Alias cardinality: a provider id still maps to one child per (parent, segment, kind)

The PR body says the provider-id alias "may legitimately point at more than one live run" and that a single-valued alias would be silently wrong. In this diff, serializeAgentChildWorkAliasKey keys aliases by parent/provider/segmentId/kind/aliasKind/alias only — childWorkId and fence are excluded — and the alias map holds exactly one childWorkId per key. A provider id therefore points at multiple children only when their segmentId (or kind/aliasKind) differs; two concurrent same-segment runs collide, and announce cannot represent both. Please confirm the producer always varies segmentId per concurrent run, otherwise the stated set-cardinality isn't actually expressible.

Technical details
# Alias identity is single-valued per scope

## Affected sites
- `src/shared/agent-status-child-work-alias.ts:137-159` — `serializeAgentChildWorkAliasKey` includes parent/provider/segmentId/kind/aliasKind/alias; excludes childWorkId and fence.
- `src/shared/agent-status-store-state.ts:132-147` — `validateAgentStatusStoreState` treats the alias key as unique, so one `childWorkId` per key.
- `src/shared/agent-status-child-work-admission-operations.ts:79` — a second concurrent binding with a different fence is rejected as `stale-invocation` under `current`.

## Required outcome
Confirm the producer always varies `segmentId` for concurrent same-provider-id runs (so two live children can coexist), or change the alias shape/key so one provider id can bind multiple children without relying on a segment side-channel.

ℹ️ Replica adopts any different-epoch snapshot

applySnapshot only rejects a same-epoch non-advancing snapshot; any different-epoch snapshot is mirrored unconditionally. Mutation envelopes are strictly epoch-guarded, but a delayed or replayed predecessor-epoch snapshot will roll the replica back until the next snapshot arrives. Is epoch ordering enforced by the transport, or should the replica refuse a snapshot whose epoch it has already moved past?

Technical details
# Snapshot epoch is not ordered

## Affected sites
- `src/shared/agent-status-store.ts:115-128` — replica `applySnapshot` only guards same-epoch regressions; a different epoch always replaces state.
- `src/shared/agent-status-store.ts:141-148` — mutation replay is guarded by exact `envelope.epoch === state.epoch`, so the snapshot path is the looser one.

## Open question for the human
Does the transport guarantee snapshots are delivered at most once and in epoch order? If not, should a replica refuse a snapshot whose epoch is older than one it has already adopted?

ℹ️ Nitpicks

  • adopt/resume/reparent/authorizeStop pass request.parent straight into agentStatusSubjectsEqual (agent-status-child-work-admission-core.ts:164), which throws on a malformed subject, whereas announce parses and returns invalid. The parameter is typed AgentStatusSubject so in-repo callers can't hit this, but if these become the untrusted ingress boundary, mirroring announce's parse-and-reject would keep the failure mode consistent.

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

Comment thread src/shared/agent-status-store-state.ts Resolved
const bindings = resolveAgentChildWorkAliasRecords(store, lookupAliases)
const exact = bindings.filter((binding) => agentChildWorkFencesEqual(binding.fence, fence))
const exactIds = new Set(exact.map((binding) => binding.childWorkId))
if (request.lifetime === 'proven-new') {

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.

announce with lifetime: 'proven-new' skips the stale-binding guard the current path applies — it inspects only exact and never bindings. Because the alias key omits fence, a proven-new announce can silently move an alias off a still-live child onto a newly minted one, leaving the predecessor membership: 'live' but unreachable by alias; the identical input under current is rejected as stale-invocation.

Technical details
# proven-new can capture a live child's alias

## Affected sites
- `src/shared/agent-status-child-work-admission-operations.ts:55-81` — `current` fails closed when `bindings.length !== exact.length` (`:79`); the `proven-new` branch (`:58-78`) returns before that check and only inspects `exact` (`:59`).
- `src/shared/agent-status-child-work-alias.ts:137-159` — the key excludes `childWorkId` and `fence`, so `upsertAliases` (`agent-status-store-mutation.ts:153-169`) overwrites the prior binding.

## Evidence
1. `announce` a live child-1 with alias `T@inv1` -> accepted.
2. `announce` the same alias `T` with fence `inv2` and `lifetime: 'proven-new'` -> accepted, child-2 minted; alias `T` now resolves to child-2 while child-1 remains `membership: 'live'` / `state: 'working'` with no alias.

## Required outcome
Either `proven-new` must also fail closed when the alias already binds another child (`ambiguous` / `id-collision`) unless that predecessor is settled, or the rebind must settle/replace the predecessor so the store never reports an abandoned live child. If the producer is expected to settle the predecessor first, encode that expectation here.

moved,
aliases,
false,
oldAliases.map(serializeAgentChildWorkAliasKey)

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.

reparent to the same parent is unconditionally store-rejected: the moved aliases keep the same parent, so their serialized keys equal the removeAliases keys passed here, and one mutation removes then re-adds each key at the same revision — tombstone.revision >= alias.revision (agent-status-store-state.ts:143) then fails validation. Skipping the removal when toParent equals fromParent (or removing only keys whose parent actually changed) fixes an idempotent reparent that currently errors.

@brennanb2025
brennanb2025 changed the base branch from brennanb2025/pr2a-1-legacy-ingress-isolation to main September 15, 2026 17:30
@brennanb2025
brennanb2025 force-pushed the brennanb2025/pr2a-2-canonical-store-contract branch from d94b0d1 to c1ac898 Compare September 15, 2026 17:44
@coderabbitai

coderabbitai Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 32322b80-b00d-42b1-8461-00a51985f9e4

📥 Commits

Reviewing files that changed from the base of the PR and between e544b9b2a0d538e2a1fd88df20463e1b3e76fdde and a90aacd.

📒 Files selected for processing (1)
  • src/shared/agent-status-store-snapshot-budget.ts

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


📝 Walkthrough

Walkthrough

This change adds a shared agent-status store with strict codecs, mutation and snapshot contracts, persistence helpers, transport envelopes, tombstones, and authority or replica behavior. It adds child-work models, alias handling, admission operations, stop authorization, legacy projections, and freshness rules. Tests cover validation, mutation and transport behavior, admission edge cases, alias collisions, bounds, and relay use without Electron-specific imports.

Priority: ⬇️ Low

Merge Risk: 🟡 Moderate · up to a90aa

Store consumers can receive rejected valid parent updates, reused child identities, or reverted replica state. Resolve these state-consistency issues before merging.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 1.39% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 144 functions across 31 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description explains the purpose, scope, design decisions, testing, and hardening, but it does not follow the required template. It omits or leaves incomplete sections such as What Changed, Linked… Update the description to include every required template section. Add a valid linked issue after Fixes #; document the changes under ## What Changed; add ## Visual Proof with N/A and a reason because there is no UI change; complete…
✅ Passed checks (3 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 identifies the primary change: adding the canonical agent-status store and child-work contract.
Full details: Description check

Explanation

The description explains the purpose, scope, design decisions, testing, and hardening, but it does not follow the required template. It omits or leaves incomplete sections such as What Changed, Linked Issue with a populated Fixes #, Visual Proof with N/A and a reason, Testing checkboxes, AI Disclosure, Review, the upstream-boundary checkbox, Notes, and the Checklist.

Resolution

Update the description to include every required template section. Add a valid linked issue after Fixes #; document the changes under ## What Changed; add ## Visual Proof with N/A and a reason because there is no UI change; complete the Testing checkboxes and commands or state that CI will cover them; complete the AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist sections.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch

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.

Actionable comments posted: 4

🧹 Nitpick comments (2)
src/shared/agent-status-child-work-admission-core.ts (1)

33-45: 🚀 Performance & Scalability | 🔵 Trivial | 🏗️ Heavy lift

Avoid repeated full-store snapshots in admission helpers.

getSnapshot() rebuilds and validates all five collections, performs full-store serialization, and deep-freezes the result. The admission paths invoke the helpers as follows: announce uses 2 calls per branch, adopt 4, resume 2, reparent 3, and authorizeAgentChildWorkStop 1. The 14 source call sites therefore repeat O(store) work for child and alias reads.

This is a real scalability cost in the shared admission contract, but the PR does not yet wire these operations to production consumers. Treat it as a recommended refactor, not a major runtime issue.

Add read methods that avoid snapshots. Use the child map for getChild(childWorkId) and direct alias-key reads for resolveAgentChildWorkAliasRecords. Add a maintained child-to-alias index for getAliasesForChild(childWorkId); the existing aliases map is keyed by alias key and cannot provide that lookup in O(aliases) by itself.

src/shared/agent-status-store-status-codec.ts (1)

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

Rebuild orchestration from validated top-level keys instead of spreading the input.

parseOrchestration validates the known scalar fields and only checks that attention is a record, then returns { ...value }. parseAgentStatusIpcPayloadCopy assigns that result to parsed.orchestration, and parseAgentStatusParentInput stores it as an AgentStatusIpcPayload. Unknown top-level orchestration properties therefore survive the canonical parent copy and violate the SAFETY invariant at line 243.

The proposed change should whitelist the validated top-level fields. It does not establish a nested attention parser or a runtime failure from extra nested properties.

♻️ Proposed shape for the return value
-  return { ...value }
+  return {
+    taskId: value.taskId,
+    dispatchId: value.dispatchId,
+    ...Object.fromEntries(
+      optionalStrings
+        .filter((key) => value[key] !== undefined)
+        .map((key) => [key, value[key]])
+    ),
+    ...(value.dispatchStatus !== undefined ? { dispatchStatus: value.dispatchStatus } : {}),
+    ...(value.attention !== undefined ? { attention: value.attention } : {})
+  }

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: df061c95-4e04-4c1e-8374-fc50f36be22c

📥 Commits

Reviewing files that changed from the base of the PR and between 9ab0a18 and c1ac898.

📒 Files selected for processing (25)
  • src/relay/agent-status-store-relay-context.test.ts
  • src/shared/agent-status-child-work-admission-collision.test.ts
  • src/shared/agent-status-child-work-admission-core.ts
  • src/shared/agent-status-child-work-admission-operations.ts
  • src/shared/agent-status-child-work-admission.test.ts
  • src/shared/agent-status-child-work-admission.ts
  • src/shared/agent-status-child-work-alias.ts
  • src/shared/agent-status-child-work-codec.ts
  • src/shared/agent-status-child-work-freshness.ts
  • src/shared/agent-status-child-work-projection.test.ts
  • src/shared/agent-status-child-work-projection.ts
  • src/shared/agent-status-child-work.test.ts
  • src/shared/agent-status-child-work.ts
  • src/shared/agent-status-store-codec.ts
  • src/shared/agent-status-store-contract.ts
  • src/shared/agent-status-store-fact-codec.ts
  • src/shared/agent-status-store-mutation.ts
  • src/shared/agent-status-store-parent.ts
  • src/shared/agent-status-store-persistence.ts
  • src/shared/agent-status-store-state.ts
  • src/shared/agent-status-store-status-codec.ts
  • src/shared/agent-status-store.test.ts
  • src/shared/agent-status-store.ts
  • src/shared/agent-status-transport-envelope.test.ts
  • src/shared/agent-status-transport-envelope.ts

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

Comment on lines +117 to +120
...(input.firstObservedAt === undefined && previous?.firstObservedAt !== undefined
? { firstObservedAt: previous.firstObservedAt }
: {}),
revision

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 | 🟠 Major | ⚡ Quick win

Keep parent firstObservedAt immutable.

When upsertParent updates an existing parent, an explicit input.firstObservedAt replaces the stored value. The analogous child update rejects such changes, and snapshot restoration preserves the stored timestamp. No supported update path requires replacing it, so this can corrupt canonical observation history.

Reject mismatches or always retain the previous value.

Proposed fix
   const previous = state.parents.get(key)
+  if (
+    previous?.firstObservedAt !== undefined &&
+    input.firstObservedAt !== undefined &&
+    input.firstObservedAt !== previous.firstObservedAt
+  ) {
+    return false
+  }
   const record = parseAgentStatusParentRecord({

Comment on lines +53 to +55
if (subject.kind === 'pty' && status?.paneKey !== subject.paneKey) {
return false
}

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
# Find parent inputs built for `pty` subjects and check whether any omit `status`.
rg -nP --type=ts -C 8 'parseAgentStatusParentInput|AgentStatusParentInput|parent:\s*\{' src cloud | rg -n -C 8 "kind: 'pty'" || true

Repository: stablyai/orca

Length of output: 151


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- focused file ---'
cat -n src/shared/agent-status-store-parent.ts | sed -n '1,140p'
printf '%s\n' '--- relevant declarations and callers ---'
rg -n -C 5 --glob '*.ts' 'parseAgentStatusParentInput|AgentStatusParentInput|applyMutation|paneKey' src cloud

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -e
log=/tmp/coderabbit-shell-logs/shell-output-OF9tdJ
printf '%s\n' '--- saved log start ---'
sed -n '1,220p' "$log"
printf '%s\n' '--- exact symbol locations ---'
rg -n --glob '*.ts' 'parseAgentStatusParentInput|AgentStatusParentInput' src cloud
printf '%s\n' '--- PTY parent-like constructions ---'
rg -n -C 6 --glob '*.ts' "kind:\s*['\"]pty['\"]" src cloud | rg -n -C 6 'parent|subject|status|kind'

Repository: stablyai/orca

Length of output: 24383


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- store contract ---'
cat -n src/shared/agent-status-store-contract.ts
printf '%s\n' '--- store codec ---'
cat -n src/shared/agent-status-store-codec.ts | sed -n '1,230p'
printf '%s\n' '--- applyMutation and parent usage ---'
rg -n -C 8 --glob '*.ts' 'applyMutation|parent\s*:' src | head -n 600
printf '%s\n' '--- focused parent tests ---'
rg -n -C 8 --glob '*agent-status*test.ts' 'parent|pty' src/shared | head -n 600

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- agent-status files ---'
git ls-files '*agent-status*' | sort
printf '%s\n' '--- applyMutation definitions/usages ---'
rg -n -C 12 --glob '*.ts' 'applyMutation' src/shared src/main src/renderer | head -n 500
printf '%s\n' '--- parent-specific tests ---'
for f in $(git ls-files '*agent-status*test.ts' | sort); do
  if rg -q 'parent|parseAgentStatusParentInput|pty' "$f"; then
    printf '%s\n' "--- $f ---"
    rg -n -C 8 'parent|parseAgentStatusParentInput|kind:\s*['"'"'"'"'"']pty['"'"'"'"'"']' "$f" | head -n 300
  fi
done

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- store test helpers and parent tests ---'
cat -n src/shared/agent-status-store.test.ts | sed -n '1,190p'
printf '%s\n' '--- parent contract documentation ---'
rg -n -C 10 'parent|status|PTY|pty' docs/reference/agent-status-store.md
printf '%s\n' '--- mutation implementation ---'
cat -n src/shared/agent-status-store-mutation.ts | sed -n '1,260p'

Repository: stablyai/orca

Length of output: 39307


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- PTY subject construction outside tests ---'
rg -n -C 8 --glob '*.ts' --glob '!*.test.ts' 'makePtyAgentStatusSubject|kind:\s*['"'"'"'"'']pty['"'"'"'"'']' src | head -n 500
printf '%s\n' '--- mutation calls outside tests ---'
rg -n -C 5 --glob '*.ts' --glob '!*.test.ts' '\.applyMutation\(' src/shared src/main src/relay | head -n 500

Repository: stablyai/orca

Length of output: 304


Guard the PTY pane-key comparison when status is absent.

status is optional, but status?.paneKey !== subject.paneKey evaluates to true when a pty parent has no status. The parser returns null, so applyMutation rejects the mutation.

🐛 Proposed fix
-  if (subject.kind === 'pty' && status?.paneKey !== subject.paneKey) {
+  if (subject.kind === 'pty' && status !== undefined && status.paneKey !== subject.paneKey) {
     return false
   }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (subject.kind === 'pty' && status?.paneKey !== subject.paneKey) {
return false
}
if (subject.kind === 'pty' && status !== undefined && status.paneKey !== subject.paneKey) {
return false
}

Comment on lines +115 to +122
if (
snapshotApplied &&
snapshot.epoch === state.epoch &&
snapshot.revision <= state.revision
) {
return false
}
const mirrored = agentStatusStoreStateFromSnapshot(snapshot, snapshot.epoch)

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 | 🟠 Major | 🏗️ Heavy lift

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect all snapshot application paths and any transport ordering guarantees.
rg -n -C5 --type=ts '\bapplySnapshot\s*\(|\bapplyTransportEnvelope\s*\(' src
rg -n -C5 --type=ts 'epoch|reconnect|snapshot|replay|sequence' src/relay src/shared

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- agent-status-store symbols and implementation ---'
rg -n 'agentStatusStoreStateFromSnapshot|snapshotApplied|applySnapshot|applyTransportEnvelope|epoch|revision' src/shared/agent-status-store.ts
sed -n '1,220p' src/shared/agent-status-store.ts

printf '%s\n' '--- exact snapshot application bindings ---'
rg -n --glob '*.ts' 'agentStatusStoreStateFromSnapshot|applySnapshot\s*\(|applyTransportEnvelope\s*\(' src --glob '!**/*.test.ts' --glob '!**/*.spec.ts' | head -n 240

Repository: stablyai/orca

Length of output: 8452


🤖 get_repo_knowledge executed:

get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions

Length of output: 30140


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- agent-status files ---'
git ls-files '*agent-status*' '*status*transport*' | head -n 160

printf '%s\n' '--- store construction and transport calls ---'
rg -n --glob '*.ts' --glob '*.tsx' 'createAgentStatusStore|applyTransportEnvelope|applySnapshot\(' src --glob '!**/*.test.ts' --glob '!**/*.spec.ts' | head -n 300

printf '%s\n' '--- transport contract and codec ---'
for f in src/shared/agent-status-transport-envelope.ts src/shared/agent-status-store-codec.ts src/shared/agent-status-store-contract.ts src/shared/agent-status-store-state.ts; do
  if [ -f "$f" ]; then
    echo "### $f"
    sed -n '1,280p' "$f"
  fi
done

Repository: stablyai/orca

Length of output: 10366


🏁 Script executed:

#!/bin/bash
set -u

printf '%s\n' '--- exact store construction and transport calls ---'
rg -n --glob '*.ts' --glob '*.tsx' 'createAgentStatusStore|applyTransportEnvelope|applySnapshot\(' src --glob '!**/*.test.ts' --glob '!**/*.spec.ts' || true

printf '%s\n' '--- relay and renderer agent-status transport files ---'
for f in \
  src/relay/agent-status-store-relay-context.test.ts \
  src/renderer/src/hooks/useIpcEvents-agent-status-snapshot-replay.test.ts \
  src/renderer/src/hooks/useIpcEvents-agent-status-snapshot-hydration.test.ts \
  src/renderer/src/hooks/ipc-events/agent-status-event-applicator.ts \
  src/renderer/src/hooks/ipc-events/agent-status-ipc-bridge.ts \
  src/renderer/src/hooks/ipc-events/agent-status-listeners.ts \
  src/main/ipc/agent-status-ipc-boundary.ts \
  docs/reference/agent-status-store.md
do
  if [ -f "$f" ]; then
    echo "### $f"
    sed -n '1,320p' "$f"
  fi
done

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -u

printf '%s\n' '--- shared store files ---'
git ls-files 'src/shared/agent-status-store*' 'src/shared/agent-status-transport-envelope*' 'src/relay/*agent-status*'

printf '%s\n' '--- epoch and snapshot tests/docs ---'
rg -n -C4 --glob '*.ts' --glob '*.md' \
  'predecessor|stale|replay|connection|incarnation|epoch|snapshot|applyTransportEnvelope' \
  src/shared/agent-status-store* src/relay docs/reference/agent-status-store.md 2>/dev/null || true

printf '%s\n' '--- transport envelope and store codec/state definitions ---'
for f in src/shared/agent-status-transport-envelope.ts src/shared/agent-status-store-codec.ts src/shared/agent-status-store-state.ts docs/reference/agent-status-store.md; do
  if [ -f "$f" ]; then
    echo "### $f"
    sed -n '1,260p' "$f"
  fi
done

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -u

printf '%s\n' '--- exact shared store paths ---'
git ls-files 'src/shared/agent-status-store*' 'src/shared/agent-status-transport-envelope*'

printf '%s\n' '--- relevant shared store tests and docs ---'
for f in $(git ls-files 'src/shared/agent-status-store*.test.ts' 'src/shared/agent-status-transport-envelope*.test.ts'); do
  echo "### $f"
  rg -n -C5 'epoch|snapshot|stale|replay|connection|incarnation|applyTransportEnvelope|applySnapshot' "$f" || true
done

for f in src/shared/agent-status-transport-envelope.ts src/shared/agent-status-store-codec.ts src/shared/agent-status-store-state.ts docs/reference/agent-status-store.md; do
  if [ -f "$f" ]; then
    echo "### $f"
    sed -n '1,260p' "$f"
  fi
done

Repository: stablyai/orca

Length of output: 44897


Reject snapshots from older authority incarnations. Replica applySnapshot rejects stale revisions only when the snapshot epoch matches state.epoch. applyTransportEnvelope forwards every snapshot envelope directly to it, and the snapshot envelope has no incarnation or generation field. A delayed epoch-a snapshot can therefore replace the replica state after it accepts epoch-b. Track the authority connection generation and reject predecessor snapshots before restoring state.

@brennanb2025
brennanb2025 force-pushed the brennanb2025/pr2a-2-canonical-store-contract branch from c1ac898 to f144127 Compare September 15, 2026 20:03
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status

The canonical store/child-work contract is clean after the hardening pass in e544b9b2a0. The fixes close four concrete contract issues: stale observations after resume are fenced, bounded invocation aliases can be retired and safely reused, snapshot admission enforces aggregate UTF-8 bytes with immutable-record caching, and batch child removal performs one alias-map cleanup pass.

Validation:

  • 9 focused contract suites: 83 passed + 1 intentional expected-failure (the deferred A→B→delayed-A trusted-connection gate).
  • pnpm tc:node, changed-code quality, formatting, pre-commit hooks, and git diff --check: passed.
  • Final-head ablation: reverting only the new production fixes caused 4 regression-test failures; restoring them returned 15/15 passing. Reverting all brand-new modules produced the expected no-test-files result, so that arm is weak by design for an import-only contract PR.
  • Electron smoke evidence (run by a non-Grok Codex worker, hidden/background CDP): screenshot. It verifies app boot/render only because these modules have no UI consumer yet; mobile, SSH, and Windows runtime QA are likewise not applicable to this shared, unimported contract.

No in-scope findings remain. The consuming PR must bind A→B→delayed-A ordering to a trusted connection before enabling replica consumers; loss of contact remains unverifiable, never death. CI checks are still running on the pushed head.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

static analysis is red with two audit:anti-slop errors — one is from this branch, one is inherited from main.

src/shared/agent-status-store-snapshot-budget.ts:10:46
  Parameter `record` uses the broad `object` type. Accept a named owner type;
  parse external input at its boundary before calling this function.

mobile/src/test-support/rpc-recording/native-mounting-substitutes.ts:45:14
  Replace `Reflect.get` with typed property access.

The second one is not this branch's problem. It sits on main's own tip: #20702 landed that Reflect.get after #20786 enabled anti-slop/no-reflect-get, so main has been red on this gate since roughly 19:20 UTC today. Because audit:anti-slop lints src config tests mobile wholesale, every open PR inherits it. #20874 fixes it on main; nothing should be patched here for it. Note that the verify check failing is just the aggregate "Require successful checks" gate reacting to this, not an independent failure.

The first one is from this branch's newer commits and needs fixing here.

A fix for the identical violation is already proven on the child branch, so this should not need re-deriving. pr2a-3-structured-routing hit the same rule at src/shared/agent-status-store-byte-budget.ts:10 and resolved it by replacing the broad object with a named union matching exactly what the call sites pass:

type AgentStatusStoreByteBudgetRecord =
  | AgentStatusStoreSnapshot
  | AgentStatusParentRecord
  | AgentChildWorkRecord
  | AgentChildWorkAliasRecord
  | AgentStatusFactRecord
  | AgentStatusTombstoneRecord

applied to both the function parameter and the WeakMap key. No pre-existing union covered that combination. If snapshot-budget.ts has the same call-site shape, the same union likely applies directly.

Two things that cost time elsewhere in this stack, worth avoiding here:

  • Don't reach for an inline oxlint-disable or relax the rule in config/oxlint-anti-slop.json — a genuine named type is what the rule is asking for.
  • pnpm run check:code-quality:changed does not cover this gate. The real command is pnpm run audit:anti-slop; run that directly to confirm. Until fix(lint): replace Reflect.get with typed property access in mounting substitutes #20874 lands, a correct fix here will leave exactly one remaining error (the inherited mobile Reflect.get) rather than exit 0 — that residual is expected and is not a reason to keep changing this branch.

@brennanb2025
brennanb2025 force-pushed the brennanb2025/pr2a-2-canonical-store-contract branch from e544b9b to a90aacd Compare September 15, 2026 20:34
@brennanb2025

brennanb2025 commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor Author

Follow-up: the first CI static-analysis run found a broad object parameter in the new snapshot-budget helper. That is fixed in amended commit a90aacd83e with a named union of canonical record types. The replacement static-analysis job now confirms the branch-specific finding is gone and reports only the pre-existing main warning at mobile/src/test-support/rpc-recording/native-mounting-substitutes.ts:45 (Reflect.get); typecheck and managed-hook checks pass, with the remaining test/package jobs still running.

@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: 3


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 171f46c0-49e0-4c37-b9e5-b2192e73ad5e

📥 Commits

Reviewing files that changed from the base of the PR and between f144127 and e544b9b2a0d538e2a1fd88df20463e1b3e76fdde.

📒 Files selected for processing (15)
  • src/shared/agent-status-child-work-admission-core.ts
  • src/shared/agent-status-child-work-admission-operations.ts
  • src/shared/agent-status-child-work-admission.test.ts
  • src/shared/agent-status-child-work-admission.ts
  • src/shared/agent-status-child-work-stop.ts
  • src/shared/agent-status-run-alias-index.test.ts
  • src/shared/agent-status-run-alias-index.ts
  • src/shared/agent-status-store-bounds.test.ts
  • src/shared/agent-status-store-contract.ts
  • src/shared/agent-status-store-mutation.ts
  • src/shared/agent-status-store-run-index.ts
  • src/shared/agent-status-store-snapshot-budget.ts
  • src/shared/agent-status-store-state.ts
  • src/shared/agent-status-store.test.ts
  • src/shared/agent-status-store.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/shared/agent-status-child-work-admission.test.ts
  • src/shared/agent-status-child-work-admission.ts

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

Comment on lines +47 to +48
state.tombstones.size <= AGENT_STATUS_STORE_LIMITS.tombstones &&
state.revision - tombstone.revision < AGENT_STATUS_STORE_TOMBSTONE_RETENTION_REVISIONS

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 | 🟠 Major | 🏗️ Heavy lift

Preserve unexpired child tombstones.

Remove one child. Then create 1,024 newer tombstones within fewer than 4,096 revisions. This capacity condition evicts the child tombstone. A later mutation can reuse the same childWorkId because upsertChildren checks only tombstone presence.

Do not evict unexpired child tombstones. Reject the mutation when the budget cannot preserve them, or maintain a separate bounded anti-reuse structure.

Comment thread src/shared/agent-status-store.test.ts Outdated
expect(replica.getParent(parent)?.firstObservedAt).toBe(30)
})

it.fails('does not roll a replica back to a superseded epoch snapshot', () => {

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 | 🟠 Major | 🏗️ Heavy lift

Prevent replica rollback across epochs.

A replica accepts epoch-a, then epoch-b, and then accepts the delayed epoch-a snapshot again. This restores superseded state because different epochs bypass revision ordering.

Require an explicit epoch transition or an ordered generation fence. Then change it.fails to it.

@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 new tombstone compaction can evict a fresh, still-load-bearing child tombstone under size pressure, so a removed child id can be resurrected well inside the retention window the code claims to honor. Details inline.

Reviewed changes

Reviewed the delta since the prior pullfrog review (f144127 → e544b9b): two fix commits hardening the canonical store and the child-work admission contract. Re-ran the 9 affected suites (83 pass, 1 expected fail), pnpm tc:node, and the changed-code quality gate — all clean. Also reproduced the two remaining open threads against this head (proven-new can still rebind an alias off a live predecessor; reparent to the same parent is still store-rejected).

  • Store read methods (agent-status-store.ts) — added getChild / getAlias / getAliasesForChild / getRunAliasIndex; admission helpers read those instead of getSnapshot(), with a test asserting no snapshot is materialized per admission.
  • Aggregate byte budget (agent-status-store-snapshot-budget.ts, agent-status-store-state.ts) — validateAgentStatusStoreState now rejects a state whose snapshot exceeds serializedBytes, closing the commit-then-throw gap; per-record byte lengths are memoized in a WeakMap.
  • Tombstone bounding + resurrection semantics (agent-status-store-contract.ts, agent-status-store-mutation.ts, agent-status-store-state.ts) — cap lowered 16 384 → 1 024 with a 4 096-revision retention, size/age compaction on mutate and restore, and the parent tombstone guard relaxed to a revision comparison so a removed parent can be re-observed.
  • Invocation fences (agent-status-child-work-admission-operations.ts) — resume rejects a non-advancing generation and retires aliases whose fence ages out of bounded history; announce rejects a fence mismatch on the current path.
  • Run-alias index (agent-status-run-alias-index.ts, agent-status-store-run-index.ts) — per-alias run cap raised from 256 to the store's parent limit; the index is derived on demand and reconstructible from a snapshot.
  • Stop authorization extracted to agent-status-child-work-stop.ts; store bounds tests added.

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

Comment on lines +44 to +54
function compactTombstones(state: AgentStatusStoreState): void {
for (const [key, tombstone] of state.tombstones) {
if (
state.tombstones.size <= AGENT_STATUS_STORE_LIMITS.tombstones &&
state.revision - tombstone.revision < AGENT_STATUS_STORE_TOMBSTONE_RETENTION_REVISIONS
) {
break
}
state.tombstones.delete(key)
}
}

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.

compactTombstones evicts the oldest tombstones whenever the count exceeds AGENT_STATUS_STORE_LIMITS.tombstones (1024), with no age check. The child-entity tombstone is the only unconditional resurrection guard (upsertChildren blocks on state.tombstones.has(...), while the parent/alias/fact checks are revision-gated and never block a later mutation), so a single 1025-entry removeChildren mutation can evict a just-created child tombstone and let that child id be re-added on the very next mutation — inside the 4096-revision retention window.

Technical details
# Size-pressure tombstone eviction drops fresh child tombstones

## Affected sites
- `src/shared/agent-status-store-mutation.ts:44-54` — `compactTombstones` deletes the oldest entries while `size > tombstones` regardless of `state.revision - tombstone.revision`, so it can evict a tombstone that is nowhere near the retention boundary.
- `src/shared/agent-status-store-mutation.ts:261` — compaction runs before `validateAgentStatusStoreState`, so the corrupted state is the one that gets validated and committed.
- `src/shared/agent-status-store-mutation.ts:171` — `upsertChildren` blocks resurrection only via `state.tombstones.has(agentStatusTombstoneMapKey('child', ...))`; parent (`:145`), alias (`state.ts:159`) and fact (`state.ts:170`) guards compare `tombstone.revision >= record.revision`, and a later mutation always has a higher revision, so those tombstones never block anything.
- `src/shared/agent-status-store-contract.ts:15` — `tombstones: 1_024`; `mutationEntries: 2_048` allows one mutation to add up to 2048 tombstones.

## Evidence (reproduced on e544b9b2a0)
1. `applyMutation({ parent })`; `applyMutation({ children: [child-1] })`; `applyMutation({ removeChildren: ['child-1'] })`.
2. `applyMutation({ children: [child-1@observedAt:30] })` → `null` (guard holds).
3. `applyMutation({ removeChildren: [1025 unused ids] })` → non-null; compaction drops `child-1`'s tombstone (and one unused) to get back to 1024.
4. `applyMutation({ children: [child-1@observedAt:30] })` → non-null; `getChildren(parent)` shows child-1 resurrected with stale state.
A 1025-entry `removeChildren` is well within `mutationEntries`; the existing `agent-status-store.test.ts:347` only exercises the no-pressure path.

## Required outcome
A mutation must not evict a tombstone whose guard is still load-bearing. Either reject a mutation that would exceed `AGENT_STATUS_STORE_LIMITS.tombstones` (fail closed instead of compacting on size), or evict only age-expired tombstones and reject when the cap cannot be respected. Add a test that overflows the cap while a fresh child tombstone exists and asserts the re-add still returns `null`.

## Note
The restore-time loop at `agent-status-store-state.ts:257-262` deletes size-blindly too, but it is also age-gated, so a restored snapshot can drop child tombstones older than the retention window. Decide whether that matches the intended restore semantics.

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