Skip to content

fix(agent-status): correlate manual Claude compact hooks - #12332

Merged
Jinwoo-H merged 5 commits into
mainfrom
fix/manual-claude-compact-status
Aug 4, 2026
Merged

Jinwoo-H merged 5 commits into
mainfrom
fix/manual-claude-compact-status

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Clears sticky working status after a manual Claude /compact by matching authenticated PreCompact and PostCompact hooks on connection, exact session presence/value, manual trigger, prompt UUID, and current status generation.
  • Keeps lastStatusByPaneKey as the sole status authority. Missing identity is never a wildcard, and stale, duplicate, cross-provider, cross-session, or later-work completions fail closed.
  • Preserves task-notification and slash-command background-task resumes. Automatic Claude and unproven Kimi compact hooks remain ignored.
  • Adds no owner map, polling, timers, global scans, subprocesses, or new listeners.

This is a review-driven replacement for #11353 with the safe scope narrowed to manual Claude compaction. Live Claude Code 2.1.220 probes showed that manual compact hooks share a distinct prompt UUID, while automatic compaction may reuse one UUID across multiple generations.

Screenshots

No visual change.

Testing

  • pnpm lint
  • pnpm typecheck
  • pnpm test — CI-equivalent shard 9 passed: 259 files, 2,965 passed, 4 skipped
  • pnpm build — package and Windows package passed on the prior CI run; this follow-up does not touch build inputs
  • Added focused regression coverage: 10 files, 468 tests passed
  • Deterministic manual compact identity oracle: 6/6 passed
  • git diff --check

AI Review Report

The review treated hook and relay payloads as hostile and checked stale, duplicate, reordered, sessionless, cross-provider, cross-connection, restore, cleanup, and 4,097-key retention sequences. CI exposed an over-broad harness-turn suppression that broke Claude background-task resumes; the predicate now suppresses only the observed compact-continuation prompt. CodeRabbit also identified that Kimi PreCompact could create working even though Kimi completion was rejected; both Kimi and automatic Claude compact events now fail closed at the listener and main relay boundaries. Its distinct-test-identity and server-teardown suggestions were also applied.

Cross-platform review found no OS-specific shortcuts, labels, paths, shells, native modules, Git commands, or Electron behavior. The same bounded TypeScript status path is used on macOS, Linux, Windows, local, SSH, relay, and folder workspaces.

Security Audit

Authenticated hook source, relay connection, provider session presence/value, prompt UUID, manual trigger, and current status generation must all match before completion. Untrusted pane keys and malformed or missing identities allocate no ownership state. The change adds no credential access, secrets, dependencies, command execution, network destinations, subprocesses, telemetry, polling, timers, or global scans.

Notes

Manual Claude compaction is the only newly supported completion lifecycle. Automatic Claude and Kimi compact completion remain unproved and intentionally do not affect durable status. The exported compact-continuation classifier inspects at most a bounded prompt head.

@coderabbitai

coderabbitai Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change adds identity metadata for manual Claude compaction events. Hook normalization validates source, provider session, connection, trigger, and prompt UUID. Relay and SSH paths preserve and validate this metadata. Tests cover lifecycle transitions, stale and duplicate events, provider changes, persistence, cleanup, and automatic compaction. A reliability gate documents the exact-generation invariant and validation evidence.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 21.43% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description check ✅ Passed The description covers the summary, visual impact, testing, AI review, security audit, and notes, with reasons for incomplete checks.
Title check ✅ Passed The title clearly and concisely identifies the fix for manual Claude compaction hook correlation.
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.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • 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: 1

🧹 Nitpick comments (2)
src/shared/manual-compact-prompt-identity.test.ts (1)

12-15: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use distinct literals for LEAF_ID and PROMPT_ID_1.

LEAF_ID and PROMPT_ID_1 hold the same UUID. These tests assert prompt-identity correlation. If production code ever confused a pane leaf id with a provider prompt id, these assertions would still pass. Give the prompt ids values that no pane key uses.

♻️ Proposed change
 const LEAF_ID = '11111111-1111-4111-8111-111111111111'
 const PANE_KEY = makePaneKey('manual-compact-prompt', LEAF_ID)
-const PROMPT_ID_1 = '11111111-1111-4111-8111-111111111111'
-const PROMPT_ID_2 = '22222222-2222-4222-8222-222222222222'
+const PROMPT_ID_1 = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaa1'
+const PROMPT_ID_2 = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaa2'
src/main/agent-hooks/manual-compact-hook-stream.test.ts (1)

256-272: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Register the first server for teardown.

first binds a real HTTP listener at line 260 but is not added to servers. If a POST or assertion throws before line 272, the listener stays open for the rest of the run. Push it into servers so afterEach always stops it. A second stop() is safe because stop() clears this.server.

♻️ Proposed change
     const first = new AgentHookServer()
+    servers.push(first)
     await first.start({ env: 'production', userDataPath })

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 069e47d1-b9ef-4af1-a5c9-d71a2a9a69aa

📥 Commits

Reviewing files that changed from the base of the PR and between cd68a8b and 09e490beeb544416bbc01f057fdea404c5ff47fc.

📒 Files selected for processing (12)
  • config/reliability-gates.jsonc
  • src/main/agent-hooks/manual-compact-hook-stream.test.ts
  • src/main/agent-hooks/manual-compact-status-cleanup.test.ts
  • src/main/agent-hooks/server.ts
  • src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts
  • src/main/ssh/ssh-relay-session.ts
  • src/relay/agent-hook-server.ts
  • src/shared/agent-hook-listener.test.ts
  • src/shared/agent-hook-listener.ts
  • src/shared/agent-hook-relay.test.ts
  • src/shared/agent-hook-relay.ts
  • src/shared/manual-compact-prompt-identity.test.ts

Comment thread src/shared/agent-hook-listener.ts Resolved
mmarabel and others added 4 commits August 3, 2026 16:10
Harness-injected UserPromptSubmit (compact summary, task notifications,
local-command machinery) no longer mints a working row without a Stop.
Claude PreCompact marks busy and PostCompact resolves to done so finished
compaction cannot leave the sidebar spinner stuck.

Fixes #11352
Address Greptile/CodeRabbit review on #11353: extract a shared
shouldIgnoreHarnessInjectedUserPromptSubmit helper for Claude and Kimi,
and add Kimi harness + PreCompact/PostCompact regression tests so the
parallel path cannot drift.
@OrcaWin
OrcaWin force-pushed the fix/manual-claude-compact-status branch from 09e490b to 75d6e5e Compare August 3, 2026 20:11

@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: Pro Plus

Run ID: 964ee2c5-dce4-459e-9d61-cb483e14eafe

📥 Commits

Reviewing files that changed from the base of the PR and between 09e490beeb544416bbc01f057fdea404c5ff47fc and 75d6e5e.

📒 Files selected for processing (14)
  • config/reliability-gates.jsonc
  • src/main/agent-hooks/manual-compact-hook-stream.test.ts
  • src/main/agent-hooks/manual-compact-status-cleanup.test.ts
  • src/main/agent-hooks/server.ts
  • src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts
  • src/main/ssh/ssh-relay-session.ts
  • src/relay/agent-hook-server.ts
  • src/shared/agent-hook-listener.test.ts
  • src/shared/agent-hook-listener.ts
  • src/shared/agent-hook-relay.test.ts
  • src/shared/agent-hook-relay.ts
  • src/shared/harness-injected-user-turns.test.ts
  • src/shared/harness-injected-user-turns.ts
  • src/shared/manual-compact-prompt-identity.test.ts
🚧 Files skipped from review as they are similar to previous changes (11)
  • src/main/ssh/ssh-relay-session.ts
  • src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts
  • src/main/agent-hooks/manual-compact-status-cleanup.test.ts
  • src/shared/agent-hook-relay.test.ts
  • src/shared/agent-hook-relay.ts
  • src/relay/agent-hook-server.ts
  • src/shared/manual-compact-prompt-identity.test.ts
  • config/reliability-gates.jsonc
  • src/main/agent-hooks/server.ts
  • src/shared/agent-hook-listener.test.ts
  • src/shared/agent-hook-listener.ts

Comment on lines +196 to +223
it('invalidates a compact completion when later provider work owns the pane', () => {
const server = new AgentHookServer()
servers.push(server)
server.ingestRemote(manualEnvelope('UserPromptSubmit', 'working'), 'conn-a')
server.ingestRemote(manualEnvelope('PreCompact', 'working'), 'conn-a')
server.ingestRemote(
{
source: 'codex',
paneKey: PANE_KEY,
hookEventName: 'UserPromptSubmit',
hasExplicitPrompt: true,
payload: { state: 'working', prompt: 'new work', agentType: 'codex' }
},
'conn-a'
)
server.ingestRemote({ ...manualEnvelope('PreCompact', 'working'), isReplay: true }, 'conn-a')
server.ingestRemote(manualEnvelope('PostCompact', 'done'), 'conn-a')

expect(server.getStatusSnapshot()[0]).toMatchObject({
state: 'working',
prompt: 'new work',
agentType: 'claude'
})
expect(server._getStateForTests().lastStatusByPaneKey.get(PANE_KEY)).toMatchObject({
source: 'codex',
hookEventName: 'UserPromptSubmit'
})
})

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

Fix the agentType expectation after the codex takeover.

The codex UserPromptSubmit envelope sets payload.agentType to 'codex' at Line 207. The assertion at Line 217 expects agentType: 'claude', while the same assertion's prompt: 'new work' at Line 216 confirms the codex payload won the pane. The raw-state check at Lines 220-221 also confirms source: 'codex' owns the pane. Expecting agentType: 'claude' contradicts the codex-sourced input in the same assertion.

Correct the expected agentType to 'codex', or clarify why the snapshot should report 'claude' for a codex-owned pane. As written, this test can mask a real defect in provider-takeover handling, which is the exact scenario this PR must validate.

🐛 Proposed fix for the assertion
     expect(server.getStatusSnapshot()[0]).toMatchObject({
       state: 'working',
       prompt: 'new work',
-      agentType: 'claude'
+      agentType: 'codex'
     })
📝 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
it('invalidates a compact completion when later provider work owns the pane', () => {
const server = new AgentHookServer()
servers.push(server)
server.ingestRemote(manualEnvelope('UserPromptSubmit', 'working'), 'conn-a')
server.ingestRemote(manualEnvelope('PreCompact', 'working'), 'conn-a')
server.ingestRemote(
{
source: 'codex',
paneKey: PANE_KEY,
hookEventName: 'UserPromptSubmit',
hasExplicitPrompt: true,
payload: { state: 'working', prompt: 'new work', agentType: 'codex' }
},
'conn-a'
)
server.ingestRemote({ ...manualEnvelope('PreCompact', 'working'), isReplay: true }, 'conn-a')
server.ingestRemote(manualEnvelope('PostCompact', 'done'), 'conn-a')
expect(server.getStatusSnapshot()[0]).toMatchObject({
state: 'working',
prompt: 'new work',
agentType: 'claude'
})
expect(server._getStateForTests().lastStatusByPaneKey.get(PANE_KEY)).toMatchObject({
source: 'codex',
hookEventName: 'UserPromptSubmit'
})
})
it('invalidates a compact completion when later provider work owns the pane', () => {
const server = new AgentHookServer()
servers.push(server)
server.ingestRemote(manualEnvelope('UserPromptSubmit', 'working'), 'conn-a')
server.ingestRemote(manualEnvelope('PreCompact', 'working'), 'conn-a')
server.ingestRemote(
{
source: 'codex',
paneKey: PANE_KEY,
hookEventName: 'UserPromptSubmit',
hasExplicitPrompt: true,
payload: { state: 'working', prompt: 'new work', agentType: 'codex' }
},
'conn-a'
)
server.ingestRemote({ ...manualEnvelope('PreCompact', 'working'), isReplay: true }, 'conn-a')
server.ingestRemote(manualEnvelope('PostCompact', 'done'), 'conn-a')
expect(server.getStatusSnapshot()[0]).toMatchObject({
state: 'working',
prompt: 'new work',
agentType: 'codex'
})
expect(server._getStateForTests().lastStatusByPaneKey.get(PANE_KEY)).toMatchObject({
source: 'codex',
hookEventName: 'UserPromptSubmit'
})
})

@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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/shared/agent-hook-listener.ts (1)

364-377: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Reject compact events without provider-session identity.

The initial gate does not require incoming.providerSession. An unanchored sessionless event therefore passes immediately. An anchored transition also passes when both sessions are undefined because agentProviderSessionsEqual treats them as equal.

Require provider-session identity before the unanchored exceptions. This preserves exact session correlation and makes sessionless transitions fail closed.

Proposed fix
   if (
     incoming.source !== 'claude' ||
     incoming.compactTrigger === undefined ||
     incoming.providerPromptId === undefined ||
+    incoming.providerSession === undefined ||
     (incoming.hookEventName !== 'PreCompact' && incoming.hookEventName !== 'PostCompact')
   ) {

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 87d86e32-dfa8-4318-acde-3b6ed763bd3d

📥 Commits

Reviewing files that changed from the base of the PR and between 75d6e5e and 926cbcc.

📒 Files selected for processing (7)
  • src/main/agent-hooks/manual-compact-hook-stream.test.ts
  • src/main/agent-hooks/server.ts
  • src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts
  • src/relay/agent-hook-server.ts
  • src/shared/agent-hook-listener.ts
  • src/shared/agent-hook-relay.ts
  • src/shared/manual-compact-prompt-identity.test.ts
🚧 Files skipped from review as they are similar to previous changes (5)
  • src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts
  • src/shared/agent-hook-relay.ts
  • src/main/agent-hooks/manual-compact-hook-stream.test.ts
  • src/main/agent-hooks/server.ts
  • src/shared/manual-compact-prompt-identity.test.ts

@Jinwoo-H
Jinwoo-H merged commit 847c8c8 into main Aug 4, 2026
42 checks passed
@Jinwoo-H
Jinwoo-H deleted the fix/manual-claude-compact-status branch August 4, 2026 22:03
brennanb2025 added a commit that referenced this pull request Aug 18, 2026
…-2915, STA-4613)

A manual /compact ends at an idle prompt without emitting Stop, so nothing in the
compact window could ever clear the pane. A worktree that entered the compact
`working` stayed `working` until the 30-minute stale sweep -- and the summarizer's
start-less SubagentStop kept republishing the row, resetting that clock each time.

The correlation added by #12332 was supposed to own this, but it could never run:
PreCompact and PostCompact were never added to CLAUDE_EVENTS, so they were never
registered with Claude. compactTrigger was always undefined, and the transition
guard, the ownership cache, the relay wire field and the ingest branch were all
unreachable. Five test files exercised the logic by injecting events past the
registration boundary, so the suite stayed green over code that could not execute.

Register PostCompact -- and deliberately NOT PreCompact. Measured on Claude Code
2.1.227, a successful manual compact emits PreCompact, a start-less SubagentStop,
SessionStart(source=compact), then PostCompact; an ABORTED compact ("Not enough
messages to compact") emits PreCompact ALONE. Mapping PreCompact to `working`
would strand the pane on every aborted compact, which is the bug being fixed, so
the abort guard is structural: Orca never subscribes to the pre-validation event.

PostCompact carries its own trigger, so no anchor is needed to tell manual from
auto and the correlation machinery is deleted rather than repaired. Manual becomes
a `done` with sessionBoundary set -- a finished compact is a session-shaped
boundary, not a completed turn, so completion notifications, unread counts and
automation-run evidence stay out of it. Auto claims nothing: it runs inside a turn
that resumes and emits its own Stop.

The source-blind early return that dropped compact events for EVERY provider
before its normalizer ran is narrowed to Claude, so it keeps failing closed on a
malformed payload without pre-empting other providers.

Ownership is kept where the deleted guard had it: a valid provider prompt id is
required, a completion clears a row but never creates one (a retired pane must not
be resurrected), and a hydrated row is matched on provider session only -- it
carries the previous session's connectionId, and older rows carry no session at
all, so a strict check would reject the restart case this fixes. A consumed
prompt id keeps relay duplicates from refreshing the row.

Mixed versions: no new wire field and no new opcode. An older relay normalizes
with its own shipped mapping and forwards the event, so ingest drops `auto`
envelopes and stamps the boundary on `manual` ones; its replay strips the trigger
entirely, so payload state stands in for it while ownership is still enforced. The
relay now caches a completion with its compact identity removed, so a client that
was offline during the compact still receives the clearing row on reconnect.

Tests go red before this change and green after: 6 of 12 in the new
registration-gated suite and 5 of 8 in the relay/ingest suite. The harness delivers
only events present in CLAUDE_EVENTS, so a fix that is never registered cannot
pass -- the failure mode that let the original correlation ship unreachable.
brennanb2025 added a commit that referenced this pull request Aug 24, 2026
…-2915, STA-4613) (#15202)

* fix(agent-status): clear the pane when a Claude compact finishes (STA-2915, STA-4613)

A manual /compact ends at an idle prompt without emitting Stop, so nothing in the
compact window could ever clear the pane. A worktree that entered the compact
`working` stayed `working` until the 30-minute stale sweep -- and the summarizer's
start-less SubagentStop kept republishing the row, resetting that clock each time.

The correlation added by #12332 was supposed to own this, but it could never run:
PreCompact and PostCompact were never added to CLAUDE_EVENTS, so they were never
registered with Claude. compactTrigger was always undefined, and the transition
guard, the ownership cache, the relay wire field and the ingest branch were all
unreachable. Five test files exercised the logic by injecting events past the
registration boundary, so the suite stayed green over code that could not execute.

Register PostCompact -- and deliberately NOT PreCompact. Measured on Claude Code
2.1.227, a successful manual compact emits PreCompact, a start-less SubagentStop,
SessionStart(source=compact), then PostCompact; an ABORTED compact ("Not enough
messages to compact") emits PreCompact ALONE. Mapping PreCompact to `working`
would strand the pane on every aborted compact, which is the bug being fixed, so
the abort guard is structural: Orca never subscribes to the pre-validation event.

PostCompact carries its own trigger, so no anchor is needed to tell manual from
auto and the correlation machinery is deleted rather than repaired. Manual becomes
a `done` with sessionBoundary set -- a finished compact is a session-shaped
boundary, not a completed turn, so completion notifications, unread counts and
automation-run evidence stay out of it. Auto claims nothing: it runs inside a turn
that resumes and emits its own Stop.

The source-blind early return that dropped compact events for EVERY provider
before its normalizer ran is narrowed to Claude, so it keeps failing closed on a
malformed payload without pre-empting other providers.

Ownership is kept where the deleted guard had it: a valid provider prompt id is
required, a completion clears a row but never creates one (a retired pane must not
be resurrected), and a hydrated row is matched on provider session only -- it
carries the previous session's connectionId, and older rows carry no session at
all, so a strict check would reject the restart case this fixes. A consumed
prompt id keeps relay duplicates from refreshing the row.

Mixed versions: no new wire field and no new opcode. An older relay normalizes
with its own shipped mapping and forwards the event, so ingest drops `auto`
envelopes and stamps the boundary on `manual` ones; its replay strips the trigger
entirely, so payload state stands in for it while ownership is still enforced. The
relay now caches a completion with its compact identity removed, so a client that
was offline during the compact still receives the clearing row on reconnect.

Tests go red before this change and green after: 6 of 12 in the new
registration-gated suite and 5 of 8 in the relay/ingest suite. The harness delivers
only events present in CLAUDE_EVENTS, so a fix that is never registered cannot
pass -- the failure mode that let the original correlation ship unreachable.

* test(agent-status): restate the compact reliability gate around the new invariant

The gate pinned a test file this change deletes, so the manifest check failed.
Repointing the path alone would have left the gate describing an invariant that
no longer exists: it required a manual PostCompact to match its exact PreCompact
generation, and PreCompact is no longer consumed at all.

Restate it. The invariant is now that PreCompact never moves a pane, that only a
manual PostCompact marks done and does so as a session boundary, that a
completion clears an existing row but never creates one, and that a relay
predating the contract has its automatic envelopes dropped and its trigger-
stripped replays classified by payload state under the same ownership checks.

Evidence runs are the real ones: the 105-test suite from this branch, and the
Claude Code 2.1.227 PTY capture that measured PreCompact arriving alone on an
aborted compact.

* fix(agent-status): clear the restart-stuck pane a compact was meant to clear

Review found the completion did not clear the pane STA-2915 actually reports, and
that republishing it was a strict regression.

- A manual completion now retires a subagent that exists only as a disk snapshot:
  a /compact only completes at an idle prompt, so a restored child is proof of
  nothing. Live evidence -- a child observed in this runtime, an unclassifiable
  running background task, a registered session cron -- still holds the pane.
- A completion that cannot clear now publishes nothing instead of restating the
  row, which was stripping restoredUnconfirmed off a hydrated row and restarting
  the staleness clock for work the compact never observed.
- The relay defers compact ownership to the client that owns pane identity, so a
  cold relay cache can no longer swallow the one event that clears a remote pane.
- claudeConsumedCompactPromptIdByPaneKey joins all three pane-scoped teardown
  routes, and an auto compact no longer spends the pane's consumed-compact slot.
- The promptless completion keeps the summarized turn's label with or without a
  trigger on the envelope.

Tests: the two restart cases now deliver the completion while the hydrated row is
still cached, so they exercise the restored-row branch instead of passing through
the strict one; the triggerless working replay is asserted from a FINISHED pane so
it can fail. Reverting the four source files turns 12 of 21 registration-gated and
8 of 12 relay/ingest tests red, and 18 of 18 targeted mutations are caught.

* fix(agent-hooks): preserve compact identity across relay replay

* docs(reliability): describe compact replay ownership
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 25, 2026
…-2915, STA-4613) (stablyai#15202)

* fix(agent-status): clear the pane when a Claude compact finishes (STA-2915, STA-4613)

A manual /compact ends at an idle prompt without emitting Stop, so nothing in the
compact window could ever clear the pane. A worktree that entered the compact
`working` stayed `working` until the 30-minute stale sweep -- and the summarizer's
start-less SubagentStop kept republishing the row, resetting that clock each time.

The correlation added by stablyai#12332 was supposed to own this, but it could never run:
PreCompact and PostCompact were never added to CLAUDE_EVENTS, so they were never
registered with Claude. compactTrigger was always undefined, and the transition
guard, the ownership cache, the relay wire field and the ingest branch were all
unreachable. Five test files exercised the logic by injecting events past the
registration boundary, so the suite stayed green over code that could not execute.

Register PostCompact -- and deliberately NOT PreCompact. Measured on Claude Code
2.1.227, a successful manual compact emits PreCompact, a start-less SubagentStop,
SessionStart(source=compact), then PostCompact; an ABORTED compact ("Not enough
messages to compact") emits PreCompact ALONE. Mapping PreCompact to `working`
would strand the pane on every aborted compact, which is the bug being fixed, so
the abort guard is structural: Orca never subscribes to the pre-validation event.

PostCompact carries its own trigger, so no anchor is needed to tell manual from
auto and the correlation machinery is deleted rather than repaired. Manual becomes
a `done` with sessionBoundary set -- a finished compact is a session-shaped
boundary, not a completed turn, so completion notifications, unread counts and
automation-run evidence stay out of it. Auto claims nothing: it runs inside a turn
that resumes and emits its own Stop.

The source-blind early return that dropped compact events for EVERY provider
before its normalizer ran is narrowed to Claude, so it keeps failing closed on a
malformed payload without pre-empting other providers.

Ownership is kept where the deleted guard had it: a valid provider prompt id is
required, a completion clears a row but never creates one (a retired pane must not
be resurrected), and a hydrated row is matched on provider session only -- it
carries the previous session's connectionId, and older rows carry no session at
all, so a strict check would reject the restart case this fixes. A consumed
prompt id keeps relay duplicates from refreshing the row.

Mixed versions: no new wire field and no new opcode. An older relay normalizes
with its own shipped mapping and forwards the event, so ingest drops `auto`
envelopes and stamps the boundary on `manual` ones; its replay strips the trigger
entirely, so payload state stands in for it while ownership is still enforced. The
relay now caches a completion with its compact identity removed, so a client that
was offline during the compact still receives the clearing row on reconnect.

Tests go red before this change and green after: 6 of 12 in the new
registration-gated suite and 5 of 8 in the relay/ingest suite. The harness delivers
only events present in CLAUDE_EVENTS, so a fix that is never registered cannot
pass -- the failure mode that let the original correlation ship unreachable.

* test(agent-status): restate the compact reliability gate around the new invariant

The gate pinned a test file this change deletes, so the manifest check failed.
Repointing the path alone would have left the gate describing an invariant that
no longer exists: it required a manual PostCompact to match its exact PreCompact
generation, and PreCompact is no longer consumed at all.

Restate it. The invariant is now that PreCompact never moves a pane, that only a
manual PostCompact marks done and does so as a session boundary, that a
completion clears an existing row but never creates one, and that a relay
predating the contract has its automatic envelopes dropped and its trigger-
stripped replays classified by payload state under the same ownership checks.

Evidence runs are the real ones: the 105-test suite from this branch, and the
Claude Code 2.1.227 PTY capture that measured PreCompact arriving alone on an
aborted compact.

* fix(agent-status): clear the restart-stuck pane a compact was meant to clear

Review found the completion did not clear the pane STA-2915 actually reports, and
that republishing it was a strict regression.

- A manual completion now retires a subagent that exists only as a disk snapshot:
  a /compact only completes at an idle prompt, so a restored child is proof of
  nothing. Live evidence -- a child observed in this runtime, an unclassifiable
  running background task, a registered session cron -- still holds the pane.
- A completion that cannot clear now publishes nothing instead of restating the
  row, which was stripping restoredUnconfirmed off a hydrated row and restarting
  the staleness clock for work the compact never observed.
- The relay defers compact ownership to the client that owns pane identity, so a
  cold relay cache can no longer swallow the one event that clears a remote pane.
- claudeConsumedCompactPromptIdByPaneKey joins all three pane-scoped teardown
  routes, and an auto compact no longer spends the pane's consumed-compact slot.
- The promptless completion keeps the summarized turn's label with or without a
  trigger on the envelope.

Tests: the two restart cases now deliver the completion while the hydrated row is
still cached, so they exercise the restored-row branch instead of passing through
the strict one; the triggerless working replay is asserted from a FINISHED pane so
it can fail. Reverting the four source files turns 12 of 21 registration-gated and
8 of 12 relay/ingest tests red, and 18 of 18 targeted mutations are caught.

* fix(agent-hooks): preserve compact identity across relay replay

* docs(reliability): describe compact replay ownership

(cherry picked from commit 1921ba2)
dallascrilley pushed a commit to dallascrilley/orca that referenced this pull request Aug 27, 2026
…-2915, STA-4613) (stablyai#15202)

* fix(agent-status): clear the pane when a Claude compact finishes (STA-2915, STA-4613)

A manual /compact ends at an idle prompt without emitting Stop, so nothing in the
compact window could ever clear the pane. A worktree that entered the compact
`working` stayed `working` until the 30-minute stale sweep -- and the summarizer's
start-less SubagentStop kept republishing the row, resetting that clock each time.

The correlation added by stablyai#12332 was supposed to own this, but it could never run:
PreCompact and PostCompact were never added to CLAUDE_EVENTS, so they were never
registered with Claude. compactTrigger was always undefined, and the transition
guard, the ownership cache, the relay wire field and the ingest branch were all
unreachable. Five test files exercised the logic by injecting events past the
registration boundary, so the suite stayed green over code that could not execute.

Register PostCompact -- and deliberately NOT PreCompact. Measured on Claude Code
2.1.227, a successful manual compact emits PreCompact, a start-less SubagentStop,
SessionStart(source=compact), then PostCompact; an ABORTED compact ("Not enough
messages to compact") emits PreCompact ALONE. Mapping PreCompact to `working`
would strand the pane on every aborted compact, which is the bug being fixed, so
the abort guard is structural: Orca never subscribes to the pre-validation event.

PostCompact carries its own trigger, so no anchor is needed to tell manual from
auto and the correlation machinery is deleted rather than repaired. Manual becomes
a `done` with sessionBoundary set -- a finished compact is a session-shaped
boundary, not a completed turn, so completion notifications, unread counts and
automation-run evidence stay out of it. Auto claims nothing: it runs inside a turn
that resumes and emits its own Stop.

The source-blind early return that dropped compact events for EVERY provider
before its normalizer ran is narrowed to Claude, so it keeps failing closed on a
malformed payload without pre-empting other providers.

Ownership is kept where the deleted guard had it: a valid provider prompt id is
required, a completion clears a row but never creates one (a retired pane must not
be resurrected), and a hydrated row is matched on provider session only -- it
carries the previous session's connectionId, and older rows carry no session at
all, so a strict check would reject the restart case this fixes. A consumed
prompt id keeps relay duplicates from refreshing the row.

Mixed versions: no new wire field and no new opcode. An older relay normalizes
with its own shipped mapping and forwards the event, so ingest drops `auto`
envelopes and stamps the boundary on `manual` ones; its replay strips the trigger
entirely, so payload state stands in for it while ownership is still enforced. The
relay now caches a completion with its compact identity removed, so a client that
was offline during the compact still receives the clearing row on reconnect.

Tests go red before this change and green after: 6 of 12 in the new
registration-gated suite and 5 of 8 in the relay/ingest suite. The harness delivers
only events present in CLAUDE_EVENTS, so a fix that is never registered cannot
pass -- the failure mode that let the original correlation ship unreachable.

* test(agent-status): restate the compact reliability gate around the new invariant

The gate pinned a test file this change deletes, so the manifest check failed.
Repointing the path alone would have left the gate describing an invariant that
no longer exists: it required a manual PostCompact to match its exact PreCompact
generation, and PreCompact is no longer consumed at all.

Restate it. The invariant is now that PreCompact never moves a pane, that only a
manual PostCompact marks done and does so as a session boundary, that a
completion clears an existing row but never creates one, and that a relay
predating the contract has its automatic envelopes dropped and its trigger-
stripped replays classified by payload state under the same ownership checks.

Evidence runs are the real ones: the 105-test suite from this branch, and the
Claude Code 2.1.227 PTY capture that measured PreCompact arriving alone on an
aborted compact.

* fix(agent-status): clear the restart-stuck pane a compact was meant to clear

Review found the completion did not clear the pane STA-2915 actually reports, and
that republishing it was a strict regression.

- A manual completion now retires a subagent that exists only as a disk snapshot:
  a /compact only completes at an idle prompt, so a restored child is proof of
  nothing. Live evidence -- a child observed in this runtime, an unclassifiable
  running background task, a registered session cron -- still holds the pane.
- A completion that cannot clear now publishes nothing instead of restating the
  row, which was stripping restoredUnconfirmed off a hydrated row and restarting
  the staleness clock for work the compact never observed.
- The relay defers compact ownership to the client that owns pane identity, so a
  cold relay cache can no longer swallow the one event that clears a remote pane.
- claudeConsumedCompactPromptIdByPaneKey joins all three pane-scoped teardown
  routes, and an auto compact no longer spends the pane's consumed-compact slot.
- The promptless completion keeps the summarized turn's label with or without a
  trigger on the envelope.

Tests: the two restart cases now deliver the completion while the hydrated row is
still cached, so they exercise the restored-row branch instead of passing through
the strict one; the triggerless working replay is asserted from a FINISHED pane so
it can fail. Reverting the four source files turns 12 of 21 registration-gated and
8 of 12 relay/ingest tests red, and 18 of 18 targeted mutations are caught.

* fix(agent-hooks): preserve compact identity across relay replay

* docs(reliability): describe compact replay ownership
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…-2915, STA-4613) (stablyai#15202)

* fix(agent-status): clear the pane when a Claude compact finishes (STA-2915, STA-4613)

A manual /compact ends at an idle prompt without emitting Stop, so nothing in the
compact window could ever clear the pane. A worktree that entered the compact
`working` stayed `working` until the 30-minute stale sweep -- and the summarizer's
start-less SubagentStop kept republishing the row, resetting that clock each time.

The correlation added by stablyai#12332 was supposed to own this, but it could never run:
PreCompact and PostCompact were never added to CLAUDE_EVENTS, so they were never
registered with Claude. compactTrigger was always undefined, and the transition
guard, the ownership cache, the relay wire field and the ingest branch were all
unreachable. Five test files exercised the logic by injecting events past the
registration boundary, so the suite stayed green over code that could not execute.

Register PostCompact -- and deliberately NOT PreCompact. Measured on Claude Code
2.1.227, a successful manual compact emits PreCompact, a start-less SubagentStop,
SessionStart(source=compact), then PostCompact; an ABORTED compact ("Not enough
messages to compact") emits PreCompact ALONE. Mapping PreCompact to `working`
would strand the pane on every aborted compact, which is the bug being fixed, so
the abort guard is structural: Orca never subscribes to the pre-validation event.

PostCompact carries its own trigger, so no anchor is needed to tell manual from
auto and the correlation machinery is deleted rather than repaired. Manual becomes
a `done` with sessionBoundary set -- a finished compact is a session-shaped
boundary, not a completed turn, so completion notifications, unread counts and
automation-run evidence stay out of it. Auto claims nothing: it runs inside a turn
that resumes and emits its own Stop.

The source-blind early return that dropped compact events for EVERY provider
before its normalizer ran is narrowed to Claude, so it keeps failing closed on a
malformed payload without pre-empting other providers.

Ownership is kept where the deleted guard had it: a valid provider prompt id is
required, a completion clears a row but never creates one (a retired pane must not
be resurrected), and a hydrated row is matched on provider session only -- it
carries the previous session's connectionId, and older rows carry no session at
all, so a strict check would reject the restart case this fixes. A consumed
prompt id keeps relay duplicates from refreshing the row.

Mixed versions: no new wire field and no new opcode. An older relay normalizes
with its own shipped mapping and forwards the event, so ingest drops `auto`
envelopes and stamps the boundary on `manual` ones; its replay strips the trigger
entirely, so payload state stands in for it while ownership is still enforced. The
relay now caches a completion with its compact identity removed, so a client that
was offline during the compact still receives the clearing row on reconnect.

Tests go red before this change and green after: 6 of 12 in the new
registration-gated suite and 5 of 8 in the relay/ingest suite. The harness delivers
only events present in CLAUDE_EVENTS, so a fix that is never registered cannot
pass -- the failure mode that let the original correlation ship unreachable.

* test(agent-status): restate the compact reliability gate around the new invariant

The gate pinned a test file this change deletes, so the manifest check failed.
Repointing the path alone would have left the gate describing an invariant that
no longer exists: it required a manual PostCompact to match its exact PreCompact
generation, and PreCompact is no longer consumed at all.

Restate it. The invariant is now that PreCompact never moves a pane, that only a
manual PostCompact marks done and does so as a session boundary, that a
completion clears an existing row but never creates one, and that a relay
predating the contract has its automatic envelopes dropped and its trigger-
stripped replays classified by payload state under the same ownership checks.

Evidence runs are the real ones: the 105-test suite from this branch, and the
Claude Code 2.1.227 PTY capture that measured PreCompact arriving alone on an
aborted compact.

* fix(agent-status): clear the restart-stuck pane a compact was meant to clear

Review found the completion did not clear the pane STA-2915 actually reports, and
that republishing it was a strict regression.

- A manual completion now retires a subagent that exists only as a disk snapshot:
  a /compact only completes at an idle prompt, so a restored child is proof of
  nothing. Live evidence -- a child observed in this runtime, an unclassifiable
  running background task, a registered session cron -- still holds the pane.
- A completion that cannot clear now publishes nothing instead of restating the
  row, which was stripping restoredUnconfirmed off a hydrated row and restarting
  the staleness clock for work the compact never observed.
- The relay defers compact ownership to the client that owns pane identity, so a
  cold relay cache can no longer swallow the one event that clears a remote pane.
- claudeConsumedCompactPromptIdByPaneKey joins all three pane-scoped teardown
  routes, and an auto compact no longer spends the pane's consumed-compact slot.
- The promptless completion keeps the summarized turn's label with or without a
  trigger on the envelope.

Tests: the two restart cases now deliver the completion while the hydrated row is
still cached, so they exercise the restored-row branch instead of passing through
the strict one; the triggerless working replay is asserted from a FINISHED pane so
it can fail. Reverting the four source files turns 12 of 21 registration-gated and
8 of 12 relay/ingest tests red, and 18 of 18 targeted mutations are caught.

* fix(agent-hooks): preserve compact identity across relay replay

* docs(reliability): describe compact replay ownership
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.

3 participants