refactor(claude): group root modules by defining owners

This commit is contained in:
Neil
2026-11-11 23:18:19 -08:00
parent 443a0ee846
commit 1c8587f802
329 changed files with 1314 additions and 14851 deletions
+4 -4
View File
@@ -44,8 +44,8 @@ on:
- 'src/main/native-chat/subagent-entry-id-bounds.ts'
- 'src/main/native-chat/agent-session-journal/item-lifecycle/journal-payload-bounds.ts'
- 'src/main/native-chat/agent-session-journal/item-lifecycle/journal-reasoning-row.ts'
- 'src/main/claude/claude-internal-message-content.ts'
- 'src/main/claude/claude-stop-hook-feedback.ts'
- 'src/main/claude/structured/journal/claude-internal-message-content.ts'
- 'src/main/claude/structured/journal/claude-stop-hook-feedback.ts'
- 'src/main/claude/structured/journal/**'
- 'src/main/claude/__fixtures__/claude-adapter-capture-fold.jsonl'
- 'src/main/codex/app-server/codex-item-field-readers.ts'
@@ -132,8 +132,8 @@ on:
- 'src/main/native-chat/subagent-entry-id-bounds.ts'
- 'src/main/native-chat/agent-session-journal/item-lifecycle/journal-payload-bounds.ts'
- 'src/main/native-chat/agent-session-journal/item-lifecycle/journal-reasoning-row.ts'
- 'src/main/claude/claude-internal-message-content.ts'
- 'src/main/claude/claude-stop-hook-feedback.ts'
- 'src/main/claude/structured/journal/claude-internal-message-content.ts'
- 'src/main/claude/structured/journal/claude-stop-hook-feedback.ts'
- 'src/main/claude/structured/journal/**'
- 'src/main/claude/__fixtures__/claude-adapter-capture-fold.jsonl'
- 'src/main/codex/app-server/codex-item-field-readers.ts'
@@ -45,9 +45,9 @@ ignores:
- '**/__fixtures__/**'
- 'src/shared/agent-launch/startup/claude-chat-entrypoint.ts'
- 'src/main/claude/claude-stream-json-connection.ts'
- 'src/main/claude/claude-agent-sdk-process-spawn.ts'
- 'src/main/claude/child-process/claude-agent-sdk-process-spawn.ts'
- 'src/main/claude/structured/launch/claude-structured-child-env.ts'
- 'src/main/claude/claude-model-catalog-probe.ts'
- 'src/main/claude/model-catalog/claude-model-catalog-probe.ts'
rule:
all:
- any:
@@ -67,9 +67,9 @@ ignores:
- '**/__fixtures__/**'
- 'src/shared/agent-launch/startup/claude-chat-entrypoint.ts'
- 'src/main/claude/claude-stream-json-connection.ts'
- 'src/main/claude/claude-agent-sdk-process-spawn.ts'
- 'src/main/claude/child-process/claude-agent-sdk-process-spawn.ts'
- 'src/main/claude/structured/launch/claude-structured-child-env.ts'
- 'src/main/claude/claude-model-catalog-probe.ts'
- 'src/main/claude/model-catalog/claude-model-catalog-probe.ts'
rule:
all:
- any:
@@ -16,7 +16,7 @@ export const MAIN_BUILD_ENTRY_POINTS: Record<string, string> = {
),
'computer-sidecar': resolve('src/main/computer/computer-sidecar.ts'),
'claude-conversation-fork-worker-entry': resolve(
'src/main/claude/claude-conversation-fork-worker-entry.ts'
'src/main/claude/transcripts/claude-conversation-fork-worker-entry.ts'
),
'stt-worker': resolve('src/main/speech/stt-worker.ts'),
'warp-theme-parser-worker': resolve('src/main/warp-themes/warp-theme-parser-worker.ts'),
+2 -37
View File
@@ -5,7 +5,6 @@
4 test-no-in-test-import-actual:src/main/bitbucket/credential-store.test.ts
1 test-no-in-test-import-actual:src/main/bitbucket/status-no-decrypt.test.ts
3 test-no-in-test-import-actual:src/main/claude-usage/scanner-scan.test.ts
1 test-no-in-test-import-actual:src/main/claude/claude-agent-sdk-process-spawn.test.ts
5 test-no-in-test-import-actual:src/main/daemon/endpoint/publication/testing/daemon-endpoint-publish.test.ts
1 test-no-in-test-import-actual:src/main/daemon/history/storage/testing/terminal-history-permissions.test.ts
1 test-no-in-test-import-actual:src/main/git/command-runner/process-capture/spawned-command-tree-kill.test.ts
@@ -28,14 +27,6 @@
3 test-no-in-test-import-actual:src/renderer/src/components/terminal-pane/snapshots/remote-snapshot-alt-screen-host-chain.test.ts
1 test-no-in-test-import-actual:src/renderer/src/hooks/useIpcEvents-agent-status-pane-teardown.test.ts
1 test-no-polling-loop:src/main/browser/cookies/browser-cookie-import-concurrency.test.ts
1 test-no-polling-loop:src/main/claude/claude-stop-ack-race.test.ts
1 test-no-polling-loop:src/main/claude/claude-stream-json-connection.test.ts
1 test-no-polling-loop:src/main/claude/claude-supervised-stop-real-cli.test.ts
1 test-no-polling-loop:src/main/claude/claude-supervised-stop.integration.test.ts
1 test-no-polling-loop:src/main/claude/structured/claude-structured-real-cli-fold.test.ts
1 test-no-polling-loop:src/main/claude/structured/claude-structured-real-cli-stop-task.test.ts
5 test-no-polling-loop:src/main/claude/structured/claude-structured-real-cli.test.ts
1 test-no-polling-loop:src/main/claude/structured/launch/claude-structured-real-cli-options.test.ts
1 test-no-polling-loop:src/main/codex/hooks/reconciliation/codex-hook-toggle-off-wins.test.ts
1 test-no-polling-loop:src/main/codex/structured/launch/codex-structured-real-cli-command-env.test.ts
1 test-no-polling-loop:src/main/daemon/providers/adapter/testing/daemon-self-retirement-respawn.test.ts
@@ -151,16 +142,6 @@
1 test-no-real-time-wait:src/main/browser/identity/wire-probes/browser-session-ua-wire-identity.electron.test.ts
1 test-no-real-time-wait:src/main/browser/network/tunnels/execution-route-socket-duplex.test.ts
1 test-no-real-time-wait:src/main/browser/network/tunnels/remote-browser-socks-server.test.ts
1 test-no-real-time-wait:src/main/claude/claude-agent-sdk-exit-proof.test.ts
1 test-no-real-time-wait:src/main/claude/claude-agent-sdk-user-message-queue.test.ts
1 test-no-real-time-wait:src/main/claude/claude-stop-ack-race.test.ts
1 test-no-real-time-wait:src/main/claude/claude-stream-json-connection.test.ts
1 test-no-real-time-wait:src/main/claude/claude-supervised-stop-real-cli.test.ts
1 test-no-real-time-wait:src/main/claude/claude-supervised-stop.integration.test.ts
2 test-no-real-time-wait:src/main/claude/structured/claude-structured-real-cli-fold.test.ts
2 test-no-real-time-wait:src/main/claude/structured/claude-structured-real-cli-stop-task.test.ts
5 test-no-real-time-wait:src/main/claude/structured/claude-structured-real-cli.test.ts
1 test-no-real-time-wait:src/main/claude/structured/launch/claude-structured-real-cli-options.test.ts
1 test-no-real-time-wait:src/main/codex/hooks/reconciliation/codex-hook-reconcile.test.ts
1 test-no-real-time-wait:src/main/codex/hooks/reconciliation/codex-hook-toggle-off-wins.test.ts
1 test-no-real-time-wait:src/main/codex/structured/launch/codex-structured-real-cli-command-env.test.ts
@@ -271,7 +252,6 @@
1 test-no-real-time-wait:tests/e2e/codex-ctrl-c-status.spec.ts
4 test-no-real-time-wait:tests/e2e/combined-diff-scroll-restore.spec.ts
1 test-no-real-time-wait:tests/e2e/computer-windows.e2e.ts
3 test-no-real-time-wait:tests/e2e/cross-version-wire/host-model-catalog-released-phone.unit.test.ts
1 test-no-real-time-wait:tests/e2e/cross-version-wire/legacy-relay-bridge.unit.test.ts
1 test-no-real-time-wait:tests/e2e/cross-version-wire/released-relay-daemon.ts
2 test-no-real-time-wait:tests/e2e/cross-version-wire/released-relay-transport.ts
@@ -427,7 +407,7 @@
2 test-no-wall-clock:src/main/agent-hooks/installation/scripts/managed-hook-timeout.test.ts
1 test-no-wall-clock:src/main/agent-hooks/server/testing/http/server-endpoint-file-lifecycle.test.ts
4 test-no-wall-clock:src/main/agent-hooks/server/testing/identity/server-launch-resume-identity.test.ts
5 test-no-wall-clock:src/main/agent-hooks/server/testing/replay/spool.test.ts
3 test-no-wall-clock:src/main/agent-hooks/server/testing/replay/spool.test.ts
3 test-no-wall-clock:src/main/agent-hooks/server/testing/structured-ingress/server-ingest-structured-status.test.ts
1 test-no-wall-clock:src/main/ai-vault/parse-cache/session-parse-cache-preview-upgrade.test.ts
2 test-no-wall-clock:src/main/ai-vault/scanners/copilot/session-scanner-copilot-parser.test.ts
@@ -440,16 +420,6 @@
2 test-no-wall-clock:src/main/antigravity/posix-hook-invocation.test.ts
2 test-no-wall-clock:src/main/browser/cookies/browser-cookie-import-partition-reland.electron.test.ts
2 test-no-wall-clock:src/main/browser/network/execution-routes/wsl-browser-network-execution-route.test.ts
1 test-no-wall-clock:src/main/claude/claude-background-wake-retention.test.ts
1 test-no-wall-clock:src/main/claude/claude-descendant-escalation-boundary.test.ts
1 test-no-wall-clock:src/main/claude/claude-folder-trust-file.test.ts
5 test-no-wall-clock:src/main/claude/claude-supervised-stop-real-cli.test.ts
6 test-no-wall-clock:src/main/claude/claude-supervised-stop.integration.test.ts
4 test-no-wall-clock:src/main/claude/structured/claude-structured-real-cli-fold.test.ts
1 test-no-wall-clock:src/main/claude/structured/claude-structured-real-cli-rewind.test.ts
3 test-no-wall-clock:src/main/claude/structured/claude-structured-real-cli-stop-task.test.ts
10 test-no-wall-clock:src/main/claude/structured/claude-structured-real-cli.test.ts
3 test-no-wall-clock:src/main/claude/structured/launch/claude-structured-real-cli-options.test.ts
1 test-no-wall-clock:src/main/codex-accounts/legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain-rollback-script.test.ts
6 test-no-wall-clock:src/main/codex/app-server/codex-app-server-client.test.ts
2 test-no-wall-clock:src/main/codex/structured/launch/codex-structured-real-cli-command-env.test.ts
@@ -628,12 +598,7 @@
1 test-timeout-needs-reason:src/main/browser/guest-lifecycle/find/browser-find-frame-traversal.electron.test.ts
1 test-timeout-needs-reason:src/main/browser/identity/wire-probes/browser-session-ua-wire-identity-cross-context.electron.test.ts
1 test-timeout-needs-reason:src/main/browser/identity/wire-probes/browser-session-ua-wire-identity.electron.test.ts
1 test-timeout-needs-reason:src/main/claude/claude-agent-sdk-exit-proof.test.ts
1 test-timeout-needs-reason:src/main/claude/claude-background-run-isolation-real-cli.test.ts
2 test-timeout-needs-reason:src/main/claude/claude-status-line-windows.test.ts
1 test-timeout-needs-reason:src/main/claude/claude-stop-ack-race.test.ts
1 test-timeout-needs-reason:src/main/claude/structured/claude-structured-real-cli.test.ts
1 test-timeout-needs-reason:src/main/claude/windows-native-hook-registration.test.ts
1 test-timeout-needs-reason:src/main/claude/child-process/claude-agent-sdk-exit-proof.test.ts
2 test-timeout-needs-reason:src/main/codex/app-server/codex-app-server-teardown.integration.test.ts
1 test-timeout-needs-reason:src/main/codex/hooks/installation/hook-service-legacy-cleanup.test.ts
1 test-timeout-needs-reason:src/main/codex/structured/catalog/codex-model-catalog-probe.test.ts
+1 -1
View File
@@ -1,6 +1,6 @@
{
"src/main/plugins/panels/plugin-source-transpile-worker-entry.ts": "Dedicated worker-thread entry; blocking work stays off Electron main.",
"src/main/claude/claude-conversation-fork-worker-entry.ts": "Dedicated worker-thread entry; blocking work stays off Electron main.",
"src/main/claude/transcripts/claude-conversation-fork-worker-entry.ts": "Dedicated worker-thread entry; blocking work stays off Electron main.",
"src/main/speech/stt-worker.ts": "Dedicated utility/forked-process entry; speech work stays off Electron main.",
"src/main/warp-themes/warp-theme-parser-worker.ts": "Dedicated worker-thread entry; blocking work stays off Electron main.",
"src/main/ai-vault-search/worker/session-search-worker-entry.ts": "Dedicated worker-thread entry; blocking work stays off Electron main.",
+7 -7
View File
@@ -89,14 +89,14 @@
1 src/main/claude-accounts/runtime-auth/runtime-paths.ts
7 src/main/claude-accounts/sign-in/claude-account-folder.ts
3 src/main/claude/agent-view/agent-view-install.ts
1 src/main/claude/claude-diff-panel-auto-open.ts
14 src/main/claude/claude-folder-trust-file.ts
2 src/main/claude/claude-profile-hook-target.ts
1 src/main/claude/claude-rejected-api-key.ts
1 src/main/claude/claude-rewind-transcript.ts
1 src/main/claude/configuration/claude-diff-panel-auto-open.ts
14 src/main/claude/configuration/claude-folder-trust-file.ts
2 src/main/claude/hooks/claude-profile-hook-target.ts
1 src/main/claude/configuration/claude-rejected-api-key.ts
1 src/main/claude/transcripts/claude-rewind-transcript.ts
1 src/main/claude/hook-service.ts
3 src/main/claude/statusline-install.ts
6 src/main/claude/windows-hook-files.ts
3 src/main/claude/hooks/statusline-install.ts
6 src/main/claude/hooks/windows-hook-files.ts
1 src/main/cli/appimage/appimage-copy-pre-extraction.ts
3 src/main/cli/appimage/appimage-extracted-root.ts
1 src/main/cli/appimage/appimage-extraction-pruning.ts
@@ -1056,62 +1056,62 @@
"src/main/claude/agent-view/agent-view-service.test.ts": 403,
"src/main/claude/claude-agent-sdk-contract-pins.test.ts": 3506,
"src/main/claude/claude-agent-sdk-exit-proof-identity.test.ts": 134,
"src/main/claude/claude-agent-sdk-exit-proof.test.ts": 8832,
"src/main/claude/claude-agent-sdk-import-boundary.test.ts": 546,
"src/main/claude/claude-agent-sdk-process-spawn.test.ts": 182,
"src/main/claude/claude-agent-sdk-user-message-queue.test.ts": 143,
"src/main/claude/child-process/claude-agent-sdk-exit-proof.test.ts": 8832,
"src/main/claude/sdk-transport/claude-agent-sdk-import-boundary.test.ts": 546,
"src/main/claude/child-process/claude-agent-sdk-process-spawn.test.ts": 182,
"src/main/claude/sdk-transport/claude-agent-sdk-user-message-queue.test.ts": 143,
"src/main/claude/claude-api-retry-row.test.ts": 901,
"src/main/claude/claude-background-run-isolation-real-cli.test.ts": 147,
"src/main/claude/claude-background-stop-records.test.ts": 1249,
"src/main/claude/claude-background-task-resume.test.ts": 54,
"src/main/claude/claude-background-task-terminal-frames.test.ts": 103,
"src/main/claude/background-tasks/claude-background-task-resume.test.ts": 54,
"src/main/claude/background-tasks/claude-background-task-terminal-frames.test.ts": 103,
"src/main/claude/claude-background-task-turn-resumption.test.ts": 325,
"src/main/claude/claude-background-wake-retention.test.ts": 1652,
"src/main/claude/claude-child-process-environment.test.ts": 52,
"src/main/claude/claude-child-work-decoder.test.ts": 110,
"src/main/claude/child-process/claude-child-process-environment.test.ts": 52,
"src/main/claude/child-work/claude-child-work-decoder.test.ts": 110,
"src/main/claude/claude-close-turn-end.test.ts": 970,
"src/main/claude/claude-command-lifecycle-frames.test.ts": 268,
"src/main/claude/claude-command-lifecycle.test.ts": 1107,
"src/main/claude/claude-command-turn.test.ts": 292,
"src/main/claude/claude-config-dir-pin.test.ts": 47,
"src/main/claude/structured/turns/claude-command-lifecycle-frames.test.ts": 268,
"src/main/claude/structured/turns/claude-command-lifecycle.test.ts": 1107,
"src/main/claude/structured/turns/claude-command-turn.test.ts": 292,
"src/main/claude/structured/launch/claude-config-dir-pin.test.ts": 47,
"src/main/claude/claude-context-model-switch.test.ts": 422,
"src/main/claude/claude-context-usage-restart.test.ts": 925,
"src/main/claude/claude-context-usage-unloaded-turn.test.ts": 4910,
"src/main/claude/claude-descendant-escalation-boundary.test.ts": 593,
"src/main/claude/claude-diff-panel-auto-open.test.ts": 117,
"src/main/claude/configuration/claude-diff-panel-auto-open.test.ts": 117,
"src/main/claude/claude-fold-steer-receipt.test.ts": 1019,
"src/main/claude/claude-folder-trust-file.test.ts": 762,
"src/main/claude/claude-hook-event-versions.test.ts": 137,
"src/main/claude/configuration/claude-folder-trust-file.test.ts": 762,
"src/main/claude/cli-capabilities/claude-hook-event-versions.test.ts": 137,
"src/main/claude/claude-informational-row.test.ts": 811,
"src/main/claude/claude-journal-turn-scope.test.ts": 254,
"src/main/claude/claude-model-catalog-probe.test.ts": 2098,
"src/main/claude/structured/journal/claude-journal-turn-scope.test.ts": 254,
"src/main/claude/model-catalog/claude-model-catalog-probe.test.ts": 2098,
"src/main/claude/claude-naming-invocation.test.ts": 334,
"src/main/claude/claude-plan-approval-mode.test.ts": 905,
"src/main/claude/claude-profile-hooks.test.ts": 371,
"src/main/claude/claude-provider-session-rename.test.ts": 597,
"src/main/claude/claude-provisional-row-corrections.test.ts": 67,
"src/main/claude/claude-request-end-wait.test.ts": 53,
"src/main/claude/claude-rewind-transcript.test.ts": 762,
"src/main/claude/hooks/claude-profile-hooks.test.ts": 371,
"src/main/claude/transcripts/claude-provider-session-rename.test.ts": 597,
"src/main/claude/subagents/claude-provisional-row-corrections.test.ts": 67,
"src/main/claude/structured/turns/claude-request-end-wait.test.ts": 53,
"src/main/claude/transcripts/claude-rewind-transcript.test.ts": 762,
"src/main/claude/claude-settings-schema-install.test.ts": 410,
"src/main/claude/claude-status-line-install.test.ts": 342,
"src/main/claude/hooks/claude-status-line-install.test.ts": 342,
"src/main/claude/claude-status-line-windows.test.ts": 273,
"src/main/claude/claude-stop-ack-race.test.ts": 1301,
"src/main/claude/claude-stream-json-connection-close.test.ts": 621,
"src/main/claude/claude-stream-json-connection.test.ts": 8687,
"src/main/claude/claude-streamed-text-checkpoints.test.ts": 59,
"src/main/claude/sdk-transport/claude-stream-json-connection.test.ts": 8687,
"src/main/claude/structured/journal/claude-streamed-text-checkpoints.test.ts": 59,
"src/main/claude/claude-structured-launch-home-perf.test.ts": 401,
"src/main/claude/claude-structured-result-control-overlap.test.ts": 1136,
"src/main/claude/claude-subagent-id-aliases.test.ts": 46,
"src/main/claude/subagents/claude-subagent-id-aliases.test.ts": 46,
"src/main/claude/claude-subagent-permission-request.test.ts": 3776,
"src/main/claude/claude-subagent-resume-after-restart.test.ts": 825,
"src/main/claude/subagents/claude-subagent-resume-after-restart.test.ts": 825,
"src/main/claude/claude-supervised-stop-real-cli.test.ts": 382,
"src/main/claude/claude-supervised-stop.integration.test.ts": 3821,
"src/main/claude/claude-transcript-catch-up.test.ts": 4017,
"src/main/claude/transcripts/claude-transcript-catch-up.test.ts": 4017,
"src/main/claude/claude-transcript-duration.test.ts": 1411,
"src/main/claude/claude-transcript-entry-uuid.test.ts": 38,
"src/main/claude/hook-service.test.ts": 329,
"src/main/claude/post-compact-hook-command.test.ts": 314,
"src/main/claude/statusline-script.test.ts": 257,
"src/main/claude/transcripts/claude-transcript-entry-uuid.test.ts": 38,
"src/main/claude/hooks/hook-service.test.ts": 329,
"src/main/claude/hooks/post-compact-hook-command.test.ts": 314,
"src/main/claude/hooks/statusline-script.test.ts": 257,
"src/main/claude/structured/claude-structured-content-parts.test.ts": 277,
"src/main/claude/structured/claude-structured-conversation-stop.test.ts": 884,
"src/main/claude/structured/claude-structured-dispatch-admission.test.ts": 426,
@@ -1153,7 +1153,7 @@
"src/main/claude/structured/launch/claude-structured-options.test.ts": 420,
"src/main/claude/structured/launch/claude-structured-provider-fallback.test.ts": 670,
"src/main/claude/structured/launch/claude-structured-real-cli-options.test.ts": 902,
"src/main/claude/windows-hook-files.test.ts": 356,
"src/main/claude/hooks/windows-hook-files.test.ts": 356,
"src/main/claude/windows-native-hook-registration.test.ts": 246,
"src/main/cli/appimage/appimage-copy-pre-extraction.test.ts": 328,
"src/main/cli/appimage/appimage-extraction-pruning-namespace.test.ts": 106,
@@ -29,7 +29,7 @@ export const ORCAD_CHILD_ENTRY_POINTS = {
'src/main/worker-thread-child-process/worker-thread-child-process-entry.ts',
claudeProfileSetup:
'src/main/claude-accounts/profiles/setup/claude-profile-setup-worker-entry.ts',
claudeConversationFork: 'src/main/claude/claude-conversation-fork-worker-entry.ts',
claudeConversationFork: 'src/main/claude/transcripts/claude-conversation-fork-worker-entry.ts',
sttWorker: 'src/main/speech/stt-worker.ts',
computerSidecar: 'src/main/computer/computer-sidecar.ts'
}
@@ -33,8 +33,7 @@ const NODE_RUNTIME_INCLUDE = [
'config/scripts/test-runtime/dom/happy-dom-mutation-observer-retention.test.ts',
// These reach Node SQLite through a shared helper or a dynamic import, which the scan skips.
'src/main/agent-hooks/server/testing/providers/codex/server-codex-session-start.test.ts',
'src/main/claude/claude-transcript-catch-up.test.ts',
'src/main/claude/claude-transcript-duration.test.ts',
'src/main/claude/transcripts/claude-transcript-catch-up.test.ts',
'tests/e2e/native-chat-startup-option-pickers.unit.test.ts',
'src/main/ai-vault/transcripts/session-document-consumer-replacement.test.ts',
'src/main/ai-vault-search/indexing/session-search-dependent-transcripts.test.ts',
@@ -44,7 +43,6 @@ const NODE_RUNTIME_INCLUDE = [
'src/main/runtime/orchestration/mailbox/routing/orchestration-mailbox-routing.test.ts',
'tests/e2e/cross-version-wire/agent-session-clear-old-client.unit.test.ts',
'tests/e2e/cross-version-wire/agent-session-clear-old-tab-mirror.unit.test.ts',
'tests/e2e/cross-version-wire/host-model-catalog-released-phone.unit.test.ts',
'src/main/pi/rpc/rpc-session-startup.test.ts',
'src/main/acp/session/acp-structured-omp-recordings.test.ts',
'src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-clear-queued-command.test.ts',
@@ -150,7 +148,6 @@ const NODE_RUNTIME_INCLUDE = [
'src/main/ipc/filesystem/watchers/filesystem-watcher-ignore-real.test.ts',
'src/main/ipc/runtime-environments/runtime-environment-preference.test.ts',
'src/renderer/src/components/emulator-pane/emulator-device-frame-visibility.test.tsx',
'src/main/claude/claude-agent-sdk-contract-pins.test.ts',
'config/scripts/desktop-distribution/runtime-verification/process-host-dev-rebuild.test.ts',
'config/scripts/test-runtime/node-worker/vitest-node-runtime-pool.test.ts',
// Reopen WAL-backed row caches read-only, which Bun on macOS cannot.
@@ -251,7 +251,7 @@ const CROSS_VERSION_WIRE_PREFIXES = [
'src/main/native-chat/agent-model-catalog/agent-model-catalog-lister.ts',
'src/main/native-chat/agent-model-catalog/agent-model-catalog-listing-waiters.ts',
'src/main/native-chat/agent-model-catalog/agent-model-catalog-probe-runner.ts',
'src/main/claude/claude-model-catalog-probe.ts',
'src/main/claude/model-catalog/claude-model-catalog-probe.ts',
'src/main/runtime/agent-session/records/agent-session-record-store',
'src/main/runtime/agent-session/records/agent-session-recovery-capsule',
'src/shared/agent-session-resume-marker',
@@ -320,7 +320,7 @@ export const PR_E2E_SOURCE_ROUTES = [
MANAGED_SSH_HARNESS.test(file) ||
file === 'tests/e2e/fixtures/structured-claude-stub.cjs' ||
(isProductSource(file) &&
/^src\/(?:main\/(?:claude\/claude-(?:stream-json-connection|stream-json-exit-error|structured-session-exit-lifecycle)|native-chat\/agent-session-wire\/structured-agent-session-failure-text)|renderer\/src\/components\/native-chat\/structured-agent-session-delivery-notices)\.ts$/.test(
/^src\/(?:main\/(?:claude\/(?:claude-(?:stream-json-connection|structured-session-exit-lifecycle)|sdk-transport\/claude-stream-json-exit-error)|native-chat\/agent-session-wire\/structured-agent-session-failure-text)|renderer\/src\/components\/native-chat\/structured-agent-session-delivery-notices)\.ts$/.test(
file
))
},
@@ -170,12 +170,9 @@ export const WINDOWS_BOUNDARY_TESTS = [
'src/shared/windows-batch-spawn.win32.test.ts',
'src/main/claude/structured/launch/claude-structured-child-env.test.ts',
'src/main/agent-hooks/installation/commands/windows-hook-payload-delivery.test.ts',
'src/main/agent-hooks/installation/scripts/managed-hook-stdin-lifecycle.test.ts',
'src/main/jcode/hook-gate-script.test.ts',
'src/main/agent-hooks/installation/commands/windows-native-hook-exe-hosts.test.ts',
'src/main/claude/windows-native-hook-registration.test.ts',
'src/main/agent-hooks/installation/commands/windows-batch-hook-launcher.test.ts',
'src/main/claude/claude-status-line-windows.test.ts',
'src/main/codex/hooks/installation/windows-hook-command.test.ts',
'src/main/codex/hooks/installation/hook-service-managed-install.test.ts',
'src/main/windows/windows-pty-job.win32.test.ts',
@@ -4,7 +4,7 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { runProcess } from '@orca/process-host'
import { removeTree } from '../../../../shared/windows-transient-lock-removal'
import '../../../claude/hook-settings'
import '../../../claude/hooks/hook-settings'
import { wrapWindowsBatchHookCommand } from './windows-direct-cmd-hook-command'
import './testing/windows-git-bash-path.test-fixture'
import { getWindowsPowerShellExecutablePath } from './windows-powershell-hook-launcher'
@@ -12,7 +12,7 @@ import {
isAgentStatusHooksEnabled,
isAgentStatusHooksEnabledForAgent
} from '../../../shared/agent-hook-listener/configuration/agent-status-hooks-setting'
import { probeClaudeCliVersion } from '../../claude/claude-hook-event-versions'
import { probeClaudeCliVersion } from '../../claude/cli-capabilities/claude-hook-event-versions'
import { detectLocalManagedAgentCliPresence } from './local-agent-cli-presence'
import {
MANAGED_AGENT_HOOK_ASYNC_REMOVERS,
@@ -7,7 +7,7 @@ import { MANAGED_AGENT_HOOK_TARGETS } from '../../../shared/managed-agent-hook-t
import { normalizeDisabledTuiAgents } from '../../../shared/agent-launch/catalog/tui-agent-selection'
import type { GlobalSettings } from '../../../shared/global-settings-types'
import type { TuiAgentDetectionCommand } from '../../../shared/agent-launch/catalog/tui-agent-detection-commands'
import { parseClaudeCliVersionOutput } from '../../claude/claude-hook-event-versions'
import { parseClaudeCliVersionOutput } from '../../claude/cli-capabilities/claude-hook-event-versions'
export type ManagedHookDetectionSettings = Partial<
Pick<
@@ -4,7 +4,7 @@ vi.mock('electron', () => ({ app: { getPath: () => '/tmp/userData' } }))
import { runVendorHook } from './testing/vendor-hook-delivery.test-fixture'
import { getManagedScript as getClaudeManagedScript } from '../../../claude/hook-service'
import { getManagedScript as getClaudeManagedScript } from '../../../claude/hooks/hook-script'
import { getManagedScript as getCursorManagedScript } from '../../../cursor/hook-script'
const CLAUDE_SCRIPT_OPTIONS = {
@@ -2,7 +2,7 @@ import { describe, expect, it, vi } from 'vitest'
vi.mock('electron', () => ({ app: { getPath: () => '/tmp/userData' } }))
import { getManagedScript as getClaudeManagedScript } from '../../../claude/hook-service'
import { getManagedScript as getClaudeManagedScript } from '../../../claude/hooks/hook-script'
import { getManagedScript as getCursorManagedScript } from '../../../cursor/hook-script'
import { runVendorHook } from './testing/vendor-hook-delivery.test-fixture'
@@ -1,284 +0,0 @@
// POSIX hooks drain before exit; Windows missing-context hooks may exit without owning stdin.
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import type * as CodexHookHashLookup from '../../../codex/trust/hooks/codex-hook-hash-lookup'
import { spawnProcess } from '@orca/process-host'
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import type * as osModule from 'node:os'
import type * as NativeHookExecutableModule from '../commands/windows-native-hook-executable'
let isolatedUserDataDir = ''
let previousUserDataPath: string | undefined
beforeEach(() => {
vi.stubEnv('GROK_HOME', undefined)
vi.stubEnv('KIMI_CODE_HOME', undefined)
vi.stubEnv('COPILOT_HOME', undefined)
vi.stubEnv('KIRO_HOME', undefined)
vi.stubEnv('XDG_CONFIG_HOME', undefined)
previousUserDataPath = process.env.ORCA_USER_DATA_PATH
isolatedUserDataDir = mkdtempSync(join(tmpdir(), 'orca-hook-stdin-user-data-'))
// Isolate managed-script resolution so inherited user-data paths cannot target live hooks.
process.env.ORCA_USER_DATA_PATH = isolatedUserDataDir
})
afterEach(() => {
if (previousUserDataPath === undefined) {
delete process.env.ORCA_USER_DATA_PATH
} else {
process.env.ORCA_USER_DATA_PATH = previousUserDataPath
}
rmSync(isolatedUserDataDir, { recursive: true, force: true })
vi.unstubAllEnvs()
})
const { homedirMock, bundledHook } = vi.hoisted(() => {
const bundledHook: { path: string | null } = { path: null }
return { homedirMock: vi.fn<() => string>(), bundledHook }
})
// Test the real built executable without packaged resource lookup.
vi.mock('../commands/windows-native-hook-executable', async (importOriginal) => ({
...(await importOriginal<typeof NativeHookExecutableModule>()),
resolveBundledWindowsNativeHookExecutable: () => bundledHook.path
}))
vi.mock('../../../codex/trust/hooks/codex-hook-hash-lookup', async (importOriginal) => ({
...(await importOriginal<typeof CodexHookHashLookup>()),
resolveCodexHookAnswerForLaunch: async () =>
(
await import('../../../codex/hooks/installation/hook-service-test-harness')
).codexHookAnswerForTests()
}))
vi.mock('electron', () => ({
app: {
getPath: () => '/tmp/orca-user-data'
}
}))
vi.mock('os', async (importOriginal) => {
const actual = await importOriginal<typeof osModule>()
return {
...actual,
homedir: homedirMock.mockImplementation(actual.homedir)
}
})
import '../../../antigravity/hook-service'
import { ClaudeHookService } from '../../../claude/hook-service'
import '../../../claude/hook-settings'
import '../../../codex/hooks/installation/hook-service'
import '../../../codex/hooks/installation/codex-hook-service-implementation'
import '../../../command-code/hook-service'
import '../../../copilot/hook-service'
import '../../../cursor/hook-service'
import '../../../devin/hook-service'
import '../../../droid/hook-service'
import '../../../gemini/hook-service'
import '../../../grok/hook-service'
import '../../../kimi/hook-service'
import '../../../openclaude/hook-service'
import { POSIX_HOOK_STDIN_READER } from './hook-stdin-contract'
import '../commands/runtime-home-hook-command'
import '../remote/testing/agent-hook-memory-sftp.test-fixture'
import { findGitBash } from '../commands/testing/windows-git-bash-path.test-fixture'
import {
WINDOWS_POWERSHELL_WARM_UP_TIMEOUT_MS,
warmWindowsEncodedPowerShell
} from '../commands/testing/windows-powershell-warm-up.test-fixture'
import {
buildWindowsNativeHookExecutable,
WINDOWS_NATIVE_HOOK_BUILD_TIMEOUT_MS
} from '../commands/testing/windows-native-hook-exe.test-fixture'
const REMOTE_HOME = '/home/dev'
const LARGE_PAYLOAD = Buffer.alloc(1_000_000, 'x')
// Seed the user's usual AutoRun target so profile redirection cannot introduce cmd stderr noise.
function seedCmdAutoRunTarget(profileDir: string): void {
mkdirSync(profileDir, { recursive: true })
writeFileSync(join(profileDir, '.cmd_aliases.cmd'), '@echo off\r\n', 'utf8')
}
type HookRun = {
exitCode: number | null
stdinErrors: NodeJS.ErrnoException[]
stderr: string
stdout: string
}
function runHookProcess(
executable: string,
args: string[],
env: NodeJS.ProcessEnv,
// An open, unwritten pipe exposes read-to-EOF hangs outside an Orca pane.
stdin: 'close' | 'abandon' = 'close'
): Promise<HookRun> {
return new Promise((resolve, reject) => {
const child = spawnProcess({
program: executable,
args,
env,
stdio: 'pipe'
})
const stdinErrors: NodeJS.ErrnoException[] = []
let stderr = ''
let stdout = ''
const timeout = setTimeout(() => {
child.stdin.destroy()
child.kill('SIGKILL')
reject(
new Error(
`hook did not finish with stdin ${stdin}d: ${executable} ${args.join(' ').slice(0, 200)}`
)
)
}, 10_000)
child.on('error', (error) => {
clearTimeout(timeout)
reject(error)
})
child.stdout.on('data', (chunk: Buffer) => {
stdout += chunk.toString()
})
child.stderr.on('data', (chunk: Buffer) => {
stderr += chunk.toString()
})
child.stdin.on('error', (error: NodeJS.ErrnoException) => stdinErrors.push(error))
child.on('close', (exitCode) => {
clearTimeout(timeout)
resolve({ exitCode, stdinErrors, stderr, stdout })
})
if (stdin === 'close') {
child.stdin.end(LARGE_PAYLOAD)
}
})
}
function hookEnvironment(extraEnv: NodeJS.ProcessEnv = {}): NodeJS.ProcessEnv {
const env = Object.fromEntries(
Object.entries(process.env).filter(([key]) => !key.startsWith('ORCA_'))
)
return {
...env,
HOME: REMOTE_HOME,
ORCA_AGENT_HOOK_ENDPOINT: '',
...extraEnv
}
}
describe('Windows managed hook stdin structure', () => {
beforeAll(async () => {
if (process.platform === 'win32') {
await warmWindowsEncodedPowerShell(hookEnvironment())
}
}, WINDOWS_POWERSHELL_WARM_UP_TIMEOUT_MS)
// Command-shape assertions missed conhost discarding the consumer's JSON output.
it.skipIf(process.platform !== 'win32').each([
{ form: 'claude-hook.cmd', bundled: false },
{ form: 'orca-agent-hook.exe claude', bundled: true }
])(
'emits parseable JSON on stdout from the registered Claude hook command ($form), through cmd.exe and Git Bash',
async ({ form, bundled }) => {
const home = mkdtempSync(join(tmpdir(), 'orca-hook-stdout-json-'))
homedirMock.mockReturnValue(home)
const absentProfile = join(home, 'absent')
seedCmdAutoRunTarget(home)
seedCmdAutoRunTarget(absentProfile)
try {
bundledHook.path = bundled ? buildWindowsNativeHookExecutable() : null
expect(new ClaudeHookService().install().state).toBe('installed')
const settings = JSON.parse(
readFileSync(join(home, '.claude', 'settings.json'), 'utf8')
) as { hooks: Record<string, { hooks: { command: string; args?: string[] }[] }[]> }
const entry = settings.hooks.PreToolUse[0].hooks[0]
expect(entry.args).toBeUndefined()
expect(entry.command.endsWith(form)).toBe(true)
// MSYS rewrites paths and switches, so exercise both shells.
const gitBash = findGitBash()
const shells = [
{ name: 'cmd.exe', executable: 'cmd.exe', args: ['/d', '/c', entry.command] },
{ name: 'Git Bash', executable: gitBash, args: ['-c', entry.command] }
]
const environments = [
{ name: 'no Orca env', env: hookEnvironment({ USERPROFILE: home }) },
{
name: 'Orca env with dead listener',
env: hookEnvironment({
USERPROFILE: home,
ORCA_AGENT_HOOK_PORT: '59999',
ORCA_AGENT_HOOK_TOKEN: 'token',
ORCA_PANE_KEY: 'tab:leaf'
})
},
{
// Profile redirection hides runtime-resolved scripts; direct launchers retain their absolute path.
name: 'missing managed script',
env: hookEnvironment({ USERPROFILE: absentProfile })
}
]
for (const shell of shells) {
for (const environment of environments) {
const label = `${shell.name} / ${environment.name}`
const result = await runHookProcess(shell.executable, shell.args, environment.env)
expect(result.exitCode, `${label} exit code`).toBe(0)
expect(result.stderr, `${label} stderr`).toBe('')
expect(() => JSON.parse(result.stdout.trim()), `${label} stdout is JSON`).not.toThrow()
expect(JSON.parse(result.stdout.trim()), `${label} stdout`).toEqual({})
}
if (bundled) {
const abandoned = await runHookProcess(
shell.executable,
shell.args,
environments[0].env,
'abandon'
)
expect(abandoned.exitCode, `${shell.name} abandoned-stdin exit code`).toBe(0)
}
}
} finally {
bundledHook.path = null
homedirMock.mockImplementation(() => process.env.HOME ?? tmpdir())
rmSync(home, { recursive: true, force: true })
}
},
// Allow cold executable builds and six shell launches under load.
WINDOWS_NATIVE_HOOK_BUILD_TIMEOUT_MS
)
})
describe.skipIf(process.platform === 'win32')('managed hook stdin lifecycle', () => {
// Exit zero does not prove stdin was consumed; measure captured bytes.
it.each([
['empty PATH', ''],
// NixOS may lack /bin/cat; exercise the shell's default PATH.
['PATH without coreutils', '/nonexistent'],
['PATH whose first cat is a decoy', '']
])('captures the whole payload with %s', async (label, pathValue) => {
const decoyDir = mkdtempSync(join(tmpdir(), 'orca-hook-stdin-decoy-'))
try {
let effectivePath = pathValue
if (label === 'PATH whose first cat is a decoy') {
const decoy = join(decoyDir, 'cat')
writeFileSync(decoy, '#!/bin/sh\nexit 0\n', { mode: 0o755 })
effectivePath = decoyDir
}
const result = await runHookProcess(
'/bin/sh',
['-c', `payload=$(${POSIX_HOOK_STDIN_READER}); printf '%s' "${'${#payload}'}"`],
{ ...hookEnvironment(), PATH: effectivePath }
)
expect(result.exitCode, `${label} exit code`).toBe(0)
expect(result.stdinErrors, `${label} stdin errors`).toHaveLength(0)
expect(result.stdout, `${label} captured bytes`).toBe(String(LARGE_PAYLOAD.length))
} finally {
rmSync(decoyDir, { recursive: true, force: true })
}
})
})
@@ -1,8 +1,6 @@
import { readSavedStatus } from '../persistence/last-status.test-fixtures'
import { describe, expect, it } from 'vitest'
import {
appendFileSync,
chmodSync,
mkdirSync,
mkdtempSync,
readFileSync,
@@ -19,10 +17,9 @@ import {
launchTokenHash,
type SpoolRecord
} from '../../../../../shared/agent-hook-listener/transport/agent-hook-spool'
import { AgentHookServer, _internals } from '../../agent-hook-server'
import { buildBody } from '../server.test-fixtures'
import { _internals as codexInternals } from '../../../../codex/hooks/installation/hook-service'
import { getManagedScript as getClaudeManagedScript } from '../../../../claude/hook-script'
import { AgentHookServer } from '../../agent-hook-server'
import { getManagedScript as getClaudeManagedScript } from '../../../../claude/hooks/hook-script'
import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id'
describe('agent hook spool', () => {
@@ -102,49 +99,6 @@ describe('agent hook spool', () => {
expect(statSync(file).ino).toBe(inode)
})
it('replays a spooled Codex SubagentStop through the server after restart', async () => {
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-spool-e2e-'))
const paneKey = makePaneKey('tab-spool', '00000000-0000-4000-8000-000000000001')
const launchToken = 'generation-token'
const first = new AgentHookServer()
await first.start({ env: 'production', userDataPath })
const started = _internals.normalizeHookPayload(
'codex',
buildBody({ hook_event_name: 'SubagentStart', agent_id: 'child-spooled' }),
'production'
)!
first.ingestRemote(
{
paneKey,
source: 'codex',
hookEventName: 'SubagentStart',
launchToken,
payload: started.payload
},
'spool-test'
)
expect(first.getStatusSnapshot()).toHaveLength(1)
first.flushStatusPersistSync()
first.stop()
const spoolDir = join(userDataPath, 'agent-hooks', 'spool')
mkdirSync(spoolDir, { recursive: true })
writeFileSync(
join(spoolDir, 'pane-tab-spooled_0.jsonl'),
`\n${JSON.stringify({ paneKey, source: 'codex', hookEventName: 'SubagentStop', launchToken, receivedAt: Date.now(), payload: { hook_event_name: 'SubagentStop', agent_id: 'child-spooled' } })}\n`
)
const restarted = new AgentHookServer()
await restarted.start({ env: 'production', userDataPath })
try {
const snapshot = restarted.getStatusSnapshot()
expect(snapshot).toHaveLength(1)
expect(snapshot[0]!.subagents).toBeUndefined()
restarted.flushStatusPersistSync()
expect(readSavedStatus(restarted.lastStatusPath!)).not.toContain('isReplay')
} finally {
restarted.stop()
}
})
it('rejects a stale remote replay against the hydrated launch-token fence', async () => {
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-spool-remote-fence-'))
const paneKey = makePaneKey('tab-remote-fence', '00000000-0000-4000-8000-000000000003')
@@ -186,37 +140,6 @@ describe('agent hook spool', () => {
}
})
it('spools when the endpoint is present but the receiver is unavailable', () => {
const dir = mkdtempSync(join(tmpdir(), 'orca-spool-failure-'))
const endpointDir = join(dir, 'agent-hooks')
mkdirSync(endpointDir, { recursive: true })
const endpoint = join(endpointDir, 'endpoint.env')
writeFileSync(
endpoint,
'ORCA_AGENT_HOOK_PORT=9\nORCA_AGENT_HOOK_TOKEN=stale\nORCA_AGENT_HOOK_ENV=production\nORCA_AGENT_HOOK_VERSION=1\n'
)
const script = join(dir, 'codex-hook.sh')
writeFileSync(script, codexInternals.getManagedScript('posix'))
chmodSync(script, 0o755)
execFileSync('/bin/sh', [script], {
input: '{"hook_event_name":"SubagentStop","agent_id":"child"}\n',
env: {
...process.env,
ORCA_AGENT_HOOK_ENDPOINT: endpoint,
ORCA_PANE_KEY: 'tab-failure:0',
ORCA_TAB_ID: 'tab-failure',
ORCA_AGENT_LAUNCH_TOKEN: 'generation-token',
CLAUDE_JOB_DIR: ''
},
timeout: 5000
})
const spoolFiles = readdirSync(join(endpointDir, 'spool'))
expect(spoolFiles).toHaveLength(1)
expect(readFileSync(join(endpointDir, 'spool', spoolFiles[0]!), 'utf8')).toContain(
'SubagentStop'
)
})
it('keeps a Claude hook attributed when CLAUDE_CODE_SUBPROCESS_ENV_SCRUB drops the pane key', () => {
const dir = mkdtempSync(join(tmpdir(), 'orca-spool-scrubbed-'))
const endpointDir = join(dir, 'agent-hooks')
@@ -278,42 +201,4 @@ describe('agent hook spool', () => {
expect(records).toHaveLength(1)
expect(records[0]).toContain('"Stop"')
})
it('does not mark a non-terminal downtime replay as runtime-observed', async () => {
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-spool-observed-'))
const paneKey = makePaneKey('tab-observed', '00000000-0000-4000-8000-000000000002')
const launchToken = 'observed-generation'
const first = new AgentHookServer()
await first.start({ env: 'production', userDataPath })
const started = _internals.normalizeHookPayload(
'codex',
buildBody({ hook_event_name: 'SubagentStart', agent_id: 'child-observed' }),
'production'
)!
first.ingestRemote(
{
paneKey,
source: 'codex',
hookEventName: 'SubagentStart',
launchToken,
payload: started.payload
},
null
)
first.flushStatusPersistSync()
first.stop()
const spoolDir = join(userDataPath, 'agent-hooks', 'spool')
mkdirSync(spoolDir, { recursive: true })
writeFileSync(
join(spoolDir, 'pane-observed.jsonl'),
`\n${JSON.stringify({ paneKey, source: 'codex', hookEventName: 'SubagentStart', launchToken, receivedAt: Date.now(), payload: started.payload })}\n`
)
const restarted = new AgentHookServer()
await restarted.start({ env: 'production', userDataPath })
try {
expect(restarted.getStatusChangeSnapshot()[0]?.observedInCurrentRuntime).toBe(false)
} finally {
restarted.stop()
}
})
})
@@ -11,7 +11,7 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import type * as NodePath from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type * as ClaudeFolderTrustFile from '../../claude/claude-folder-trust-file'
import type * as ClaudeFolderTrustFile from '../../claude/configuration/claude-folder-trust-file'
const CODEX_CONFIG_FILES = ['/orca/codex-home/config.toml', '/home/u/.codex/config.toml']
@@ -47,7 +47,7 @@ vi.mock('../../codex/configuration/homes/codex-home-paths', () => ({
getLocalCodexTrustConfigFiles: mocks.codexConfigFiles
}))
vi.mock('../../qoder/workspace-trust', () => ({ markQoderWorkspaceTrusted: mocks.qoder }))
vi.mock('../../claude/claude-folder-trust-file', async (importOriginal) => {
vi.mock('../../claude/configuration/claude-folder-trust-file', async (importOriginal) => {
const actual = await importOriginal<typeof ClaudeFolderTrustFile>()
mocks.claudeGrant.mockImplementation(actual.grantClaudeWorkspaceTrust)
return { ...actual, grantClaudeWorkspaceTrust: mocks.claudeGrant }
@@ -4,7 +4,7 @@ import {
SHORT_AGENT_TRUST_WRITE_DEADLINE_MS
} from './agent-trust-write-deadline'
import type { AgentTrustPreset } from './agent-trust-presets'
import { resolveLocalClaudeTrustConfig } from '../../claude/claude-folder-trust-file'
import { resolveLocalClaudeTrustConfig } from '../../claude/configuration/claude-folder-trust-file'
import type { ClaudeRuntimeAuthPreparation } from '../../claude-accounts/runtime-auth/runtime-auth-types'
import type { AgentWorkspaceTrustSpawnRequest } from '../../../shared/agent-launch/permissions/agent-workspace-trust-spawn-request'
import { parseWslUncPath, toLinuxPath } from '../../../shared/wsl-paths'
@@ -14,7 +14,7 @@ import { awaitAgentTrustWriteWithinDeadline } from './agent-trust-write-deadline
import {
type ClaudeTrustConfigTarget,
grantClaudeWorkspaceTrust
} from '../../claude/claude-folder-trust-file'
} from '../../claude/configuration/claude-folder-trust-file'
import { isTooBroadToPreTrust } from '../../../shared/agent-launch/permissions/workspace-pretrust-scope'
/** Resolve trust on the agent’s execution host, including WSL guests and SSH relays. */
@@ -15,7 +15,7 @@ import {
import { claudeProfileMissing } from './claude-profile-launch-errors'
import type { GlobalSettings } from '../../../../shared/global-settings-types'
import type { ClaudeManagedAccount } from '../../../../shared/managed-account-types'
import { probeRecentClaudeCliVersion } from '../../../claude/claude-hook-event-versions'
import { probeRecentClaudeCliVersion } from '../../../claude/cli-capabilities/claude-hook-event-versions'
import { writeFileAtomically } from '../../../filesystem/atomic-file-publication'
import { resolveClaudeCommand } from '../../../codex-cli/command'
import {
@@ -1,5 +1,5 @@
import type { ClaudeProfileRouter, ClaudeProfileRouterSettings } from './claude-profile-router'
import { claudeLaunchDestinationHome } from '../../../claude/claude-launch-destination-home'
import { claudeLaunchDestinationHome } from '../../../claude/structured/launch/claude-launch-destination-home'
/** Every native switcher destination, even an account whose setup has not created its home. */
export async function claudeProfileSelectionHomes(
@@ -5,7 +5,7 @@ import { isDefinitiveAbsence } from '../../../../shared/definitive-filesystem-ab
import {
resolveClaudeGlobalConfigFile,
updateClaudeGlobalConfig
} from '../../../claude/claude-folder-trust-file'
} from '../../../claude/configuration/claude-folder-trust-file'
import { publishFileWithoutOverwrite } from '../../../filesystem/atomic-file-publication'
import { CLAUDE_PROFILE_HISTORY_DIRS, mergeClaudeProfileDirectory } from './claude-profile-history'
import { readClaudeProfileObject, resolveClaudeDefaultHome } from '../claude-profile-paths'
@@ -11,7 +11,7 @@ import { readFile, stat } from 'node:fs/promises'
import { homedir } from 'node:os'
import { dirname, join } from 'node:path'
import { z } from 'zod'
import { resolveClaudeGlobalConfigFile } from '../../claude/claude-folder-trust-file'
import { resolveClaudeGlobalConfigFile } from '../../claude/configuration/claude-folder-trust-file'
import { execSecurityCommand } from '../../macos-keychain/generic-password'
import { describeClaudeProfile, readClaudeProfileObject } from '../profiles/claude-profile-paths'
import { claudeConfigDirSpellings, claudeKeychainService } from '../runtime-auth/keychain'
@@ -1,15 +1,13 @@
import { classifyClaudeBackgroundTaskKind } from '../../shared/claude-background-task-kind'
import type {
AgentSessionBackgroundTask,
AgentSessionBackgroundTaskRunState
} from '../../shared/agent-session/agent-session-background-task-wire'
import { ownRetainedString } from '../../shared/own-retained-string'
} from '../../../shared/agent-session/agent-session-background-task-wire'
import { ownRetainedString } from '../../../shared/own-retained-string'
const MAX_TASK_ID_LENGTH = 512
const MAX_TASK_TEXT_LENGTH = 512
export type ClaudeBackgroundTaskKind = AgentSessionBackgroundTask['kind']
export { classifyClaudeBackgroundTaskKind }
export function record(value: unknown): Record<string, unknown> | null {
return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : null
@@ -1,8 +1,8 @@
import type { AgentJournalItemIdentity } from '../../shared/agent-session/journal/agent-session-journal-identity'
import { parseAgentJournalItemKey } from '../../shared/agent-session/journal/agent-session-journal-item-key'
import type { AgentJournalProducerLinkage } from '../../shared/agent-session/journal/agent-session-journal-types'
import { isBackgroundTaskBlock } from '../../shared/native-chat/native-chat-types'
import type { StructuredAgentSessionLifecycleJournal } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-journal-views'
import type { AgentJournalItemIdentity } from '../../../shared/agent-session/journal/agent-session-journal-identity'
import { parseAgentJournalItemKey } from '../../../shared/agent-session/journal/agent-session-journal-item-key'
import type { AgentJournalProducerLinkage } from '../../../shared/agent-session/journal/agent-session-journal-types'
import { isBackgroundTaskBlock } from '../../../shared/native-chat/native-chat-types'
import type { StructuredAgentSessionLifecycleJournal } from '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-journal-views'
export type ClaudeBackgroundTaskDescriptor = {
identity: AgentJournalItemIdentity
@@ -1,4 +1,4 @@
import { isSettledBackgroundTaskState } from '../../shared/native-chat/input/native-chat-background-task-row'
import { isSettledBackgroundTaskState } from '../../../shared/native-chat/input/native-chat-background-task-row'
import type { ClaudeBackgroundTaskRow } from './claude-background-task-row-lifecycle'
const MAX_GENERATION_ENTRIES = 512
@@ -1,12 +1,7 @@
import type { ClaudeTaskInvocations } from './claude-task-invocations'
import { isSettledBackgroundTaskState } from '../../shared/native-chat/input/native-chat-background-task-row'
import {
classifyClaudeBackgroundTaskKind,
record,
taskDescription,
taskId,
taskName
} from './claude-background-task-frames'
import { isSettledBackgroundTaskState } from '../../../shared/native-chat/input/native-chat-background-task-row'
import { classifyClaudeBackgroundTaskKind } from '../../../shared/claude-background-task-kind'
import { record, taskDescription, taskId, taskName } from './claude-background-task-frames'
import type {
ClaudeBackgroundTaskChange,
ClaudeBackgroundTaskRow
@@ -1,29 +1,23 @@
import type { AgentJournalItemIdentity } from '../../shared/agent-session/journal/agent-session-journal-identity'
import type { AgentJournalTurnScope } from '../../shared/agent-session/journal/agent-session-journal-turn-scope'
import { backgroundTaskJournalBody } from '../../shared/native-chat/input/native-chat-background-task-row'
import { isBackgroundTaskBlock } from '../../shared/native-chat/native-chat-types'
import type { AgentJournalItemIdentity } from '../../../shared/agent-session/journal/agent-session-journal-identity'
import type { AgentJournalTurnScope } from '../../../shared/agent-session/journal/agent-session-journal-turn-scope'
import { backgroundTaskJournalBody as claudeBackgroundTaskBody } from '../../../shared/native-chat/input/native-chat-background-task-row'
import { isBackgroundTaskBlock } from '../../../shared/native-chat/native-chat-types'
import type {
StructuredAgentSessionEventSink,
StructuredAgentSessionSinkAdmission
} from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink'
import type { StructuredAgentSessionLifecycleJournal } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-journal-views'
} from '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink'
import type { StructuredAgentSessionLifecycleJournal } from '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-journal-views'
import type { ClaudeBackgroundTaskRow } from './claude-background-task-row-lifecycle'
import { agentJournalItemKey } from '../../shared/agent-session/journal/agent-session-journal-item-key'
import { estimateStructuredAgentSessionItemBytes } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink-estimate'
import { agentJournalItemKey } from '../../../shared/agent-session/journal/agent-session-journal-item-key'
import { estimateStructuredAgentSessionItemBytes } from '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink-estimate'
import {
claudeBackgroundTaskIdentity,
resolveClaudeBackgroundTaskIdentity
} from './claude-background-task-identity'
export {
claudeBackgroundTaskIdentity,
resolveClaudeBackgroundTaskIdentity
} from './claude-background-task-identity'
const MAX_RESOLVED_TASK_IDENTITIES = 512
const ADMITTED: StructuredAgentSessionSinkAdmission = { accepted: true }
export const claudeBackgroundTaskBody = backgroundTaskJournalBody
export class ClaudeBackgroundTaskIdentityResolver {
private journal: StructuredAgentSessionLifecycleJournal | null = null
private epoch: string | null = null
@@ -1,13 +1,13 @@
import type { ClaudeTaskInvocation } from './claude-task-invocations'
import type { AgentJournalProducerLinkage } from '../../shared/agent-session/journal/agent-session-journal-types'
import type { AgentJournalProducerLinkage } from '../../../shared/agent-session/journal/agent-session-journal-types'
import {
canReplaceBackgroundTaskState,
isSettledBackgroundTaskState
} from '../../shared/native-chat/input/native-chat-background-task-row'
import type { NativeChatBackgroundTaskBlock } from '../../shared/native-chat/native-chat-types'
import type { ClaudeSubagentIds } from './claude-subagent-id-aliases'
} from '../../../shared/native-chat/input/native-chat-background-task-row'
import type { NativeChatBackgroundTaskBlock } from '../../../shared/native-chat/native-chat-types'
import type { ClaudeSubagentIds } from '../subagents/claude-subagent-id-aliases'
import { classifyClaudeBackgroundTaskKind } from '../../../shared/claude-background-task-kind'
import {
classifyClaudeBackgroundTaskKind,
liveClaudeTaskRunState,
record,
taskAliasId,
@@ -1,10 +1,10 @@
import { AGENT_JOURNAL_THREAD_SCOPE } from '../../shared/agent-session/journal/agent-session-journal-types'
import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session/journal/agent-session-journal-types'
import { vi } from 'vitest'
import type { AgentJournalItemBody } from '../../shared/agent-session/journal/agent-session-journal-types'
import type { AgentJournalItemIdentity } from '../../shared/agent-session/journal/agent-session-journal-identity'
import type { NativeChatBackgroundTaskBlock } from '../../shared/native-chat/native-chat-types'
import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink'
import type { AgentJournalItemBody } from '../../../shared/agent-session/journal/agent-session-journal-types'
import type { AgentJournalItemIdentity } from '../../../shared/agent-session/journal/agent-session-journal-identity'
import type { NativeChatBackgroundTaskBlock } from '../../../shared/native-chat/native-chat-types'
import type { StructuredAgentSessionEventSink } from '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink'
import { ClaudeBackgroundTaskRows } from './claude-background-task-rows'
/** Lifecycle frames captured from the reported failure. */
@@ -1,11 +1,11 @@
import { CLAUDE_BACKGROUND_TASK_SILENT_REFRESH_SUBTYPES } from './claude-background-task-frames'
import type { ClaudeTaskInvocations } from './claude-task-invocations'
import { claudeBackgroundTaskToolUseId } from './claude-background-task-row-lifecycle'
import type { AgentJournalTurnScope } from '../../shared/agent-session/journal/agent-session-journal-turn-scope'
import type { AgentJournalTurnScope } from '../../../shared/agent-session/journal/agent-session-journal-turn-scope'
import type {
StructuredAgentSessionEventSink,
StructuredAgentSessionSinkAdmission
} from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink'
} from '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink'
import type { ClaudeBackgroundTaskRow } from './claude-background-task-row-lifecycle'
import {
ClaudeBackgroundTaskIdentityResolver,
@@ -1,8 +1,8 @@
import { ClaudeTaskInvocations } from './claude-task-invocations'
import type { AgentJournalTurnScope } from '../../shared/agent-session/journal/agent-session-journal-turn-scope'
import { isSettledBackgroundTaskState } from '../../shared/native-chat/input/native-chat-background-task-row'
import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink'
import { BoundedMap } from '../../shared/bounded-map'
import type { AgentJournalTurnScope } from '../../../shared/agent-session/journal/agent-session-journal-turn-scope'
import { isSettledBackgroundTaskState } from '../../../shared/native-chat/input/native-chat-background-task-row'
import type { StructuredAgentSessionEventSink } from '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink'
import { BoundedMap } from '../../../shared/bounded-map'
import {
record,
taskAliasId,
@@ -31,7 +31,7 @@ import {
} from './claude-background-task-row-writer'
import { observeClaudeBackgroundTaskStart } from './claude-background-task-start'
import { observeOwnedClaudeBackgroundTaskRoster } from './claude-background-task-roster'
import { ClaudeSubagentIds } from './claude-subagent-id-aliases'
import { ClaudeSubagentIds } from '../subagents/claude-subagent-id-aliases'
import { ClaudeOverflowTerminalRows } from './claude-overflow-terminal-rows'
const MAX_TASK_ROWS = 64
@@ -1,5 +1,5 @@
import { isSettledBackgroundTaskState } from '../../shared/native-chat/input/native-chat-background-task-row'
import { classifyClaudeBackgroundTaskKind } from './claude-background-task-frames'
import { isSettledBackgroundTaskState } from '../../../shared/native-chat/input/native-chat-background-task-row'
import { classifyClaudeBackgroundTaskKind } from '../../../shared/claude-background-task-kind'
import {
claudeBackgroundTaskToolUseId,
isClaudeBackgroundTranscriptTask,
@@ -10,7 +10,7 @@ import {
ensureClaudeBackgroundTaskRowSlot,
type ClaudeBackgroundTaskLedgers
} from './claude-background-task-memory'
import { isClaudeSubagentTask } from './claude-subagent-task-frames'
import { isClaudeSubagentTask } from '../subagents/claude-subagent-task-frames'
type ClaudeBackgroundTaskStartInput = {
id: string
@@ -7,23 +7,6 @@ import {
} from './claude-background-task-row-test-support'
describe('claude background task terminal frames', () => {
it('reports a failure for a task it never saw admitted', () => {
const { rows, items, latest, latestTwin, turnOpens } = harness()
expect(rows.observe(ORPHAN_FAILED_NOTIFICATION)).toBe(true)
expect(items).toHaveLength(1)
expect(turnOpens).toHaveLength(1)
expect(latest()).toMatchObject({
type: 'background-task',
taskId: 'bjzenpq13',
kind: 'unknown',
state: 'blocked',
summary: 'Locate the exact screenshot session',
parentToolUseId: 'toolu_01ASNfnDBEzt4w3ejLE12bGu'
})
expect(latest()?.label).toBe('')
expect(latestTwin()).toBe('Locate the exact screenshot session')
})
it('does not resurrect an orphan outcome that named its own parent tool', () => {
const { rows, items, latest } = harness([
FORWARDED_TOOL,
@@ -2,9 +2,9 @@ import type {
AgentSessionBackgroundTask,
AgentSessionBackgroundTaskRunState,
AgentSessionBackgroundTaskState
} from '../../shared/agent-session/agent-session-background-task-wire'
} from '../../../shared/agent-session/agent-session-background-task-wire'
import { classifyClaudeBackgroundTaskKind } from '../../../shared/claude-background-task-kind'
import {
classifyClaudeBackgroundTaskKind,
liveClaudeTaskRunState,
record,
taskDescription,
@@ -21,14 +21,6 @@ import {
} from './claude-settled-background-tasks'
import { combineClaudeBackgroundTaskRoster } from './claude-background-task-roster-merge'
export {
classifyClaudeBackgroundTaskKind,
isBoundedClaudeTaskId,
taskDescription as claudeTaskDescription,
taskId as claudeTaskId
} from './claude-background-task-frames'
export type { ClaudeBackgroundTaskKind } from './claude-background-task-frames'
// Bound terminal IDs without evicting live tasks.
const MAX_TERMINAL_TASK_IDS = 256
export type ClaudeGoalBackgroundWork = 'live' | 'unverifiable' | 'exited'
@@ -3,7 +3,7 @@
import type {
AgentSessionBackgroundTask,
AgentSessionBackgroundTaskRunState
} from '../../shared/agent-session/agent-session-background-task-wire'
} from '../../../shared/agent-session/agent-session-background-task-wire'
const MAX_RETAINED_TASKS = 256
@@ -0,0 +1,42 @@
import type { ChildProcessWithoutNullStreams } from 'node:child_process'
import { describe, expect, it } from 'vitest'
import { spawnProcess } from '@orca/process-host'
import { proveClaudeChildExit } from './claude-agent-sdk-exit-proof'
import { managedChild } from './claude-child-exit-proof-fixture'
const COOPERATIVE_CHILD = `
process.stdin.on('end', () => process.exit(0))
process.stdin.resume()
process.stdout.write('ready\\n')
`
/** Sample at the close boundary; zombies count as exited even though kill(pid, 0) finds them. */
// ps start times have second precision; cross that boundary so the snapshot permits forced signals.
// Model registry retries: slow process-table reads may leave one close attempt unproven.
function spawnScript(script: string): ChildProcessWithoutNullStreams {
const child = spawnProcess({
program: process.execPath,
args: ['-e', script],
stdio: ['pipe', 'pipe', 'pipe']
})
managedChild(child)
return child
}
function firstStdoutLine(child: ChildProcessWithoutNullStreams): Promise<string> {
return new Promise((resolve) => {
child.stdout.setEncoding('utf8').once('data', (chunk: string) => resolve(chunk.trim()))
})
}
describe('claude child exit proof', () => {
it('proves a clean close of a childless root with one snapshot and no signal', async () => {
const child = spawnScript(COOPERATIVE_CHILD)
expect(await firstStdoutLine(child)).toBe('ready')
await expect(proveClaudeChildExit({ managed: managedChild(child) })).resolves.toBe(true)
}, 20_000)
})
@@ -2,15 +2,15 @@ import type { ChildProcess } from 'node:child_process'
import {
terminateDescendantSnapshotWithVerdict,
type DescendantTreeVerdict
} from '../pty/process-retirement/pty-descendant-exit-verification'
} from '../../pty/process-retirement/pty-descendant-exit-verification'
import {
captureDescendantSnapshot,
type DescendantSnapshot
} from '../pty/process-retirement/pty-descendant-termination'
import { terminateWindowsProcessTree } from '../pty/process-retirement/windows-process-tree-kill'
} from '../../pty/process-retirement/pty-descendant-termination'
import { terminateWindowsProcessTree } from '../../pty/process-retirement/windows-process-tree-kill'
import { mergeClaudeDescendantSnapshots } from './claude-child-tree-snapshot'
import { terminateClaudeRoot } from './claude-child-root-termination'
import { killProviderWriter } from '../provider-process/provider-process-teardown'
import { killProviderWriter } from '../../provider-process/provider-process-teardown'
import {
proveClaudeChildExitWithReaper,
type ClaudeChildExitProofInput
@@ -0,0 +1,72 @@
import { createFakePipedChild } from '../../../shared/__fixtures__/fake-spawned-child'
import { describe, expect, it, vi } from 'vitest'
import type { SpawnOptions as SdkSpawnOptions } from '@anthropic-ai/claude-agent-sdk'
import type { PipedProcessSpawner, ProcessSpec } from '@orca/process-host/process-spec'
import type * as ProviderSupervisor from '../../provider-process/provider-process-supervisor'
import { createClaudeCodeProcessSpawn } from './claude-agent-sdk-process-spawn'
vi.mock('../../provider-process/provider-process-supervisor', async (importOriginal) => {
const actual = await importOriginal<typeof ProviderSupervisor>()
return { ...actual, createProviderSpawnSpec: vi.fn(actual.createProviderSpawnSpec) }
})
function fakeSpawn() {
const child = createFakePipedChild()
const specs: ProcessSpec[] = []
const spawnImpl: PipedProcessSpawner = (spec) => {
specs.push(spec)
return child
}
return { child, spawnImpl, specs }
}
function sdkOptions(overrides: Partial<SdkSpawnOptions> = {}): SdkSpawnOptions {
return {
command: '/usr/local/bin/claude',
args: ['--output-format', 'stream-json'],
cwd: '/work/repo',
env: { PATH: '/usr/bin', CLAUDE_CONFIG_DIR: '/accounts/one', UNSET: undefined },
signal: new AbortController().signal,
...overrides
}
}
describe('claude agent SDK process spawn', () => {
it('keeps native chat identity after SDK and configured environment defaults', () => {
const process = fakeSpawn()
createClaudeCodeProcessSpawn(process.spawnImpl, 'win32').spawn(
sdkOptions({
env: {
CLAUDE_CODE_ENTRYPOINT: 'sdk-ts',
claude_code_entrypoint: 'account',
PATH: 'C:\\bin'
}
})
)
expect(process.specs[0]?.env).toMatchObject({ CLAUDE_CODE_ENTRYPOINT: 'orca', PATH: 'C:\\bin' })
expect(
Object.keys(process.specs[0]?.env ?? {}).filter(
(key) => key.toUpperCase() === 'CLAUDE_CODE_ENTRYPOINT'
)
).toEqual(['CLAUDE_CODE_ENTRYPOINT'])
})
it('preserves a Windows .cmd shim and its arguments for the host spawner', () => {
const process = fakeSpawn()
createClaudeCodeProcessSpawn(process.spawnImpl, 'win32').spawn(
sdkOptions({
command: 'C:\\Users\\dev\\AppData\\npm\\claude.cmd',
args: ['--setting-sources=user,project,local', '--session-id', 'a b&c']
})
)
expect(process.specs).toEqual([
expect.objectContaining({
program: 'C:\\Users\\dev\\AppData\\npm\\claude.cmd',
args: ['--setting-sources=user,project,local', '--session-id', 'a b&c']
})
])
})
})
@@ -1,4 +1,4 @@
import { withOrcaClaudeChatEntrypoint } from '../../shared/agent-launch/startup/claude-chat-entrypoint'
import { withOrcaClaudeChatEntrypoint } from '../../../shared/agent-launch/startup/claude-chat-entrypoint'
import type { ChildProcessWithoutNullStreams } from 'node:child_process'
import type { PipedProcessSpawner } from '@orca/process-host/process-spec'
import type { SpawnOptions as ClaudeAgentSdkSpawnOptions } from '@anthropic-ai/claude-agent-sdk'
@@ -6,7 +6,7 @@ import { spawnProcess } from '@orca/process-host'
import {
spawnManagedProviderProcess,
type ManagedProviderProcess
} from '../provider-process/managed-provider-process'
} from '../../provider-process/managed-provider-process'
import { claudeChildClosePolicy, claudeChildCloseProven } from './claude-child-exit-proof-ladder'
export type ClaudeCodeProcessSpawn = {
@@ -2,7 +2,7 @@ import type { ChildProcessWithoutNullStreams } from 'node:child_process'
import {
spawnManagedProviderProcess,
type ManagedProviderProcess
} from '../provider-process/managed-provider-process'
} from '../../provider-process/managed-provider-process'
import { claudeChildClosePolicy, claudeChildCloseProven } from './claude-child-exit-proof-ladder'
const managedChildren = new WeakMap<object, ManagedProviderProcess>()
@@ -1,9 +1,9 @@
import type { ManagedProviderProcess } from '../provider-process/managed-provider-process'
import { PROVIDER_SUPERVISOR_MAX_STOP_MS } from '../provider-process/provider-process-supervisor'
import type { ManagedProviderProcess } from '../../provider-process/managed-provider-process'
import { PROVIDER_SUPERVISOR_MAX_STOP_MS } from '../../provider-process/provider-process-supervisor'
import type {
ProviderProcessClosePolicy,
ProviderProcessCloseResult
} from '../provider-process/provider-process-close'
} from '../../provider-process/provider-process-close'
import type { ClaudeChildTreeReaper } from './claude-agent-sdk-exit-proof'
export const GRACEFUL_EXIT_MS = 1_500
@@ -1,12 +1,12 @@
import {
CLAUDE_AUTH_ENV_VARS,
applyClaudeEnvPatch
} from '../claude-accounts/runtime-auth/environment'
import { stripInheritedAgentSessionEnv } from '../../shared/agent-launch/startup/parent-agent-session-env'
} from '../../claude-accounts/runtime-auth/environment'
import { stripInheritedAgentSessionEnv } from '../../../shared/agent-launch/startup/parent-agent-session-env'
import {
LEGACY_NATIVE_CHAT_VISUALS_DIR_ENV,
NATIVE_CHAT_SCRATCH_DIR_ENV
} from '../native-chat/native-chat-visuals-delivery'
} from '../../native-chat/native-chat-visuals-delivery'
function cloneProcessEnv(source: NodeJS.ProcessEnv): Record<string, string> {
const env: Record<string, string> = {}
@@ -1,4 +1,4 @@
import type { DescendantSnapshot } from '../pty/process-retirement/pty-descendant-termination'
import type { DescendantSnapshot } from '../../pty/process-retirement/pty-descendant-termination'
// Non-atomic scans may omit live rows; retain them, but reject any PID whose identity changed.
function mergeRowsByPid<Row extends { pid: number }>(
@@ -1,5 +1,5 @@
import { StringDecoder } from 'node:string_decoder'
import { createIncrementalNdjsonFramer } from '../../shared/main-process-ndjson-framer'
import { createIncrementalNdjsonFramer } from '../../../shared/main-process-ndjson-framer'
// Unescaped quotes occur only as JSON structure, so other records skip this second parse.
const FAILED_RESULT_TOKENS = [/"type"\s*:\s*"result"/, /"is_error"\s*:\s*true/]
@@ -1,10 +1,10 @@
import { BoundedMap } from '../../shared/bounded-map'
import { runsOrcaOrchestrationWait } from '../../shared/orca-cli-invocations'
import { BoundedMap } from '../../../shared/bounded-map'
import { runsOrcaOrchestrationWait } from '../../../shared/orca-cli-invocations'
import {
claudeRecord,
claudeToolUses,
readClaudeMessageEnvelope
} from './structured/journal/claude-structured-item-translation'
} from '../structured/journal/claude-structured-item-translation'
/** Bash calls that block on `orca orchestration check --wait`, by tool_use_id, until their background task starts. */
export class ClaudeAgentWaitCalls {
@@ -1,9 +1,9 @@
// Roster changes, turn endings and spawn results cannot settle a child.
import { ClaudeTaskInvocations } from './claude-task-invocations'
import type { AgentChildWorkEvidence } from '../../shared/agent-status/child-work/agent-status-child-work-evidence'
import { ClaudeTaskInvocations } from '../background-tasks/claude-task-invocations'
import type { AgentChildWorkEvidence } from '../../../shared/agent-status/child-work/agent-status-child-work-evidence'
import { classifyClaudeBackgroundTaskKind } from '../../../shared/claude-background-task-kind'
import {
classifyClaudeBackgroundTaskKind,
liveClaudeTaskRunState,
record,
taskAliasId,
@@ -13,8 +13,8 @@ import {
taskText,
taskUsageTotalTokens,
terminalClaudeTaskRunState
} from './claude-background-task-frames'
import { claudeStartedTaskKind } from './claude-subagent-task-frames'
} from '../background-tasks/claude-background-task-frames'
import { claudeStartedTaskKind } from '../subagents/claude-subagent-task-frames'
import { ClaudeAgentWaitCalls } from './claude-agent-wait-calls'
import {
claudeChildWorkOutcome,
@@ -1,26 +1,24 @@
import { ORCA_ORCHESTRATION_WAIT_COMMAND } from '../../shared/orca-cli-invocations'
import { ORCA_ORCHESTRATION_WAIT_COMMAND } from '../../../shared/orca-cli-invocations'
import type {
AgentChildWorkKind,
AgentChildWorkOperation,
AgentChildWorkOutcome
} from '../../shared/agent-status/child-work/agent-status-child-work'
} from '../../../shared/agent-status/child-work/agent-status-child-work'
import type {
AgentChildWorkEvidence,
AgentChildWorkLiveObservation
} from '../../shared/agent-status/child-work/agent-status-child-work-evidence'
import { taskText, taskUsageTotalTokens } from './claude-background-task-frames'
import type {
ClaudeSession,
ClaudeStructuredSessionEvent
} from './structured/claude-structured-session-state'
import { deriveToolInputPreview } from '../../shared/agent-hook-listener/tool-input-preview'
} from '../../../shared/agent-status/child-work/agent-status-child-work-evidence'
import { taskText, taskUsageTotalTokens } from '../background-tasks/claude-background-task-frames'
import type { ClaudeSession } from '../structured/claude-structured-session-state'
import type { ClaudeStructuredSessionEvent } from '../structured/claude-structured-session-event'
import { deriveToolInputPreview } from '../../../shared/agent-hook-listener/tool-input-preview'
import {
claudeRecord,
claudeToolResultId,
claudeToolUses,
readClaudeMessageEnvelope,
type ClaudeToolUse
} from './structured/journal/claude-structured-item-translation'
} from '../structured/journal/claude-structured-item-translation'
export type EndedClaudeTask = {
run: string | undefined
@@ -1,317 +0,0 @@
import { createClaudeCodeProcessSpawn } from './claude-agent-sdk-process-spawn'
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import {
query,
type CanUseTool,
type Options,
type SDKUserMessage,
type SpawnedProcess as SdkSpawnedProcess,
type SpawnOptions as SdkSpawnOptions
} from '@anthropic-ai/claude-agent-sdk'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { spawnProcess } from '@orca/process-host'
import { ClaudePromptRegistry } from './claude-prompt-registry'
import { claudeLaunchPermissions } from './structured/claude-structured-inbound-control'
import { claudeStructuredPermissionOptions } from './structured/launch/claude-structured-launch-resolution'
// Exercise the real SDK against a scripted CLI to detect protocol and spawn-contract drift.
const FAKE_CLI = join(__dirname, '__fixtures__', 'claude-agent-sdk-scripted-cli.mjs')
const SESSION_ID = '5348c19f-6a54-4c2e-9c68-9c2b1a3d4e5f'
const RESULT_FRAME = {
type: 'result',
subtype: 'success',
is_error: false,
duration_ms: 1,
duration_api_ms: 1,
num_turns: 1,
result: 'ok',
session_id: SESSION_ID,
total_cost_usd: 0,
usage: { input_tokens: 1, output_tokens: 1 },
uuid: 'uuid-result-1'
}
type ScenarioStep = Record<string, unknown>
type SpawnSeen = {
command: string
args: string[]
cwd: string | undefined
env: Record<string, string | undefined>
}
type ScriptedCliReport = {
argv: string[]
execPath: string
controlRequests: { request_id: string; request: { subtype: string } }[]
controlResponses: { response: { request_id: string; response?: Record<string, unknown> } }[]
userMessages: Record<string, unknown>[]
}
const scratchDirs: string[] = []
afterEach(() => {
vi.unstubAllEnvs()
for (const dir of scratchDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true })
}
})
function scriptScenario(
steps: ScenarioStep[],
controlResponses: Record<string, unknown> = {},
extra: Record<string, unknown> = {}
): {
scenarioPath: string
reportPath: string
cwd: string
readReport: () => ScriptedCliReport
} {
const dir = mkdtempSync(join(tmpdir(), 'claude-sdk-contract-'))
scratchDirs.push(dir)
const scenarioPath = join(dir, 'scenario.json')
const reportPath = join(dir, 'report.json')
writeFileSync(scenarioPath, JSON.stringify({ steps, controlResponses, ...extra }))
return {
scenarioPath,
reportPath,
cwd: dir,
readReport: () => JSON.parse(readFileSync(reportPath, 'utf8')) as ScriptedCliReport
}
}
function scenarioEnv(scenario: { scenarioPath: string; reportPath: string }) {
return {
PATH: process.env.PATH,
ORCA_SDK_CONTRACT_SCENARIO_PATH: scenario.scenarioPath,
ORCA_SDK_CONTRACT_REPORT_PATH: scenario.reportPath
}
}
function recordingSpawner(spawns: SpawnSeen[]) {
return (opts: SdkSpawnOptions): SdkSpawnedProcess => {
spawns.push({
command: opts.command,
args: [...opts.args],
cwd: opts.cwd,
env: { ...opts.env }
})
return spawnProcess({
program: opts.command,
args: opts.args,
cwd: opts.cwd,
env: opts.env as NodeJS.ProcessEnv,
signal: opts.signal
}) as unknown as SdkSpawnedProcess
}
}
function singleUserTurn(): AsyncIterable<SDKUserMessage> {
return (async function* () {
yield {
type: 'user',
message: { role: 'user', content: [{ type: 'text', text: 'hello' }] },
parent_tool_use_id: null,
session_id: SESSION_ID
} as SDKUserMessage
// Keep input open until the scripted CLI exits; an unresolved promise does not keep Node alive.
await new Promise<void>(() => {})
})()
}
async function drainQuery(options: Options): Promise<Record<string, unknown>[]> {
const messages: Record<string, unknown>[] = []
for await (const message of query({ prompt: singleUserTurn(), options })) {
messages.push(message as unknown as Record<string, unknown>)
}
return messages
}
describe('Claude Agent SDK contract pins', () => {
it('gives canUseTool the wire request_id and fires its abort signal on control_cancel_request', async () => {
const scenario = scriptScenario([
{ awaitUserMessage: true },
{
emit: {
type: 'control_request',
request_id: 'perm-421',
request: {
subtype: 'can_use_tool',
tool_name: 'Bash',
input: { command: 'echo hi' },
tool_use_id: 'tool-use-9'
}
}
},
{ delayMs: 120 },
{ emit: { type: 'control_cancel_request', request_id: 'perm-421' } },
{ awaitControlResponse: 'perm-421' },
{ emit: RESULT_FRAME }
])
const seen: { toolName: string; requestId: string; toolUseID: string }[] = []
let abortFired = false
const canUseTool: CanUseTool = (toolName, _input, { signal, requestId, toolUseID }) => {
seen.push({ toolName, requestId, toolUseID })
return new Promise((resolve) => {
signal.addEventListener('abort', () => {
abortFired = true
resolve({ behavior: 'deny', message: 'cancelled by test' })
})
})
}
const spawns: SpawnSeen[] = []
await drainQuery({
pathToClaudeCodeExecutable: FAKE_CLI,
cwd: scenario.cwd,
env: scenarioEnv(scenario),
canUseTool,
spawnClaudeCodeProcess: recordingSpawner(spawns)
})
expect(seen).toEqual([{ toolName: 'Bash', requestId: 'perm-421', toolUseID: 'tool-use-9' }])
expect(abortFired).toBe(true)
const settled = scenario
.readReport()
.controlResponses.find((frame) => frame.response.request_id === 'perm-421')
expect(settled?.response.response?.behavior).toBe('deny')
expect(spawns).toHaveLength(1)
})
describe("Full access decisions keep each request's place in one stdout chunk", () => {
const status = (permissionMode: string) => ({
type: 'system',
subtype: 'status',
status: null,
permissionMode,
session_id: SESSION_ID
})
const ask = (id: string, extra: Record<string, unknown> = {}) => ({
type: 'control_request',
request_id: id,
request: {
subtype: 'can_use_tool',
tool_name: 'Bash',
input: { command: 'echo harmless' },
tool_use_id: `tool-${id}`,
...extra
}
})
const cancel = (id: string) => ({ type: 'control_cancel_request', request_id: id })
type WireFrame = ReturnType<typeof status> | ReturnType<typeof ask> | ReturnType<typeof cancel>
const isAsk = (frame: WireFrame): frame is ReturnType<typeof ask> => 'request' in frame
const many = (prefix: string) =>
Array.from({ length: 300 }, (_, index) => ask(`${prefix}${index}`))
const asked = (ids: string[], allowed: boolean) =>
ids.map((requestId) => ({ requestId, allowed }))
const manyIds = (prefix: string) => many(prefix).map((frame) => frame.request_id)
it.each([
{
label: 'plan, then bypass, with the interaction flag',
frames: [
status('plan'),
ask('A'),
status('bypassPermissions'),
ask('B'),
ask('flagged', { tool_name: 'mcp__forms__confirm', requires_user_interaction: true })
],
seen: [...asked(['A'], false), ...asked(['B'], true), ...asked(['flagged'], false)],
interaction: [true],
pending: []
},
{
label: 'a request initialize resends, then plan',
frames: [status('plan'), ask('A')],
seen: [...asked(['resent'], true), ...asked(['A'], false)],
interaction: [],
pending: [ask('resent')]
},
{
label: 'a cancel in the same chunk',
frames: [status('plan'), ask('A'), cancel('A'), status('bypassPermissions'), ask('B')],
seen: [...asked(['A'], false), ...asked(['B'], true)],
interaction: [],
pending: []
},
{
label: 'a duplicate id after bypass',
frames: [status('plan'), ask('A'), status('bypassPermissions'), ask('A'), ask('B')],
seen: [...asked(['A', 'A'], false), ...asked(['B'], true)],
interaction: [],
pending: []
},
{
label: 'more than 256 unread requests in plan',
frames: [status('plan'), ...many('p'), status('bypassPermissions'), ask('B')],
seen: [...asked(manyIds('p'), false), ...asked(['B'], true)],
interaction: [],
pending: []
},
{
label: 'more than 256 unread requests in Full access',
frames: [status('bypassPermissions'), ...many('f'), status('plan'), ask('C')],
seen: [...asked(manyIds('f'), true), ...asked(['C'], false)],
interaction: [],
pending: []
}
])('$label', async ({ frames, seen: expected, interaction: flags, pending }) => {
const requestIds = [
...new Set([...pending, ...frames].filter(isAsk).map((frame) => frame.request_id))
]
const scenario = scriptScenario(
[
{ awaitUserMessage: true },
{ emitTogether: frames },
...requestIds.map((id) => ({ awaitControlResponse: id })),
{ emit: RESULT_FRAME }
],
{},
{ pendingPermissionRequests: { initialize: pending } }
)
const prompts = new ClaudePromptRegistry()
const permissions = claudeLaunchPermissions(
{ sessionId: 'session-1', prompts, emit: () => {} },
{
providerSessionId: SESSION_ID,
options: claudeStructuredPermissionOptions('full-access')
}
)
const seen: { requestId: string; allowed: boolean }[] = []
const interaction: unknown[] = []
const canUseTool: CanUseTool = async (toolName, input, options) => {
if ('requiresUserInteraction' in options) {
interaction.push(options.requiresUserInteraction)
}
const answer = permissions.handlers.canUseTool!(toolName, input, options)
// Answer any card at once so the scripted turn can finish.
prompts.find(options.requestId)?.prompt.settle({
behavior: 'deny',
message: 'asked',
toolUseID: options.toolUseID
})
const decision = { requestId: options.requestId, allowed: false }
seen.push(decision)
const result = await answer
decision.allowed = result?.behavior === 'allow'
return result ?? { behavior: 'deny', message: 'cancelled', toolUseID: options.toolUseID }
}
const spawner = createClaudeCodeProcessSpawn(
spawnProcess,
process.platform,
{ pathToClaudeCodeExecutable: FAKE_CLI },
permissions.handlers.onStdout
)
await drainQuery({
pathToClaudeCodeExecutable: FAKE_CLI,
cwd: scenario.cwd,
env: scenarioEnv(scenario),
canUseTool,
spawnClaudeCodeProcess: spawner.spawn
})
expect(seen).toEqual(expected)
expect(interaction).toEqual(flags)
})
})
})
@@ -1,31 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import { collectDescendantRows } from '../pty/process-retirement/pty-descendant-termination'
import { createClaudeChildTreeReaper } from './claude-agent-sdk-exit-proof'
describe('Claude child root identity', () => {
it('rejects mixed old and recycled root rows instead of making the tree killable', async () => {
const child = { pid: 100, kill: vi.fn(() => true) }
const terminateDescendants = vi.fn(async () => 'exited' as const)
const tree = createClaudeChildTreeReaper(child, {
site: 'claude-structured-child-close',
platform: 'linux',
captureDescendants: vi.fn(async () =>
collectDescendantRows(
100,
[
{ pid: 100, ppid: 1, pgid: 100, startedAt: 'Mon Jan 1 00:00:00 2026' },
{ pid: 100, ppid: 1, pgid: 101, startedAt: 'Mon Jan 1 00:00:01 2026' },
{ pid: 200, ppid: 100, pgid: 200, startedAt: 'Mon Jan 1 00:00:00 2026' }
],
1
)
),
terminateDescendants
})
await expect(tree.reap()).resolves.toBe('unverifiable')
expect(terminateDescendants).not.toHaveBeenCalled()
expect(child.kill).toHaveBeenCalledWith('SIGKILL')
})
})
@@ -1,181 +0,0 @@
import { execFileSync, type ChildProcessWithoutNullStreams } from 'node:child_process'
import { describe, expect, it } from 'vitest'
import { spawnProcess } from '@orca/process-host'
import { proveClaudeChildExit } from './claude-agent-sdk-exit-proof'
import { managedChild } from './claude-child-exit-proof-fixture'
function childWithDescendantScript(input: {
rootTrapsSigterm: boolean
descendantTrapsSigterm: boolean
}): string {
const descendantScript = `${input.descendantTrapsSigterm ? 'process.on("SIGTERM", () => {}); ' : ''}setInterval(() => {}, 1000000)`
const rootBehaviour = input.rootTrapsSigterm
? `process.on('SIGTERM', () => {})
process.on('SIGINT', () => {})
setInterval(() => {}, 1000000)`
: `process.stdin.on('end', () => process.exit(0))
process.stdin.resume()`
return `
const descendant = require('node:child_process').spawn(
process.execPath,
['-e', ${JSON.stringify(descendantScript)}],
{ stdio: 'ignore' }
)
descendant.unref()
process.stdout.write(JSON.stringify({ descendantPid: descendant.pid }) + '\\n')
${rootBehaviour}
`
}
const COOPERATIVE_CHILD = `
process.stdin.on('end', () => process.exit(0))
process.stdin.resume()
process.stdout.write('ready\\n')
`
/** Sample at the close boundary; zombies count as exited even though kill(pid, 0) finds them. */
function descendantState(pid: number): 'running' | 'exited' {
let state: string
try {
state = execFileSync('ps', ['-o', 'state=', '-p', String(pid)], {
encoding: 'utf8',
env: { ...process.env, LANG: 'C', LC_ALL: 'C' }
}).trim()
} catch (error) {
// ps exits 1 when no process matches; anything else is a failed probe, not an answer.
if ((error as { status?: number }).status !== 1) {
throw error
}
return 'exited'
}
return state.startsWith('Z') ? 'exited' : 'running'
}
// ps start times have second precision; cross that boundary so the snapshot permits forced signals.
function ageDescendantPastTheCaptureSecond(): Promise<void> {
// ast-grep-ignore: test-no-wall-clock -- ps reports native process birth times on this clock.
return new Promise((resolve) => setTimeout(resolve, 1_000 - (Date.now() % 1_000) + 20))
}
// Model registry retries: slow process-table reads may leave one close attempt unproven.
async function proveExitWithRetries(
input: Parameters<typeof proveClaudeChildExit>[0],
attempts = 3
): Promise<boolean> {
for (let attempt = 1; attempt < attempts; attempt += 1) {
if (await proveClaudeChildExit(input)) {
return true
}
}
return proveClaudeChildExit(input)
}
function spawnScript(script: string): ChildProcessWithoutNullStreams {
const child = spawnProcess({
program: process.execPath,
args: ['-e', script],
stdio: ['pipe', 'pipe', 'pipe']
})
managedChild(child)
return child
}
function firstStdoutLine(child: ChildProcessWithoutNullStreams): Promise<string> {
return new Promise((resolve) => {
child.stdout.setEncoding('utf8').once('data', (chunk: string) => resolve(chunk.trim()))
})
}
describe('claude child exit proof', () => {
it.runIf(process.platform !== 'win32')(
'reports a proven exit only once a SIGTERM-resistant descendant is gone at the close boundary',
async () => {
const child = spawnScript(
childWithDescendantScript({ rootTrapsSigterm: true, descendantTrapsSigterm: true })
)
const { descendantPid } = JSON.parse(await firstStdoutLine(child)) as {
descendantPid: number
}
expect(descendantState(descendantPid)).toBe('running')
await ageDescendantPastTheCaptureSecond()
try {
const proven = await proveExitWithRetries({ managed: managedChild(child) })
// Assert at lease release; polling afterward could conceal a surviving descendant.
expect({ proven, descendant: descendantState(descendantPid) }).toEqual({
proven: true,
descendant: 'exited'
})
} finally {
try {
process.kill(descendantPid, 'SIGKILL')
} catch {
// Already gone.
}
}
},
20_000
)
it.runIf(process.platform !== 'win32')(
'proves a promptly exiting root only once its stubborn descendant is gone too',
async () => {
const child = spawnScript(
childWithDescendantScript({ rootTrapsSigterm: false, descendantTrapsSigterm: true })
)
const { descendantPid } = JSON.parse(await firstStdoutLine(child)) as {
descendantPid: number
}
expect(descendantState(descendantPid)).toBe('running')
await ageDescendantPastTheCaptureSecond()
try {
const proven = await proveExitWithRetries({ managed: managedChild(child) })
expect({ proven, descendant: descendantState(descendantPid) }).toEqual({
proven: true,
descendant: 'exited'
})
} finally {
try {
process.kill(descendantPid, 'SIGKILL')
} catch {
// Already gone.
}
}
},
20_000
)
it.runIf(process.platform !== 'win32')(
'still proves a stubborn child whose descendant honours SIGTERM',
async () => {
const child = spawnScript(
childWithDescendantScript({ rootTrapsSigterm: true, descendantTrapsSigterm: false })
)
const { descendantPid } = JSON.parse(await firstStdoutLine(child)) as {
descendantPid: number
}
try {
const proven = await proveExitWithRetries({ managed: managedChild(child) })
expect({ proven, descendant: descendantState(descendantPid) }).toEqual({
proven: true,
descendant: 'exited'
})
} finally {
try {
process.kill(descendantPid, 'SIGKILL')
} catch {
// Already gone.
}
}
},
20_000
)
it('proves a clean close of a childless root with one snapshot and no signal', async () => {
const child = spawnScript(COOPERATIVE_CHILD)
expect(await firstStdoutLine(child)).toBe('ready')
await expect(proveClaudeChildExit({ managed: managedChild(child) })).resolves.toBe(true)
}, 20_000)
})
@@ -1,128 +0,0 @@
import { createFakePipedChild } from '../../shared/__fixtures__/fake-spawned-child'
import { describe, expect, it, vi } from 'vitest'
import type { SpawnOptions as SdkSpawnOptions } from '@anthropic-ai/claude-agent-sdk'
import type { PipedProcessSpawner, ProcessSpec } from '@orca/process-host/process-spec'
import type * as ProviderSupervisor from '../provider-process/provider-process-supervisor'
import { createProviderSpawnSpec } from '../provider-process/provider-process-supervisor'
import { createClaudeCodeProcessSpawn } from './claude-agent-sdk-process-spawn'
import { proveClaudeChildExitWithReaper } from './claude-child-exit-proof-ladder'
vi.mock('../provider-process/provider-process-supervisor', async (importOriginal) => {
const actual = await importOriginal<typeof ProviderSupervisor>()
return { ...actual, createProviderSpawnSpec: vi.fn(actual.createProviderSpawnSpec) }
})
function fakeSpawn() {
const child = createFakePipedChild()
const specs: ProcessSpec[] = []
const spawnImpl: PipedProcessSpawner = (spec) => {
specs.push(spec)
return child
}
return { child, spawnImpl, specs }
}
function sdkOptions(overrides: Partial<SdkSpawnOptions> = {}): SdkSpawnOptions {
return {
command: '/usr/local/bin/claude',
args: ['--output-format', 'stream-json'],
cwd: '/work/repo',
env: { PATH: '/usr/bin', CLAUDE_CONFIG_DIR: '/accounts/one', UNSET: undefined },
signal: new AbortController().signal,
...overrides
}
}
describe('claude agent SDK process spawn', () => {
it.each([
{ platform: 'darwin', specSupervised: false },
{ platform: 'win32', specSupervised: true }
] as const)(
'stops Claude by the spawn spec\u2019s supervision on $platform, never the platform',
async ({ platform, specSupervised }) => {
const actual = await vi.importActual<typeof ProviderSupervisor>(
'../provider-process/provider-process-supervisor'
)
vi.mocked(createProviderSpawnSpec).mockImplementationOnce((...args) => ({
...actual.createProviderSpawnSpec(...args),
supervised: specSupervised
}))
const process = fakeSpawn()
const spawn = createClaudeCodeProcessSpawn(process.spawnImpl, platform)
spawn.spawn(sdkOptions())
expect(spawn.supervised).toBe(specSupervised)
const managed = spawn.managed
if (!managed) {
throw new Error('Claude spawner did not retain its managed child')
}
process.child.stdin.on('finish', () =>
setTimeout(() => process.child.emit('exit', 0, null), 10)
)
const tree = {
capture: vi.fn(async () => {}),
reap: vi.fn(async () => 'exited' as const),
treeVerdict: 'exited' as const,
forcedReapAttempted: false
}
await expect(proveClaudeChildExitWithReaper({ managed, tree }, () => tree)).resolves.toBe(
true
)
if (specSupervised) {
expect(process.child.kill).toHaveBeenCalledWith('SIGTERM')
} else {
expect(process.child.kill).not.toHaveBeenCalled()
}
}
)
it('drains stderr into a bounded tail so an exit error still carries it', async () => {
const process = fakeSpawn()
const spawn = createClaudeCodeProcessSpawn(process.spawnImpl)
spawn.spawn(sdkOptions())
process.child.stderr.write('x'.repeat(9000))
process.child.stderr.write('claude: not signed in')
await new Promise((resolve) => setImmediate(resolve))
expect(spawn.managed?.stderrTail()).toMatch(/claude: not signed in$/)
expect(spawn.managed?.stderrTail().length).toBe(8192)
})
it('keeps native chat identity after SDK and configured environment defaults', () => {
const process = fakeSpawn()
createClaudeCodeProcessSpawn(process.spawnImpl, 'win32').spawn(
sdkOptions({
env: {
CLAUDE_CODE_ENTRYPOINT: 'sdk-ts',
claude_code_entrypoint: 'account',
PATH: 'C:\\bin'
}
})
)
expect(process.specs[0]?.env).toMatchObject({ CLAUDE_CODE_ENTRYPOINT: 'orca', PATH: 'C:\\bin' })
expect(
Object.keys(process.specs[0]?.env ?? {}).filter(
(key) => key.toUpperCase() === 'CLAUDE_CODE_ENTRYPOINT'
)
).toEqual(['CLAUDE_CODE_ENTRYPOINT'])
})
it('preserves a Windows .cmd shim and its arguments for the host spawner', () => {
const process = fakeSpawn()
createClaudeCodeProcessSpawn(process.spawnImpl, 'win32').spawn(
sdkOptions({
command: 'C:\\Users\\dev\\AppData\\npm\\claude.cmd',
args: ['--setting-sources=user,project,local', '--session-id', 'a b&c']
})
)
expect(process.specs).toEqual([
expect.objectContaining({
program: 'C:\\Users\\dev\\AppData\\npm\\claude.cmd',
args: ['--setting-sources=user,project,local', '--session-id', 'a b&c']
})
])
})
})
@@ -1,65 +0,0 @@
import type { SDKUserMessage } from '@anthropic-ai/claude-agent-sdk'
import { describe, expect, it } from 'vitest'
import {
claudeUserMessageWasProvablyUnwritten,
createClaudeUserMessageQueue
} from './claude-agent-sdk-user-message-queue'
// Model the SDK pump: it resumes only after transport.write and abandons the iterator on failure.
const frame = (text: string): SDKUserMessage =>
({
type: 'user',
message: { role: 'user', content: [{ type: 'text', text }] }
}) as unknown as SDKUserMessage
const settled = (promise: Promise<void>): Promise<'settled' | 'pending'> =>
Promise.race([
promise.then(
() => 'settled' as const,
() => 'settled' as const
),
new Promise<'pending'>((resolve) => setTimeout(() => resolve('pending'), 100))
])
describe('claude user message queue', () => {
it('treats a frame the SDK pulled and abandoned as write-outcome unknown', async () => {
const queue = createClaudeUserMessageQueue()
const pump = queue.messages[Symbol.asyncIterator]()
const sent = queue.push(frame('hello'))
await pump.next()
await pump.return?.(undefined)
await expect(settled(sent)).resolves.toBe('settled')
const error = await sent.catch((caught: unknown) => caught)
expect(error).toMatchObject({
message: 'claude stream-json input ended before confirming the frame write'
})
expect(claudeUserMessageWasProvablyUnwritten(error)).toBe(false)
})
it('marks only frames still queued in Orca as provably unwritten', async () => {
const queue = createClaudeUserMessageQueue()
const pump = queue.messages[Symbol.asyncIterator]()
const inFlight = queue.push(frame('first')).catch((caught: unknown) => caught)
await pump.next()
const queued = queue.push(frame('second')).catch((caught: unknown) => caught)
queue.fail(new Error('claude stream-json exited: child died'))
expect(claudeUserMessageWasProvablyUnwritten(await inFlight)).toBe(false)
expect(claudeUserMessageWasProvablyUnwritten(await queued)).toBe(true)
})
it('still settles a written frame only once the pump asks for the next one', async () => {
const queue = createClaudeUserMessageQueue()
const pump = queue.messages[Symbol.asyncIterator]()
const sent = queue.push(frame('hello'))
const pulled = await pump.next()
expect(pulled.value).toMatchObject({ type: 'user' })
await expect(settled(sent)).resolves.toBe('pending')
void pump.next()
await expect(sent).resolves.toBeUndefined()
})
})
@@ -1,102 +0,0 @@
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { AgentJournalItemBody } from '../../shared/agent-session/journal/agent-session-journal-types'
import type { AgentSessionJournalIdentity } from '../../shared/agent-session/journal/agent-session-journal-identity'
import { openAgentSessionJournal } from '../native-chat/agent-session-journal/journal-store-factory'
import { createDeferredStructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink'
import { createClaudeJournalTranslator } from './structured/journal/claude-structured-journal-translation'
import {
closeTestJournalHostDatabases,
openTestJournalHostDatabase
} from '../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support'
import { testEventSinkLogging } from '../native-chat/agent-session-wire/host/testing/structured-agent-session-logger-test-support'
import { claudeProviderHandle } from '../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding'
const IDENTITY: AgentSessionJournalIdentity = {
sessionId: 'session-1',
workspaceId: 'workspace-1',
hostId: 'host-1',
agent: 'claude',
providerHandle: claudeProviderHandle('provider-1', 'leaf-1')
}
function apiRetry(attempt: number, fields: Record<string, unknown> = {}): Record<string, unknown> {
return {
type: 'system',
subtype: 'api_retry',
attempt,
max_retries: 10,
retry_delay_ms: 622,
error_status: 429,
error: 'rate_limit',
session_id: 'provider-1',
uuid: `9b2f6a1e-0c4d-4e7a-8f3b-00000000000${attempt}`,
...fields
}
}
let root = ''
beforeEach(async () => {
root = await mkdtemp(join(tmpdir(), 'orca-claude-api-retry-'))
})
afterEach(async () => {
await closeTestJournalHostDatabases()
await rm(root, { recursive: true, force: true })
})
async function statusRowsFor(frames: Record<string, unknown>[]) {
const journal = await openAgentSessionJournal({
identity: IDENTITY,
database: openTestJournalHostDatabase(root),
now: () => 1_700_000_000_000,
mintEpoch: () => 'epoch-1'
})
const deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging())
deferred.bind({ journal, fence: 1, publish: vi.fn() })
const translator = createClaudeJournalTranslator({ sink: deferred.sink, fallbackIdPrefix: '1' })
for (const frame of frames) {
translator.handle({ type: 'message', sessionId: 'orca-session', message: frame })
await deferred.drained()
}
return journal
.snapshot()
.items.flatMap((item): Extract<AgentJournalItemBody, { kind: 'status' }>[] =>
item.body.kind === 'status' ? [item.body] : []
)
}
describe('a Claude api_retry frame', () => {
it('writes one sentence row per retry run, revised by each attempt, not the frame', async () => {
const rows = await statusRowsFor([apiRetry(1), apiRetry(2), apiRetry(3)])
expect(rows).toHaveLength(1)
const [row] = rows
expect(row).toMatchObject({
text: 'Claude is rate-limited and retrying. Retry 3 of 10.\nLast error: HTTP 429 rate limit.',
tone: 'warning',
failure: {
kind: 'providerRetrying',
retry: { error: 'rate_limit', status: 429, attempt: 3, maxRetries: 10 },
detail: { audience: 'log' }
}
})
expect(row).not.toHaveProperty('providerFrame')
expect(row.failure?.detail?.text).toContain('"attempt":3')
})
it('hides unmodeled system frames even when their payload names an error', async () => {
const unknown = {
type: 'system',
subtype: 'future_notice',
error: 'rate_limit',
session_id: 'provider-1',
uuid: 'future-1'
}
const rows = await statusRowsFor([unknown])
expect(rows).toEqual([])
})
})
@@ -1,66 +0,0 @@
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { runProcess } from '@orca/process-host'
import { withCliRuntimeOnPath } from '../../shared/node-cli-command-resolution'
import { claudeBackgroundArgs } from '../../shared/claude-background-run-isolation'
import { CLAUDE_MODEL_LIST_ARGS } from '../../shared/claude-model-list-probe'
import { realClaudeAvailable, realClaudeCommand } from './claude-real-cli-availability-test-support'
// Probe real CLI control answers in a temporary account home without spending a turn.
const root = mkdtempSync(join(tmpdir(), 'orca-claude-isolation-'))
afterEach(() => rmSync(root, { recursive: true, force: true }))
async function loaded(args: string[]): Promise<{ servers: unknown; hooksOff: unknown }> {
const request = (id: string) =>
`${JSON.stringify({ type: 'control_request', request_id: id, request: { subtype: id } })}\n`
const { stdout } = await runProcess({
program: realClaudeCommand,
args,
cwd: root,
input: request('mcp_status') + request('get_settings'),
timeoutMs: 60_000,
env: withCliRuntimeOnPath(realClaudeCommand, {
...process.env,
HOME: root,
CLAUDE_CONFIG_DIR: join(root, 'config')
})
})
const answers = new Map(
stdout.split('\n').flatMap((line) => {
const response = line.startsWith('{') ? JSON.parse(line).response : undefined
return response?.request_id ? [[response.request_id, response.response]] : []
})
)
return {
servers: answers.get('mcp_status')?.mcpServers?.map((server: { name: string }) => server.name),
hooksOff: answers.get('get_settings')?.effective?.disableAllHooks ?? false
}
}
describe.skipIf(!realClaudeAvailable)('background Claude runs with the real CLI', () => {
it('load none of the user MCP servers or hooks, and keep a --mcp-config the user passed', async () => {
const server = { type: 'stdio', command: '/bin/cat', args: [] }
mkdirSync(join(root, 'config'))
writeFileSync(
join(root, 'config', '.claude.json'),
JSON.stringify({ mcpServers: { user: server } })
)
writeFileSync(
join(root, 'config', 'settings.json'),
JSON.stringify({ allowedMcpServers: [{ serverName: 'user' }, { serverName: 'explicit' }] })
)
writeFileSync(join(root, 'mcp.json'), JSON.stringify({ mcpServers: { explicit: server } }))
const listing = CLAUDE_MODEL_LIST_ARGS.slice(0, -claudeBackgroundArgs().length)
expect(await loaded(listing)).toEqual({ servers: ['user'], hooksOff: false })
expect(await loaded([...listing, ...claudeBackgroundArgs()])).toEqual({
servers: [],
hooksOff: true
})
expect(
await loaded([...listing, ...claudeBackgroundArgs(), '--mcp-config', join(root, 'mcp.json')])
).toEqual({ servers: ['explicit'], hooksOff: true })
}, 180_000)
})
@@ -1,185 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
agentChildWorkStopEvidence,
agentChildWorkStopTargets,
type AgentChildWorkStopAcknowledgement
} from '../../shared/agent-status/child-work/agent-child-work-stop-targets'
import type { AgentSessionRecord } from '../../shared/agent-session/lifecycle/agent-session-record'
import { agentChildWorkLiveness } from '../../shared/agent-status/child-work/agent-status-child-work-liveness'
import { conversationCommandBlocked } from '../native-chat/agent-session-wire/operations/structured-conversation-command-admission'
import type { CapturedFrame } from './claude-captured-frame-builders.test-fixture'
import { PARENT_TASK_STOP } from './claude-parent-task-frames.test-fixture'
import { RESUMED_BY_MESSAGE } from './claude-captured-task-frames.test-fixture'
import { hostWithParent, parent, producer } from './claude-child-work-producer-harness.test-fixture'
vi.mock('../telemetry/client', () => ({ track: vi.fn() }))
vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn(() => ({})) }))
afterEach(() => vi.restoreAllMocks())
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: admission reads only the lease and the command/rewind records, all absent here.
const RECORD = { lease: {} } as unknown as AgentSessionRecord
/** Host records retain live work after provider roster removal. */
async function droppedFromRoster() {
const host = hostWithParent()
const run = await producer(host)
const launch: CapturedFrame[] = RESUMED_BY_MESSAGE.filter((captured) => captured.at < 5_077)
run.replay(launch)
run.replay([
{ at: 6_000, frame: { type: 'system', subtype: 'background_tasks_changed', tasks: [] } }
])
const records = () => host.getStructuredChildWorkViews(parent)
const blocked = () =>
conversationCommandBlocked(
{
sessionId: 'session-1',
fence: 7,
journal: {
itemsRead: () => ({ items: [] }),
cursor: () => ({ epoch: 'e', sequence: 0 }),
item: () => null,
submissions: () => [],
inputOrder: { recoverableSubmissions: () => [] },
runningTurn: () => null,
itemFence: () => undefined,
visitItems: () => undefined,
wroteBeforeOpen: () => false
},
adapter: run.adapter
},
RECORD,
{ views: records(), open: agentChildWorkLiveness(records()) !== null }
)
const stopCalls = () =>
run.claude.connections[0]!.calls.filter((call) => call.subtype === 'stop_task')
expect(records()).toMatchObject([
{ membership: 'live', stoppable: true, providerId: 'agent-1', kind: 'agent' }
])
expect(blocked()?.message).toBe('Stop background tasks before using this command.')
// Snapshot stop targets before dispatch; settle only acknowledged records.
const stop = async (taskId?: string) => {
const targets = agentChildWorkStopTargets(records(), taskId)
const acknowledged: AgentChildWorkStopAcknowledgement[] = []
const outcome = await run.adapter.stopBackgroundTasks({
sessionId: 'session-1',
fence: 7,
taskIds: targets.map((target) => target.providerId),
acknowledge: (acknowledgement) => void acknowledged.push(acknowledgement)
})
host.ingestStructuredChildWork(
parent,
agentChildWorkStopEvidence(targets, acknowledged, 6_500),
'claude'
)
return outcome
}
const basis = () => host.getStructuredChildWork(parent).map((record) => record.outcomeBasis)
return { run, records, blocked, stopCalls, stop, basis }
}
describe('a background Stop acts on the host child records', () => {
it('keeps a stopped owner and its independently stoppable shell attached from real task frames', async () => {
const host = hostWithParent()
const run = await producer(host)
run.replay(PARENT_TASK_STOP.slice(0, 7))
const owner = run.records().find((record) => record.kind === 'agent')
expect(owner).toMatchObject({ membership: 'settled', outcome: 'cancelled' })
expect(run.records().find((record) => record.kind === 'command')).toMatchObject({
membership: 'live',
stoppable: true,
parentChildWorkId: owner?.childWorkId
})
const targets = agentChildWorkStopTargets(
host.getStructuredChildWorkViews(parent),
'shell-child'
)
expect(targets.map((target) => target.providerId)).toEqual(['shell-child'])
await run.adapter.stopBackgroundTasks({
sessionId: 'session-1',
fence: 7,
taskIds: targets.map((target) => target.providerId)
})
expect(run.claude.connections[0]!.calls.filter((call) => call.subtype === 'stop_task')).toEqual(
[{ subtype: 'stop_task', params: { taskId: 'shell-child' } }]
)
run.replay(PARENT_TASK_STOP.slice(7))
expect(run.records().find((record) => record.kind === 'command')).toMatchObject({
membership: 'settled',
outcome: 'cancelled'
})
// Start-only delivery in reverse owner order must converge too; no original tool traffic is replayed.
const childFirst = await producer()
childFirst.replay([PARENT_TASK_STOP[3]!, PARENT_TASK_STOP[1]!])
const resolvedOwner = childFirst.records().find((record) => record.kind === 'agent')
expect(childFirst.records().find((record) => record.kind === 'command')).toMatchObject({
membership: 'live',
parentChildWorkId: resolvedOwner?.childWorkId
})
})
it("stops the row's own task, which the records keep after the roster dropped it", async () => {
const { records, blocked, stopCalls, stop, basis } = await droppedFromRoster()
const outcome = await stop('agent-1')
expect(outcome).toMatchObject({ cancelled: true })
expect(stopCalls()).toEqual([{ subtype: 'stop_task', params: { taskId: 'agent-1' } }])
expect(records()).toMatchObject([{ membership: 'settled', outcome: 'cancelled' }])
expect(basis()).toEqual(['stop-acknowledged'])
expect(blocked()).toBeNull()
})
it('leaves a task that ended on its own frame as it ended: its row offers no stop', async () => {
const { run, records, stopCalls, stop } = await droppedFromRoster()
run.replay([
{
at: 7_000,
frame: {
type: 'system',
subtype: 'task_updated',
task_id: 'agent-1',
patch: { status: 'completed' }
}
},
{
at: 7_000,
frame: {
type: 'system',
subtype: 'task_notification',
task_id: 'agent-1',
status: 'completed'
}
}
])
const outcome = await stop('agent-1')
expect(outcome).toMatchObject({ cancelled: false })
expect(stopCalls()).toEqual([])
expect(records()).toMatchObject([{ membership: 'settled', outcome: 'succeeded' }])
})
it('lets the task’s own completion, written before the acknowledgement, replace the Stop', async () => {
const { run, records, stop } = await droppedFromRoster()
await stop('agent-1')
expect(records()).toMatchObject([{ membership: 'settled', outcome: 'cancelled' }])
// The completion the CLI wrote before its answer, which the SDK delivered after it.
run.replay([
{
at: 7_000,
frame: {
type: 'system',
subtype: 'task_notification',
task_id: 'agent-1',
status: 'completed',
summary: 'Found 3 call sites'
}
}
])
expect(records()).toMatchObject([
{ membership: 'settled', outcome: 'succeeded', lastMessage: 'Found 3 call sites' }
])
})
})
@@ -1,238 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import type {
AgentJournalItemBody,
AgentJournalRenderItem
} from '../../shared/agent-session/journal/agent-session-journal-types'
import type { AgentJournalItemIdentity } from '../../shared/agent-session/journal/agent-session-journal-identity'
import { agentJournalItemKey } from '../../shared/agent-session/journal/agent-session-journal-item-key'
import { readAgentJournalTurn } from '../../shared/agent-session/lifecycle/agent-session-turn-record'
import { hasUnansweredStructuredAgentSessionDispatch } from '../../shared/agent-session/requests/structured-agent-session-unanswered-dispatch'
import { projectStructuredAgentSessionStatus } from '../../shared/agent-session/view/structured-agent-session-projection'
import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink'
import { createClaudeJournalTranslator } from './structured/journal/claude-structured-journal-translation'
const SESSION = 'claude-session'
const TOOL = 'toolu_fwd'
function harness() {
const appended: { identity: AgentJournalItemIdentity; body: AgentJournalItemBody }[] = []
const sink: StructuredAgentSessionEventSink = {
appendItem: (identity, body) => appended.push({ identity, body }),
appendTombstone: () => {},
publish: vi.fn()
}
const translator = createClaudeJournalTranslator({ sink, fallbackIdPrefix: 'test' })
const items = (): AgentJournalRenderItem[] => {
const byKey = new Map<string, AgentJournalRenderItem>()
appended.forEach(({ identity, body }, index) => {
const key = agentJournalItemKey(identity)
const existing = byKey.get(key)
byKey.set(key, {
itemId: key,
revision: (existing?.revision ?? 0) + 1,
body,
sequence: existing?.sequence ?? index,
observedAt: index
})
})
return [...byKey.values()].sort((a, b) => a.sequence - b.sequence)
}
return { translator, items, appended }
}
function projected(items: readonly AgentJournalRenderItem[]): string {
expect(hasUnansweredStructuredAgentSessionDispatch([], null)).toBe(false)
return projectStructuredAgentSessionStatus(items, [], null)
}
function systemFrame(uuid: string, fields: Record<string, unknown>) {
return {
type: 'message' as const,
sessionId: 'orca-session',
message: { type: 'system', uuid, session_id: SESSION, ...fields }
}
}
function spawnToolCall(translator: ReturnType<typeof harness>['translator']) {
translator.handle({
type: 'message' as const,
sessionId: 'orca-session',
message: {
type: 'assistant',
uuid: 'a1',
session_id: SESSION,
parent_tool_use_id: null,
message: {
role: 'assistant',
content: [{ type: 'tool_use', id: TOOL, name: 'Bash', input: { command: 'wait' } }]
}
}
})
}
function settleTurn(translator: ReturnType<typeof harness>['translator']) {
translator.handle({
type: 'message' as const,
sessionId: 'orca-session',
message: {
type: 'result',
subtype: 'success',
uuid: 'r1',
session_id: SESSION,
parent_tool_use_id: null,
duration_ms: 1000
}
})
}
describe('a typed background-task row opens the turn it resumes', () => {
it('reports working, not idle, when a task notification wakes the agent', () => {
const { translator, items } = harness()
spawnToolCall(translator)
translator.handle(
systemFrame('s1', {
subtype: 'task_started',
task_id: 'byjnee2no',
tool_use_id: TOOL,
task_type: 'local_bash',
description: 'Wait for the verification verdict',
is_backgrounded: true
})
)
settleTurn(translator)
expect(projected(items())).toBe('idle')
translator.handle(
systemFrame('s2', {
subtype: 'task_notification',
task_id: 'byjnee2no',
tool_use_id: TOOL,
status: 'failed',
summary: 'Background command "Wait" failed with exit code 1'
})
)
const taskRow = items().find((item) => item.itemId.includes('byjnee2no'))
expect(taskRow).toBeDefined()
const running = items().filter((item) => readAgentJournalTurn(item.body)?.state === 'running')
expect(running).toHaveLength(1)
expect(projected(items())).toBe('working')
})
it('does not reopen a completed turn when an overflow terminal row is enriched', () => {
const { translator, items } = harness()
for (let index = 0; index < 64; index += 1) {
translator.handle(
systemFrame(`start-${index}`, {
subtype: 'task_started',
task_id: `live-${index}`,
task_type: 'local_bash',
is_backgrounded: true
})
)
}
translator.handle(
systemFrame('overflow-start', {
subtype: 'task_started',
task_id: 'overflow-turn',
task_type: 'local_bash',
is_backgrounded: true
})
)
translator.handle(
systemFrame('overflow-update', {
subtype: 'task_updated',
task_id: 'overflow-turn',
patch: { status: 'failed' }
})
)
settleTurn(translator)
expect(projected(items())).toBe('idle')
translator.handle(
systemFrame('overflow-notification', {
subtype: 'task_notification',
task_id: 'overflow-turn',
status: 'stopped',
summary: 'No completion record was found'
})
)
expect(projected(items())).toBe('idle')
})
})
it('keeps an alias-only owned notification idle even when its alias was forwarded at the root', () => {
const { translator, items } = harness()
spawnToolCall(translator)
translator.handle(
systemFrame('owned-start', {
subtype: 'task_started',
task_id: 'owned',
tool_use_id: TOOL,
parent_task_id: 'owner',
task_type: 'local_bash',
is_backgrounded: true
})
)
settleTurn(translator)
translator.handle(
systemFrame('owned-terminal', {
subtype: 'task_notification',
tool_use_id: TOOL,
status: 'completed',
summary: 'Finished child'
})
)
expect(items().find((item) => item.itemId.includes('owned'))?.body).toMatchObject({
kind: 'message',
blocks: expect.arrayContaining([
expect.objectContaining({ type: 'background-task', taskId: 'owned', state: 'done' })
])
})
expect(projected(items())).toBe('idle')
translator.dispose()
})
it('keeps owned terminal overflow writes idle without a retained row invocation', () => {
const { translator, items } = harness()
for (let index = 0; index < 65; index += 1) {
translator.handle(
systemFrame(`owned-start-${index}`, {
subtype: 'task_started',
task_id: `owned-${index}`,
parent_task_id: 'owner',
task_type: 'local_bash',
is_backgrounded: true
})
)
}
settleTurn(translator)
translator.handle(
systemFrame('overflow-owned-patch', {
subtype: 'task_updated',
task_id: 'owned-64',
patch: { status: 'failed' }
})
)
translator.handle(
systemFrame('overflow-owned-orphan', {
subtype: 'task_notification',
task_id: 'owned-terminal-only',
parent_task_id: 'owner',
status: 'completed'
})
)
const terminal = items().filter(
(item) =>
item.body.kind === 'message' &&
item.body.blocks.some(
(block) =>
block.type === 'background-task' &&
['owned-64', 'owned-terminal-only'].includes(block.taskId)
)
)
expect(terminal).toHaveLength(2)
expect(projected(items())).toBe('idle')
translator.dispose()
})
@@ -1,157 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { AgentJournalSubmission } from '../../shared/agent-session/journal/agent-session-journal-types'
import { structuredRunningChildWork } from '../../shared/agent-status/child-work/agent-child-work-listing'
import type { AgentHookServer } from '../agent-hooks/server/agent-hook-server'
import type { StructuredAgentSessionJournalProjections } from '../native-chat/agent-session-wire/observations/structured-agent-session-status-journal-projection'
import { StructuredAgentSessionStatusFeed } from '../native-chat/agent-session-wire/observations/structured-agent-session-status-feed'
import type { CapturedFrame } from './claude-captured-frame-builders.test-fixture'
import { backgroundWakeCapture } from './claude-captured-fold-steer-frames.test-fixture'
import { MOVED_TO_BACKGROUND } from './claude-captured-task-frames.test-fixture'
import { hostWithParent, parent, producer } from './claude-child-work-producer-harness.test-fixture'
import { PROVIDER_SESSION_ID } from './structured/claude-structured-session-test-support'
import { createStructuredAgentSessionLogger } from '../native-chat/agent-session-wire/host/structured-agent-session-logger'
vi.mock('../telemetry/client', () => ({ track: vi.fn() }))
vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn(() => ({})) }))
afterEach(() => vi.restoreAllMocks())
type Journal = Parameters<StructuredAgentSessionJournalProjections['read']>[0]
async function wiredSession() {
const host: AgentHookServer = hostWithParent()
const run = await producer(host)
const submissions: AgentJournalSubmission[] = []
let sequence = 0
const journal = {
cursor: () => ({ epoch: 'epoch-1', sequence: ++sequence }),
lastActivityAt: () => 1,
submissions: (): ReturnType<Journal['submissions']> =>
submissions.map((submission) => ({ ...submission })),
item: (itemId: string): ReturnType<Journal['item']> => {
const item = run.journalItems.get(itemId)
return item ? { ...item, revision: 1, observedAt: run.now() } : null
},
statusRead(): ReturnType<Journal['statusRead']> {
return this.snapshot()
},
inputOrder: {
inputCount: () => submissions.length,
inputOrdinal: (id: string) => submissions.findIndex((s) => s.clientMessageId === id),
recoverableSubmissions: () =>
submissions.filter((s) => s.dispatchState === 'pending' || s.dispatchState === 'unknown')
},
context: { floor: () => null },
stopMarks: { latest: () => null, revision: () => 0 },
itemFence: () => undefined,
wroteBeforeOpen: () => false,
runningTurn: () => null,
snapshot: () => ({
items: [...run.journalItems.values()]
.sort((a, b) => a.sequence - b.sequence)
.map((item) => ({ ...item, revision: 1, observedAt: run.now() })),
submissions: submissions.map((submission) => ({ ...submission }))
})
}
const feed = new StructuredAgentSessionStatusFeed({
logger: createStructuredAgentSessionLogger(),
sessions: new Map([
[
parent.sessionId,
{
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the fixture supplies the feed's cursor, clock, Stop marks, context floor, snapshot, submissions, item and provenance reads.
journal: journal as unknown as Journal,
params: {
location: {
executionHostId: parent.executionHostId,
wslDistro: parent.wslDistro,
workspaceId: parent.workspaceId,
workspaceKind: parent.workspaceKind
},
provider: 'claude' as const
}
}
]
]),
getConversation: () => null,
now: () => Date.now(),
statusSink: () => ({
publish: (summary, subject) => host.ingestStructuredStatus(summary, subject),
forget: (subject) => host.dropStructuredStatus(subject),
publishChildWork: (subject, evidence, provider) =>
host.ingestStructuredChildWork(subject, evidence, provider),
readChildWork: (subject) => host.getStructuredChildWorkViews(subject)
})
})
const describe = (views: ReturnType<typeof host.getStructuredChildWorkViews>) =>
views.map((view) => `${view.description}:${view.membership}:${view.outcome ?? ''}`)
const records = () => describe(host.getStructuredChildWorkViews(parent))
const running = () =>
describe(structuredRunningChildWork(host.getStructuredChildWorkViews(parent)))
const replay = (frames: readonly CapturedFrame[]) => {
for (const captured of frames) {
run.replay([captured])
feed.publish(parent.sessionId)
}
}
const send = (clientMessageId: string): AgentJournalSubmission => {
const submission: AgentJournalSubmission = {
clientMessageId,
fence: 7,
payloadFingerprint: clientMessageId,
dispatchState: 'pending',
providerItemId: null,
reason: null,
submittedAt: run.now(),
resolvedAt: null
}
submissions.push(submission)
feed.publish(parent.sessionId)
return submission
}
const accept = (submission: AgentJournalSubmission) => {
submission.dispatchState = 'accepted'
feed.publish(parent.sessionId)
}
const rootTurns = () =>
[...run.journalItems.values()].filter((item) => !item.agentId && item.body.kind === 'turn')
return { run, feed, records, running, replay, send, accept, rootTurns }
}
describe("a finished child's record stays until the user's next turn", () => {
it("keeps a background agent through Claude's own wake turn, then retires it at the next send", async () => {
const session = await wiredSession()
session.replay(MOVED_TO_BACKGROUND)
expect(session.rootTurns()).toHaveLength(2)
expect(session.records()).toContain('Run 45s sleep command:settled:succeeded')
expect(session.running()).toEqual([])
const next = session.send('next-send')
// Submitting is not acceptance; a refused send must not retire retained work.
expect(session.records()).toContain('Run 45s sleep command:settled:succeeded')
session.accept(next)
expect(session.records()).toEqual([])
})
it('keeps a background shell through the wake its completion opens, and a steer into that wake retires it', async () => {
const session = await wiredSession()
const { firstTurn, wake } = backgroundWakeCapture({
sessionId: PROVIDER_SESSION_ID,
first: 'first-uuid',
steer: 'steer-uuid'
})
session.accept(session.send('first-uuid'))
session.replay(firstTurn)
expect(session.running()).toEqual(['Sleep then print marker:live:'])
const wakeInit = wake.findIndex((captured) => captured.frame.subtype === 'init')
session.replay(wake.slice(0, wakeInit + 1))
expect(session.rootTurns()).toHaveLength(2)
expect(session.records()).toEqual(['Sleep then print marker:settled:succeeded'])
expect(session.running()).toEqual([])
session.accept(session.send('steer-uuid'))
expect(session.records()).toEqual([])
session.replay(wake.slice(wakeInit + 1))
expect(session.records()).toEqual([])
})
})
@@ -1,254 +0,0 @@
// CLI 2.1.280 captures: sanitized IDs/paths/prompts; original frame order and send-relative times.
import {
assistant,
assistantText,
assistantToolUse,
initFrame,
resultFrame,
sessionIdle,
taskFrame,
toolResult,
userReplay,
type CapturedFoldFrame,
type FoldCaptureIds
} from './claude-fold-steer-frame-builders.test-fixture'
export type { CapturedFoldFrame, FoldCaptureIds }
export const FIRST_PROMPT = 'Run the sleep command three times, then reply: FIRST DONE'
export const STEER_PROMPT = 'Also say the word banana at the end of your reply.'
export const SECOND_STEER_PROMPT = 'And also say the word mango at the very end.'
export const FOLD_FRESH_SEND_AT = { first: 12, steer: 3_878 }
export function foldFreshCapture({ sessionId, first, steer }: FoldCaptureIds): CapturedFoldFrame[] {
return [
initFrame(222, sessionId),
userReplay(2_094, sessionId, first, FIRST_PROMPT),
assistantToolUse(2_676, sessionId, 'reply-tool-1', 'toolu_sleep_1', [first]),
toolResult(7_890, sessionId, 'tool-result-1', 'toolu_sleep_1'),
userReplay(7_892, sessionId, steer, STEER_PROMPT),
assistantToolUse(9_725, sessionId, 'reply-tool-2', 'toolu_sleep_2'),
toolResult(14_740, sessionId, 'tool-result-2', 'toolu_sleep_2'),
assistantText(23_039, sessionId, 'reply-text-1', 'FIRST DONE banana'),
resultFrame(23_048, sessionId, 'result-1', {
userMessageUuids: [first, steer],
durationMs: 22_845,
numTurns: 4
}),
sessionIdle(23_049, sessionId)
]
}
export const FOLD_RESUMED_SEND_AT = { first: 12, steer: 4_458 }
export function foldResumedCapture({
sessionId,
first,
steer
}: FoldCaptureIds): CapturedFoldFrame[] {
return [
initFrame(218, sessionId),
userReplay(2_057, sessionId, first, FIRST_PROMPT),
assistant(
3_229,
sessionId,
'reply-thinking-1',
[{ type: 'thinking', thinking: 'plan' }],
[first]
),
assistantToolUse(3_258, sessionId, 'reply-tool-1', 'toolu_sleep_1'),
toolResult(8_464, sessionId, 'tool-result-1', 'toolu_sleep_1'),
userReplay(8_467, sessionId, steer, STEER_PROMPT),
assistantToolUse(10_318, sessionId, 'reply-tool-2', 'toolu_sleep_2'),
toolResult(15_373, sessionId, 'tool-result-2', 'toolu_sleep_2'),
assistantText(23_587, sessionId, 'reply-text-1', 'FIRST DONE banana'),
resultFrame(23_628, sessionId, 'result-1', {
userMessageUuids: [first, steer],
durationMs: 23_367,
numTurns: 4
}),
sessionIdle(23_640, sessionId)
]
}
export const TWO_STEERS_SEND_AT = { first: 31, steer: 3_630, secondSteer: 5_031 }
export function twoSteersCapture({
sessionId,
first,
steer,
secondSteer
}: Required<FoldCaptureIds>): CapturedFoldFrame[] {
return [
initFrame(351, sessionId),
userReplay(1_169, sessionId, first, FIRST_PROMPT),
assistantToolUse(2_412, sessionId, 'reply-tool-1', 'toolu_sleep_1', [first]),
toolResult(7_949, sessionId, 'tool-result-1', 'toolu_sleep_1'),
userReplay(7_963, sessionId, steer, STEER_PROMPT),
userReplay(7_967, sessionId, secondSteer, SECOND_STEER_PROMPT),
assistantToolUse(9_806, sessionId, 'reply-tool-2', 'toolu_sleep_2'),
toolResult(14_835, sessionId, 'tool-result-2', 'toolu_sleep_2'),
assistantText(22_210, sessionId, 'reply-text-1', 'FIRST DONE banana mango'),
resultFrame(22_317, sessionId, 'result-1', {
userMessageUuids: [first, steer, secondSteer],
durationMs: 21_859,
numTurns: 4
}),
sessionIdle(22_341, sessionId)
]
}
/** A steer replayed after the first result runs in its own turn. */
export const MISS_SEND_AT = { first: 30, steer: 23_384 }
export function missCapture({ sessionId, first, steer }: FoldCaptureIds): {
beforeSteerSend: CapturedFoldFrame[]
afterSteerSend: CapturedFoldFrame[]
} {
return {
beforeSteerSend: [
initFrame(333, sessionId),
userReplay(2_118, sessionId, first, FIRST_PROMPT),
assistantToolUse(2_793, sessionId, 'reply-tool-1', 'toolu_sleep_1', [first]),
toolResult(8_258, sessionId, 'tool-result-1', 'toolu_sleep_1'),
assistantToolUse(11_019, sessionId, 'reply-tool-2', 'toolu_sleep_2'),
toolResult(15_961, sessionId, 'tool-result-2', 'toolu_sleep_2'),
assistantToolUse(18_362, sessionId, 'reply-tool-3', 'toolu_sleep_3'),
toolResult(23_375, sessionId, 'tool-result-3', 'toolu_sleep_3')
],
afterSteerSend: [
assistantText(25_550, sessionId, 'reply-text-1', 'FIRST DONE'),
resultFrame(25_556, sessionId, 'result-1', {
userMessageUuids: [first],
durationMs: 25_241,
numTurns: 4
}),
initFrame(25_584, sessionId),
userReplay(28_703, sessionId, steer, STEER_PROMPT),
assistantText(29_239, sessionId, 'reply-text-2', 'banana'),
resultFrame(29_275, sessionId, 'result-2', {
userMessageUuids: [steer],
durationMs: 3_711,
numTurns: 1
}),
sessionIdle(29_306, sessionId)
]
}
}
/** Cancelled steer has no replay; the synthetic interrupt text is not a send. */
export const CANCEL_SEND_AT = { first: 18, steer: 3_578 }
export function cancelCapture({ sessionId, first, steer: _steer }: FoldCaptureIds): {
beforeSteerSend: CapturedFoldFrame[]
afterInterrupt: CapturedFoldFrame[]
} {
return {
beforeSteerSend: [
initFrame(354, sessionId),
userReplay(1_329, sessionId, first, FIRST_PROMPT),
assistantToolUse(2_366, sessionId, 'reply-tool-1', 'toolu_sleep_1', [first])
],
afterInterrupt: [
toolResult(
3_889,
sessionId,
'tool-result-1',
'toolu_sleep_1',
"The user doesn't want to proceed with this tool use.",
true
),
{
at: 3_900,
frame: {
type: 'user',
session_id: sessionId,
parent_tool_use_id: null,
uuid: 'interrupt-notice-1',
message: {
role: 'user',
content: [{ type: 'text', text: '[Request interrupted by user for tool use]' }]
}
}
},
resultFrame(3_926, sessionId, 'result-1', {
userMessageUuids: [first],
durationMs: 3_573,
numTurns: 3,
subtype: 'error_during_execution',
isError: true,
terminalReason: 'aborted_tools'
}),
sessionIdle(3_941, sessionId)
]
}
}
/** A steer before the first replay still folds into one result naming both sends. */
export const EARLY_STEER_SEND_AT = { first: 11, steer: 312 }
export function earlySteerCapture({
sessionId,
first,
steer
}: FoldCaptureIds): CapturedFoldFrame[] {
return [
initFrame(205, sessionId),
userReplay(1_208, sessionId, first, FIRST_PROMPT),
assistantToolUse(2_190, sessionId, 'reply-tool-1', 'toolu_sleep_1', [first]),
toolResult(6_316, sessionId, 'tool-result-1', 'toolu_sleep_1'),
userReplay(6_318, sessionId, steer, STEER_PROMPT),
assistantText(7_336, sessionId, 'reply-text-1', 'FIRST DONE banana'),
resultFrame(7_340, sessionId, 'result-1', {
userMessageUuids: [first, steer],
durationMs: 7_155,
numTurns: 2
}),
sessionIdle(7_341, sessionId)
]
}
/** Completion precedes wake init; the new cycle has no user replay or result send IDs. */
export function backgroundWakeCapture({ sessionId, first }: FoldCaptureIds): {
firstTurn: CapturedFoldFrame[]
wake: CapturedFoldFrame[]
} {
return {
firstTurn: [
initFrame(252, sessionId),
userReplay(1_193, sessionId, first, FIRST_PROMPT),
assistantToolUse(2_372, sessionId, 'reply-tool-1', 'toolu_bg_1', [first]),
taskFrame(2_530, sessionId, 'task_started', {
task_id: 'task_bg_1',
tool_use_id: 'toolu_bg_1',
description: 'Sleep then print marker',
is_backgrounded: true,
task_type: 'local_bash'
}),
toolResult(2_532, sessionId, 'tool-result-1', 'toolu_bg_1'),
assistantText(3_403, sessionId, 'reply-text-1', 'STARTED'),
resultFrame(3_406, sessionId, 'result-1', {
userMessageUuids: [first],
durationMs: 3_177,
numTurns: 2
}),
sessionIdle(3_407, sessionId)
],
wake: [
taskFrame(17_547, sessionId, 'task_updated', {
task_id: 'task_bg_1',
patch: { status: 'completed' }
}),
taskFrame(17_547, sessionId, 'task_notification', {
task_id: 'task_bg_1',
tool_use_id: 'toolu_bg_1',
status: 'completed',
summary: 'Background command completed (exit code 0)'
}),
initFrame(17_626, sessionId),
assistantText(19_721, sessionId, 'wake-text-1', 'The background command finished.'),
resultFrame(19_729, sessionId, 'result-2', {
userMessageUuids: [],
durationMs: 2_105,
numTurns: 1
}),
sessionIdle(19_730, sessionId)
]
}
}
@@ -1,145 +0,0 @@
// CLI 2.1.280 captures: sanitized IDs/paths/prompts; original frame order and send-relative times.
import {
result,
spawn,
system,
toolResult,
type CapturedFrame
} from './claude-captured-frame-builders.test-fixture'
const interruptedAgentStart = (at: number, toolUseId: string): CapturedFrame[] => [
{
at,
frame: spawn(toolUseId, 'Agent', { description: 'Run sleep command and report' }, null)
},
{
at: at + 16,
frame: system('task_started', {
task_id: 'agent-1',
tool_use_id: toolUseId,
description: 'Run sleep command and report',
subagent_type: 'general-purpose',
is_backgrounded: false,
task_type: 'local_agent'
})
},
{
at: at + 4_357,
frame: system('task_progress', {
task_id: 'agent-1',
tool_use_id: toolUseId,
usage: { total_tokens: 18_844, tool_uses: 1, duration_ms: 4_342 },
last_tool_name: 'Bash'
})
}
]
const REJECTED = "The user doesn't want to proceed with this tool use. The tool use was rejected."
/** An interrupt while the foreground agent sits between tools: its own stop comes first. */
export const INTERRUPTED_BETWEEN_TOOLS: CapturedFrame[] = [
...interruptedAgentStart(5_000, 'toolu_agent'),
{
at: 11_019,
frame: system('task_updated', { task_id: 'agent-1', patch: { status: 'killed' } })
},
{
at: 11_019,
frame: system('task_notification', {
task_id: 'agent-1',
tool_use_id: 'toolu_agent',
status: 'stopped',
summary: 'Run sleep command and report'
})
},
{ at: 11_020, frame: toolResult('toolu_agent', REJECTED, null, true) },
{ at: 11_026, frame: result('error_during_execution') }
]
/** An interrupt while the foreground agent's own shell runs: the spawn result precedes its stop. */
export const INTERRUPTED_IN_OWN_SHELL: CapturedFrame[] = [
...interruptedAgentStart(2_876, 'toolu_agent'),
{
at: 6_317,
frame: spawn('toolu_shell', 'Bash', { command: 'sleep 45; echo 1' }, 'toolu_agent')
},
{
at: 9_424,
frame: system('task_started', {
task_id: 'shell-1',
owned_by_subagent: true,
tool_use_id: 'toolu_shell',
description: 'Sleep 45 seconds then print 1',
is_backgrounded: false,
task_type: 'local_bash'
})
},
{
at: 11_321,
frame: system('task_notification', {
task_id: 'shell-1',
tool_use_id: 'toolu_shell',
status: 'stopped',
summary: 'Sleep 45 seconds then print 1'
})
},
{ at: 11_324, frame: toolResult('toolu_agent', REJECTED, null, true) },
{
at: 11_325,
frame: system('task_updated', { task_id: 'agent-1', patch: { status: 'killed' } })
},
{
at: 11_325,
frame: system('task_notification', {
task_id: 'agent-1',
tool_use_id: 'toolu_agent',
status: 'stopped',
summary: 'Run sleep command and report'
})
},
{ at: 11_328, frame: result('error_during_execution') }
]
/** A foreground agent that finishes: its own ending, then its summary, then the spawn result. */
export const FOREGROUND_SUCCESS: CapturedFrame[] = [
{ at: 3_695, frame: spawn('toolu_agent', 'Agent', { description: 'Run echo hi command' }, null) },
{
at: 3_709,
frame: system('task_started', {
task_id: 'agent-1',
tool_use_id: 'toolu_agent',
description: 'Run echo hi command',
subagent_type: 'general-purpose',
is_backgrounded: false,
task_type: 'local_agent'
})
},
{
at: 5_501,
frame: system('task_progress', {
task_id: 'agent-1',
tool_use_id: 'toolu_agent',
usage: { total_tokens: 14_576, tool_uses: 1, duration_ms: 1_792 },
last_tool_name: 'Bash'
})
},
{ at: 5_505, frame: spawn('toolu_echo', 'Bash', { command: 'echo hi' }, 'toolu_agent') },
{ at: 5_652, frame: toolResult('toolu_echo', 'hi', 'toolu_agent', false) },
{
at: 7_101,
frame: system('task_updated', { task_id: 'agent-1', patch: { status: 'completed' } })
},
{
at: 7_101,
frame: system('task_notification', {
task_id: 'agent-1',
tool_use_id: 'toolu_agent',
status: 'completed',
summary: 'The command executed successfully. Output: `hi`',
usage: { total_tokens: 16_908, tool_uses: 1, duration_ms: 3_393 }
})
},
{ at: 7_113, frame: toolResult('toolu_agent', 'hi', null) },
{ at: 8_952, frame: result('success') }
]
@@ -1,59 +0,0 @@
export type CapturedFrame = { at: number; frame: Record<string, unknown> }
export function spawn(
id: string,
name: string,
input: Record<string, unknown>,
parent: string | null
) {
return {
type: 'assistant',
parent_tool_use_id: parent,
message: {
id: `msg-${id}`,
role: 'assistant',
content: [{ type: 'tool_use', id, name, input }]
}
}
}
export function toolResult(
toolUseId: string,
content: string,
parent: string | null,
isError?: boolean
) {
return {
type: 'user',
parent_tool_use_id: parent,
message: {
role: 'user',
content: [
{
type: 'tool_result',
tool_use_id: toolUseId,
content,
...(isError === undefined ? {} : { is_error: isError })
}
]
}
}
}
export function says(id: string, text: string, parent: string | null) {
return {
type: 'assistant',
parent_tool_use_id: parent,
message: { id: `msg-${id}`, role: 'assistant', content: [{ type: 'text', text }] }
}
}
export function system(subtype: string, fields: Record<string, unknown>) {
return { type: 'system', subtype, ...fields }
}
export const result = (subtype: string) => ({
type: 'result',
subtype,
is_error: subtype !== 'success'
})
@@ -1,224 +0,0 @@
// CLI 2.1.280 captures: sanitized IDs/paths/prompts; original frame order and send-relative times.
import {
result,
says,
spawn,
system,
toolResult,
type CapturedFrame
} from './claude-captured-frame-builders.test-fixture'
/** Parent finishes while the backgrounded agent's shell keeps running. */
export const MOVED_TO_BACKGROUND: CapturedFrame[] = [
{
at: 3_259,
frame: spawn(
'toolu_agent',
'Agent',
{ description: 'Run 45s sleep command', run_in_background: false },
null
)
},
{
at: 3_275,
frame: system('task_started', {
task_id: 'agent-1',
tool_use_id: 'toolu_agent',
description: 'Run 45s sleep command',
subagent_type: 'general-purpose',
is_backgrounded: false,
task_type: 'local_agent'
})
},
{
at: 6_126,
frame: system('task_progress', {
task_id: 'agent-1',
tool_use_id: 'toolu_agent',
description: 'Running Sleep 45 seconds then print 1',
usage: { total_tokens: 18_837, tool_uses: 1, duration_ms: 2_852 },
last_tool_name: 'Bash'
})
},
{
at: 6_127,
frame: spawn(
'toolu_shell',
'Bash',
{ command: 'sleep 45; echo 1', description: 'Sleep 45 seconds then print 1' },
'toolu_agent'
)
},
{
at: 9_249,
frame: system('task_started', {
task_id: 'shell-1',
owned_by_subagent: true,
tool_use_id: 'toolu_shell',
description: 'Sleep 45 seconds then print 1',
is_backgrounded: false,
task_type: 'local_bash'
})
},
{
at: 11_128,
frame: system('background_tasks_changed', {
tasks: [
{ task_id: 'agent-1', task_type: 'local_agent', description: 'Run 45s sleep command' }
]
})
},
{
at: 11_128,
frame: system('task_updated', { task_id: 'agent-1', patch: { is_backgrounded: true } })
},
{
at: 11_139,
frame: toolResult('toolu_agent', 'Async agent launched successfully.', null)
},
{ at: 12_563, frame: says('parent-1', 'The agent has been launched.', null) },
{ at: 12_610, frame: result('success') },
{
at: 51_275,
frame: system('task_notification', {
task_id: 'shell-1',
tool_use_id: 'toolu_shell',
status: 'completed',
summary: 'Sleep 45 seconds then print 1'
})
},
{ at: 51_292, frame: toolResult('toolu_shell', '1', 'toolu_agent', false) },
{ at: 52_398, frame: says('agent-1-final', 'Exact stdout: `1`', 'toolu_agent') },
{ at: 52_441, frame: system('background_tasks_changed', { tasks: [] }) },
{
at: 52_441,
frame: system('task_updated', { task_id: 'agent-1', patch: { status: 'completed' } })
},
{
at: 52_441,
frame: system('task_notification', {
task_id: 'agent-1',
tool_use_id: 'toolu_agent',
status: 'completed',
summary: 'The command completed after ~45 seconds. Exact stdout: `1`',
usage: { total_tokens: 22_160, tool_uses: 1, duration_ms: 49_167 }
})
},
{ at: 54_303, frame: says('parent-2', 'The agent ran the command.', null) },
{ at: 54_450, frame: result('success') }
]
/** Messaging a finished agent resumes it under the message call, after its roster entry. */
export const RESUMED_BY_MESSAGE: CapturedFrame[] = [
{
at: 3_279,
frame: spawn(
'toolu_agent',
'Agent',
{ description: 'Run echo first-run command', run_in_background: true },
null
)
},
{
at: 3_320,
frame: system('background_tasks_changed', {
tasks: [
{ task_id: 'agent-1', task_type: 'local_agent', description: 'Run echo first-run command' }
]
})
},
{
at: 3_322,
frame: system('task_started', {
task_id: 'agent-1',
tool_use_id: 'toolu_agent',
description: 'Run echo first-run command',
subagent_type: 'general-purpose',
is_backgrounded: true,
task_type: 'local_agent'
})
},
{ at: 3_349, frame: toolResult('toolu_agent', 'Async agent launched successfully.', null) },
{ at: 4_765, frame: result('success') },
{
at: 5_077,
frame: system('task_progress', {
task_id: 'agent-1',
tool_use_id: 'toolu_agent',
usage: { total_tokens: 13_615, tool_uses: 1, duration_ms: 1_759 },
last_tool_name: 'Bash'
})
},
{ at: 7_427, frame: system('background_tasks_changed', { tasks: [] }) },
{
at: 7_427,
frame: system('task_updated', { task_id: 'agent-1', patch: { status: 'completed' } })
},
{
at: 7_427,
frame: system('task_notification', {
task_id: 'agent-1',
tool_use_id: 'toolu_agent',
status: 'completed',
summary: 'The command executed successfully. Output: `first-run`',
usage: { total_tokens: 15_971, tool_uses: 1, duration_ms: 4_110 }
})
},
{ at: 10_960, frame: result('success') },
{
at: 16_118,
frame: spawn(
'toolu_message',
'SendMessage',
{ to: 'agent-1', message: 'Run echo second-run and report.' },
null
)
},
{
at: 16_142,
frame: system('background_tasks_changed', {
tasks: [
{ task_id: 'agent-1', task_type: 'local_agent', description: 'Run echo first-run command' }
]
})
},
{
at: 16_143,
frame: system('task_started', {
task_id: 'agent-1',
tool_use_id: 'toolu_message',
description: 'Run echo first-run command',
subagent_type: 'general-purpose',
is_backgrounded: true,
task_type: 'local_agent'
})
},
{ at: 16_166, frame: toolResult('toolu_message', '{"success":true}', null) },
{ at: 17_420, frame: result('success') },
{
at: 17_889,
frame: system('task_progress', {
task_id: 'agent-1',
tool_use_id: 'toolu_message',
usage: { total_tokens: 16_064, tool_uses: 2, duration_ms: 14_568 },
last_tool_name: 'Bash'
})
},
{ at: 19_568, frame: system('background_tasks_changed', { tasks: [] }) },
{
at: 19_568,
frame: system('task_updated', { task_id: 'agent-1', patch: { status: 'completed' } })
},
{
at: 19_568,
frame: system('task_notification', {
task_id: 'agent-1',
tool_use_id: 'toolu_message',
status: 'completed',
summary: 'The command executed successfully. Output: `second-run`',
usage: { total_tokens: 16_259, tool_uses: 2, duration_ms: 16_249 }
})
},
{ at: 20_956, frame: result('success') }
]
@@ -1,121 +0,0 @@
// CLI 2.1.280 capture: sanitized IDs/prompts; original frame order and spawn-relative times.
import {
result,
says,
spawn,
system,
toolResult,
type CapturedFrame
} from './claude-captured-frame-builders.test-fixture'
/** Shell completion resumes the same agent under its original spawn call. */
export const WAKES_AFTER_ITS_SHELL: CapturedFrame[] = [
{
at: 0,
frame: spawn(
'toolu_agent',
'Agent',
{ description: 'Sleep 40 seconds then reply', run_in_background: true },
null
)
},
{
at: 15,
frame: system('task_started', {
task_id: 'agent-1',
tool_use_id: 'toolu_agent',
description: 'Sleep 40 seconds then reply',
subagent_type: 'general-purpose',
is_backgrounded: true,
task_type: 'local_agent'
})
},
{ at: 30, frame: toolResult('toolu_agent', 'Async agent launched successfully.', null) },
{ at: 1_944, frame: result('success') },
{
at: 4_343,
frame: spawn(
'toolu_shell',
'Bash',
{
command: 'sleep 40',
description: 'Wait 40 seconds in background',
run_in_background: true
},
'toolu_agent'
)
},
{
at: 4_431,
frame: system('task_started', {
task_id: 'shell-1',
owned_by_subagent: true,
tool_use_id: 'toolu_shell',
description: 'Wait 40 seconds in background',
is_backgrounded: true,
task_type: 'local_bash'
})
},
{
at: 4_441,
frame: toolResult(
'toolu_shell',
'Command running in background with ID: shell-1.',
'toolu_agent'
)
},
{
at: 11_913,
frame: system('task_updated', { task_id: 'agent-1', patch: { status: 'completed' } })
},
{
at: 11_913,
frame: system('task_notification', {
task_id: 'agent-1',
tool_use_id: 'toolu_agent',
status: 'completed',
summary: '`sleep 40` is still running in the background.',
usage: { total_tokens: 17_928, tool_uses: 2, duration_ms: 11_901 }
})
},
{
at: 44_454,
frame: system('task_updated', { task_id: 'shell-1', patch: { status: 'completed' } })
},
{
at: 44_454,
frame: system('task_notification', {
task_id: 'shell-1',
tool_use_id: 'toolu_shell',
status: 'completed',
summary: 'Background command "Wait 40 seconds in background" completed (exit code 0)'
})
},
{
at: 44_460,
frame: system('task_started', {
task_id: 'agent-1',
tool_use_id: 'toolu_agent',
description: 'Sleep 40 seconds then reply',
subagent_type: 'general-purpose',
is_backgrounded: true,
task_type: 'local_agent'
})
},
{ at: 46_198, frame: says('agent-1-final', 'DONE', 'toolu_agent') },
{
at: 46_198,
frame: system('task_updated', { task_id: 'agent-1', patch: { status: 'completed' } })
},
{
at: 46_199,
frame: system('task_notification', {
task_id: 'agent-1',
tool_use_id: 'toolu_agent',
status: 'completed',
summary: 'DONE',
usage: { total_tokens: 18_181, tool_uses: 2, duration_ms: 46_184 }
})
}
]
@@ -1,191 +0,0 @@
import { expect } from 'vitest'
import { agentJournalItemKey } from '../../shared/agent-session/journal/agent-session-journal-item-key'
import type { AgentJournalRenderItem } from '../../shared/agent-session/journal/agent-session-journal-types'
import { createAgentChildWorkAdmission } from '../../shared/agent-status/child-work/agent-status-child-work-admission'
import type { AgentChildWorkRecord } from '../../shared/agent-status/child-work/agent-status-child-work'
import type { AgentChildWorkEvidence } from '../../shared/agent-status/child-work/agent-status-child-work-evidence'
import { reconcileAgentChildWorkEvidence } from '../../shared/agent-status/child-work/agent-status-child-work-reconciliation'
import type { AgentChildWorkReconcileOutcome } from '../../shared/agent-status/child-work/agent-status-child-work-evidence-admission'
import { createAgentStatusStore } from '../../shared/agent-status/store/agent-status-store'
import { makeStructuredAgentStatusSubject } from '../../shared/agent-status/contracts/agent-status-subject'
import { AgentHookServer } from '../agent-hooks/server/agent-hook-server'
import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink'
import type { CapturedFrame } from './claude-captured-frame-builders.test-fixture'
import { ClaudeStructuredSessionAdapter } from './structured/claude-structured-session-adapter'
import {
fakeClaude,
identityFor,
PROVIDER_SESSION_ID
} from './structured/claude-structured-session-test-support'
export const parent = makeStructuredAgentStatusSubject(
{
executionHostId: 'local',
wslDistro: null,
workspaceId: 'workspace-1',
workspaceKind: 'folder'
},
'session-1'
)
let uuid = 0
export function frame(fields: Record<string, unknown>): Record<string, unknown> {
return { session_id: PROVIDER_SESSION_ID, uuid: `frame-${++uuid}`, ...fields }
}
export function system(subtype: string, fields: Record<string, unknown>) {
return frame({ type: 'system', subtype, ...fields })
}
export function toolUse(
id: string,
name: string,
input: unknown,
parentToolUseId: string | null = null
) {
return frame({
type: 'assistant',
parent_tool_use_id: parentToolUseId,
message: {
id: `msg-${id}`,
role: 'assistant',
content: [{ type: 'tool_use', id, name, input }]
}
})
}
export function toolResult(
toolUseId: string,
text: string,
parentToolUseId: string | null = null,
isError = false
) {
return frame({
type: 'user',
parent_tool_use_id: parentToolUseId,
message: {
role: 'user',
content: [{ type: 'tool_result', tool_use_id: toolUseId, content: text, is_error: isError }]
}
})
}
type Delivery = { kind: 'journal' | 'publish' | 'evidence'; detail: string }
export type JournaledItem = Pick<AgentJournalRenderItem, 'itemId' | 'body' | 'sequence' | 'agentId'>
export const T0 = 1_700_000_000_500
export function hostWithParent(): AgentHookServer {
const host = new AgentHookServer()
host.ingestStructuredStatus(
{
sessionId: parent.sessionId,
workspaceId: parent.workspaceId,
agent: 'claude',
status: 'working',
hostExecutionOwned: true,
latestPrompt: 'find the flaky tests',
updatedAt: 100
},
parent
)
return host
}
/** With `host`, evidence goes through the host's own ingest instead of straight to reconciliation. */
export async function producer(host?: AgentHookServer) {
const claude = fakeClaude()
const store = createAgentStatusStore({ epoch: 'epoch-1', mode: 'authority' })
expect(store.applyMutation({ parent: { subject: parent } })).not.toBeNull()
const admission = createAgentChildWorkAdmission(store, {
mintChildWorkId: (() => {
let minted = 0
return () => `child-${++minted}`
})()
})
let clock = T0
const deliveries: Delivery[] = []
/** The producer linkage the journal stamped on each child row. */
const stamps: { providerParentRef?: string; attempt?: number }[] = []
const evidenceLog: AgentChildWorkEvidence[][] = []
const ingested: (AgentChildWorkReconcileOutcome | null)[] = []
const adapter = new ClaudeStructuredSessionAdapter({
resolveLaunch: async () => ({
pathToClaudeCodeExecutable: 'claude',
options: {},
cwd: '/work/repo',
claudeConfigDir: '/accounts/claude',
providerSessionId: PROVIDER_SESSION_ID,
resumeLeafUuid: null,
resumesTranscript: false,
cliFlag: async () => 'supported' as const,
continuesChain: false
}),
openConnection: claude.openConnection,
readProcessStartTime: async () => 1_700_000_000_000,
now: () => clock,
persistHandle: async () => {},
onChildWorkEvidence: (sessionId, evidence) => {
expect(sessionId).toBe('session-1')
deliveries.push({ kind: 'evidence', detail: evidence.map((edge) => edge.type).join(',') })
evidenceLog.push(evidence)
if (host) {
ingested.push(host.ingestStructuredChildWork(parent, evidence, 'claude'))
} else {
reconcileAgentChildWorkEvidence({ store, admission, parent, provider: 'claude', evidence })
}
}
})
const journalItems = new Map<string, JournaledItem>()
const journal: StructuredAgentSessionEventSink = {
appendItem: (identity, body, options) => {
deliveries.push({ kind: 'journal', detail: JSON.stringify(identity) })
const itemId = agentJournalItemKey(identity)
journalItems.set(itemId, {
itemId,
body,
sequence: journalItems.get(itemId)?.sequence ?? journalItems.size + 1,
...(options?.agentId ? { agentId: options.agentId } : {})
})
if (options?.agentId !== undefined) {
stamps.push(options)
}
},
appendTombstone: () => {},
// Production's journal publication is what republishes the parent's own row.
publish: () => deliveries.push({ kind: 'publish', detail: '' })
}
await adapter.acquire({
identity: identityFor(),
fence: 7,
spawnToken: 'spawn-9',
events: journal
})
const send = (message: Record<string, unknown>): Delivery[] => {
const from = deliveries.length
claude.connections[0]!.handlers.onMessage?.(message)
return deliveries.slice(from)
}
const replay = (frames: readonly CapturedFrame[]) => {
for (const { at, frame: captured } of frames) {
clock = T0 + at
send(frame(captured))
}
}
const records = (): AgentChildWorkRecord[] =>
host ? host.getStructuredChildWork(parent) : store.getChildren(parent)
const byDescription = (description: string) =>
records().find((record) => record.description === description)
return {
adapter,
claude,
now: () => clock,
store,
send,
replay,
records,
byDescription,
evidenceLog,
stamps,
ingested,
journalItems
}
}
@@ -1,77 +0,0 @@
// Close supplies no turn outcome; a prior observed exit keeps its own cause.
import { describe, expect, it } from 'vitest'
import type {
AgentJournalItemBody,
AgentJournalTurnLifecycle
} from '../../shared/agent-session/journal/agent-session-journal-types'
import { readAgentJournalTurn } from '../../shared/agent-session/lifecycle/agent-session-turn-record'
import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink'
import type { ClaudeStructuredSessionEvent } from './structured/claude-structured-session-state'
import {
PROVIDER_SESSION_ID,
adapterFor,
fakeClaude,
identityFor,
tick
} from './structured/claude-structured-session-test-support'
function turnSink() {
const turns: AgentJournalTurnLifecycle[] = []
const sink: StructuredAgentSessionEventSink = {
appendItem: (_identity, body: AgentJournalItemBody) => {
const turn = readAgentJournalTurn(body)
if (turn) {
turns.push(turn)
}
},
appendTombstone: () => {},
publish: () => {}
}
return { sink, turns }
}
async function childInsideTurn() {
const claude = fakeClaude()
const events: ClaudeStructuredSessionEvent[] = []
const adapter = adapterFor(claude, {}, events)
const { sink, turns } = turnSink()
await adapter.acquire({ identity: identityFor(), fence: 7, spawnToken: 'spawn-9', events: sink })
const connection = claude.connections[0]!
connection.handlers.onMessage?.({
session_id: PROVIDER_SESSION_ID,
type: 'assistant',
uuid: 'assistant-1',
parent_tool_use_id: null,
message: { role: 'assistant', content: [{ type: 'text', text: 'working' }] }
})
await tick()
expect(turns.at(-1)).toMatchObject({ state: 'running' })
return { adapter, connection, events, turns }
}
describe('a Claude close settles the open turn with no verdict of its own', () => {
it('ends it interrupted, with no outcome', async () => {
const { adapter, turns } = await childInsideTurn()
await expect(adapter.closeSession('session-1')).resolves.toBe(true)
expect(turns.at(-1)).toMatchObject({ state: 'interrupted' })
expect(turns.at(-1)).not.toHaveProperty('outcome')
})
it('settles a crash it saw before the close once, as that exit', async () => {
const { adapter, connection, events, turns } = await childInsideTurn()
connection.handlers.onExit?.(new Error('provider exited'))
await adapter.closeSession('session-1')
await tick()
const settled = turns.filter((turn) => turn.state !== 'running')
expect(settled).toEqual([expect.objectContaining({ state: 'interrupted' })])
expect(settled[0]).not.toHaveProperty('outcome')
expect(events.filter((event) => event.type === 'ended')).toEqual([
expect.objectContaining({ cause: 'unexpected-exit' })
])
})
})
@@ -1,119 +0,0 @@
import { describe, expect, it } from 'vitest'
import { selectStructuredAgentContextUsage } from '../../shared/agent-session/structured-agent-session-context-usage'
import { readAgentJournalTurn } from '../../shared/agent-session/lifecycle/agent-session-turn-record'
import { bindClaudeContextUsageCapture } from './claude-context-usage'
import {
assistantFrame,
initFrame,
resultFrame,
setup,
userFrame
} from './claude-context-usage-test-support'
const SONNET = 'claude-sonnet-5'
const OPUS = 'claude-opus-5-5'
// Shape measured from Claude Code 2.1.280: plan mode under `opusplan` keys Opus with `[1m]`.
const PLAN_USAGE = {
[SONNET]: { contextWindow: 200_000 },
[`${OPUS}[1m]`]: { contextWindow: 1_000_000 }
}
const answer = (model: string, totalTokens: number, rawMaxTokens: number) => ({
model,
totalTokens,
rawMaxTokens,
categories: []
})
function session(init: string) {
const t = setup({ init })
const pending: ((value: unknown) => void)[] = []
bindClaudeContextUsageCapture(
{ getContextUsage: () => new Promise((resolve) => pending.push(resolve)) },
t.translator,
{ now: () => 90_000 }
)
const settle = async (): Promise<void> => {
for (let index = 0; index < 4; index += 1) {
await Promise.resolve()
}
}
const reply = async (value: unknown, request = pending.length - 1): Promise<void> => {
pending[request]?.(value)
await settle()
}
const ring = () => selectStructuredAgentContextUsage(t.items())
const unknownWrites = () =>
t.appends.filter(
(entry) => readAgentJournalTurn(entry.body)?.contextUsage?.used?.kind === 'unknown'
).length
return { ...t, pending, reply, ring, unknownWrites }
}
describe('the context ring across a model change', () => {
it('holds estimates from the moment an approved plan hands the turn to another model', async () => {
const s = session(SONNET)
s.handle(userFrame('turn-a', 1_000))
s.handle(assistantFrame('reply-a', 2_000, 100_000, undefined, OPUS))
s.handle(resultFrame(3_000, PLAN_USAGE))
await s.reply(answer(`${OPUS}[1m]`, 101_000, 1_000_000))
s.handle(initFrame(SONNET, 3_900))
s.handle(userFrame('turn-b', 4_000))
s.handle(assistantFrame('reply-b1', 5_000, 110_000, undefined, OPUS))
expect(s.ring()).toMatchObject({ usedTokens: 110_000, windowTokens: 1_000_000 })
const requests = s.pending.length
s.handle(assistantFrame('reply-b2', 6_000, 120_000, undefined, SONNET))
expect(s.ring()).toBeNull()
expect(s.unknownWrites()).toBe(1)
expect(s.pending).toHaveLength(requests + 1)
s.handle(assistantFrame('reply-b3', 7_000, 130_000, undefined, SONNET))
expect(s.unknownWrites()).toBe(1)
expect(s.turnRow('turn-b')?.body).toMatchObject({ contextUsage: { used: { kind: 'unknown' } } })
await s.reply(answer(SONNET, 121_000, 200_000), requests)
expect(s.turnRow('turn-b')?.body).toMatchObject({
contextUsage: { window: { tokens: 200_000 }, used: { kind: 'unknown' } }
})
s.handle(assistantFrame('reply-b4', 7_500, 140_000, undefined, SONNET))
expect(s.ring()).toMatchObject({ usedTokens: 140_000, windowTokens: 200_000, percentage: 70 })
s.handle(resultFrame(8_000, PLAN_USAGE))
expect(s.ring()).toMatchObject({ usedTokens: 140_000, windowTokens: 200_000 })
await s.reply(answer(SONNET, 141_000, 200_000))
expect(s.ring()).toMatchObject({ usedTokens: 141_000, windowTokens: 200_000, estimated: false })
s.translator.dispose()
})
it('does not let a turn result undo the window a mid-turn switch between 1M and 200k reported', async () => {
const s = session(`${SONNET}[1m]`)
s.handle(userFrame('turn-a', 1_000))
s.handle(assistantFrame('reply-a', 2_000, 140_000, undefined, SONNET))
s.handle(resultFrame(3_000, { [`${SONNET}[1m]`]: { contextWindow: 1_000_000 } }))
await s.reply(answer(`${SONNET}[1m]`, 141_000, 1_000_000))
s.handle(initFrame(`${SONNET}[1m]`, 3_900))
s.handle(userFrame('turn-b', 4_000))
s.handle(assistantFrame('reply-b1', 5_000, 145_000, undefined, SONNET))
s.translator.modelMayHaveChanged()
const switched = s.pending.length - 1
s.handle(assistantFrame('reply-b2', 6_000, 150_000, undefined, SONNET))
await s.reply(answer(SONNET, 151_000, 200_000), switched)
s.handle(assistantFrame('reply-b3', 7_000, 160_000, undefined, SONNET))
expect(s.ring()).toMatchObject({ usedTokens: 160_000, windowTokens: 200_000, percentage: 80 })
s.handle(
resultFrame(8_000, {
[`${SONNET}[1m]`]: { contextWindow: 1_000_000 },
[SONNET]: { contextWindow: 200_000 }
})
)
expect(s.ring()).toMatchObject({ usedTokens: 160_000, windowTokens: 200_000, percentage: 80 })
s.translator.markContextActivity()
await s.reply(answer(SONNET, 161_000, 200_000))
s.handle(initFrame(SONNET, 8_900))
s.handle(userFrame('turn-c', 9_000))
s.handle(assistantFrame('reply-c', 10_000, 170_000, undefined, SONNET))
expect(s.ring()).toMatchObject({ usedTokens: 170_000, windowTokens: 200_000, percentage: 85 })
s.translator.dispose()
})
})
@@ -1,206 +0,0 @@
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { selectStructuredAgentContextUsage } from '../../shared/agent-session/structured-agent-session-context-usage'
import type { AgentSessionJournal } from '../native-chat/agent-session-journal/journal-store'
import { createTrackedJournalOpener } from '../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support'
import { createDeferredStructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink'
import '../native-chat/agent-session-wire/termination/structured-agent-session-dead-generation-settlement'
import { settleStaleStructuredAgentSessionState } from '../native-chat/agent-session-wire/termination/structured-agent-session-stale-state-settlement'
import { readAgentJournalTurn } from '../../shared/agent-session/lifecycle/agent-session-turn-record'
import { bindClaudeContextUsageCapture } from './claude-context-usage'
import { createClaudeJournalTranslator } from './structured/journal/claude-structured-journal-translation'
import { testEventSinkLogging } from '../native-chat/agent-session-wire/host/testing/structured-agent-session-logger-test-support'
import { claudeProviderHandle } from '../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding'
const journals = createTrackedJournalOpener()
let root: string
beforeEach(async () => {
root = await mkdtemp(join(tmpdir(), 'orca-claude-context-restart-'))
})
afterEach(async () => {
await journals.closeAll()
await rm(root, { recursive: true, force: true })
})
function frame(message: Record<string, unknown>, observedAt: number, startsTurn = false) {
return {
type: 'message' as const,
sessionId: 'orca-session',
observedAt,
...(startsTurn ? { startsTurn: true as const } : {}),
message: { session_id: 'claude-session', parent_tool_use_id: null, ...message }
}
}
const initFrame = (at: number) =>
frame({ type: 'system', subtype: 'init', uuid: `init-${at}`, model: 'claude-fable-5-1[1m]' }, at)
const userFrame = (uuid: string, at: number) =>
frame(
{ type: 'user', uuid, message: { role: 'user', content: [{ type: 'text', text: 'go' }] } },
at,
true
)
const assistantFrame = (uuid: string, at: number, input: number, model = 'claude-fable-5-1') =>
frame(
{
type: 'assistant',
uuid,
message: {
role: 'assistant',
model,
content: [{ type: 'text', text: uuid }],
usage: {
input_tokens: input,
cache_creation_input_tokens: 0,
cache_read_input_tokens: 0,
output_tokens: 4
}
}
},
at
)
const resultFrame = (at: number, contextWindow = 1_000_000) =>
frame(
{
type: 'result',
subtype: 'success',
is_error: false,
result: 'done',
duration_ms: 10,
uuid: `result-${at}`,
modelUsage: { 'claude-fable-5-1[1m]': { contextWindow } }
},
at
)
const compactBoundary = (at: number) =>
frame(
{
type: 'system',
subtype: 'compact_boundary',
uuid: `compact-${at}`,
compact_metadata: { trigger: 'manual', pre_tokens: 150_000 }
},
at
)
const postCompactionReport = {
model: 'claude-fable-5-1[1m]',
totalTokens: 40_000,
rawMaxTokens: 1_000_000,
percentage: 4,
categories: [{ name: 'Messages', tokens: 30_000 }]
}
async function openJournal(): Promise<AgentSessionJournal> {
return journals.open({
identity: {
sessionId: 'orca-session',
workspaceId: 'workspace-1',
hostId: 'local',
agent: 'claude',
providerHandle: claudeProviderHandle('claude-session', null)
},
now: () => 9_000,
stateDirectory: join(root, 'orca-session')
})
}
function acquire(journal: AgentSessionJournal) {
const deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging())
const translator = createClaudeJournalTranslator({ sink: deferred.sink, coalesceMs: 0 })
deferred.bind({ journal, fence: 1, publish: () => {} })
const answers: ((value: unknown) => void)[] = []
const unbind = bindClaudeContextUsageCapture(
{
getContextUsage: () => new Promise((resolve) => answers.push(resolve))
},
translator,
{ now: () => 20_000 }
)
const settle = async (): Promise<void> => {
for (let index = 0; index < 4; index += 1) {
await Promise.resolve()
}
await expect(deferred.drained()).resolves.toEqual({ ok: true })
}
const detach = (): void => deferred.unbind()
const reattach = (): void => deferred.bind({ journal, fence: 1, publish: () => {} })
const release = (): void => {
unbind?.()
translator.dispose()
deferred.close()
}
return { translator, answers, settle, detach, reattach, release }
}
const ring = (journal: AgentSessionJournal) =>
selectStructuredAgentContextUsage(journal.snapshot().items)
describe('context usage across a restart', () => {
it('resets the ring at a /compact that is the first thing after a restart, then reads the fresh report', async () => {
const journal = await openJournal()
const before = acquire(journal)
before.translator.handle(initFrame(900))
before.translator.handle(userFrame('turn-a', 1_000))
before.translator.handle(assistantFrame('reply-a', 2_000, 150_000))
before.translator.handle(resultFrame(3_000))
await before.settle()
expect(ring(journal)).toMatchObject({ usedTokens: 150_000, windowTokens: 1_000_000 })
before.release()
const after = acquire(journal)
after.translator.handle(compactBoundary(10_000))
await after.settle()
expect(ring(journal)).toBeNull()
after.translator.handle(resultFrame(11_000))
await after.settle()
expect(ring(journal)).toBeNull()
after.answers.at(-1)?.(postCompactionReport)
await after.settle()
expect(ring(journal)).toMatchObject({
usedTokens: 40_000,
windowTokens: 1_000_000,
estimated: false,
categories: [{ name: 'Messages', tokens: 30_000 }]
})
after.release()
})
it('never brings a settled turn back to running with a context write that ran late', async () => {
const journal = await openJournal()
const live = acquire(journal)
live.translator.handle(initFrame(900))
live.translator.handle(userFrame('turn-a', 1_000))
live.translator.handle(assistantFrame('reply-a', 2_000, 20_000))
await live.settle()
live.detach()
live.translator.handle(assistantFrame('reply-a2', 3_000, 30_000))
await settleStaleStructuredAgentSessionState({
journal,
sessionId: 'orca-session',
fence: 1,
acquisitionGeneration: 'next',
deathEvidence: null
})
live.reattach()
await live.settle()
const turn = journal
.snapshot()
.items.map((item) => readAgentJournalTurn(item.body))
.find(Boolean)
expect(turn).toMatchObject({
state: 'unverifiable',
contextUsage: { used: { kind: 'estimate', usage: { inputTokens: 30_000 } } }
})
live.release()
})
})
@@ -1,187 +0,0 @@
import { vi } from 'vitest'
import type {
AgentJournalItemBody,
AgentJournalRenderItem
} from '../../shared/agent-session/journal/agent-session-journal-types'
import type { AgentJournalItemIdentity } from '../../shared/agent-session/journal/agent-session-journal-identity'
import { agentJournalItemKey } from '../../shared/agent-session/journal/agent-session-journal-item-key'
import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink'
import type { StructuredAgentSessionRevisionJournal } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-journal-views'
import { createJournalReducerState } from '../native-chat/agent-session-journal/projection/journal-reducer'
import { personStopDecidesTurn } from '../native-chat/agent-session-journal/context-epochs/journal-stop-turn-end'
import type { ClaudeContextReportTarget } from './claude-context-facts'
import { createClaudeJournalTranslator } from './structured/journal/claude-structured-journal-translation'
import { claudeTurnLifecycleIdentity } from './claude-turn-lifecycle-item'
export function journal({ deferred = false } = {}) {
const queued: (() => void)[] = []
const run = (write: () => void): void => {
if (deferred) {
queued.push(write)
} else {
write()
}
}
const flush = (): void => {
while (queued.length) {
queued.shift()!()
}
}
const clock = { now: 0 }
const appends: { identity: AgentJournalItemIdentity; body: AgentJournalItemBody }[] = []
const rows = new Map<string, AgentJournalRenderItem>()
const appendItem: StructuredAgentSessionEventSink['appendItem'] = (identity, body, options) => {
appends.push({ identity, body })
const itemId = agentJournalItemKey(identity)
const existing = rows.get(itemId)
rows.set(itemId, {
itemId,
revision: (existing?.revision ?? 0) + 1,
sequence: existing?.sequence ?? rows.size + 1,
observedAt: existing?.observedAt ?? options?.observedAt ?? clock.now,
...options,
turnScope: existing?.turnScope ?? options.turnScope,
body
})
}
const scans = { count: 0 }
const bound: StructuredAgentSessionRevisionJournal = {
item: (itemId) => rows.get(itemId) ?? null,
epoch: 'test',
visitItems: (visit) => {
scans.count += 1
for (const row of rows.values()) {
visit(row.itemId, row.sequence, row.body)
}
},
itemBody: (itemId) => rows.get(itemId)?.body ?? null
}
const revise: NonNullable<StructuredAgentSessionEventSink['tryReviseResolvedItemAndPublish']> = (
_reservedBytes,
resolve,
options
) => {
run(() => {
const resolved = resolve(bound)
if (resolved) {
appendItem(resolved.identity, resolved.body, options)
}
})
return { accepted: true }
}
const stopState = createJournalReducerState('orca-session', 'test')
const queueStop = (turnId: string, at: number): void =>
run(() => {
stopState.queuePauseMarks.latestStop = {
sequence: rows.size + 1,
event: { reason: 'user-stop', turnId, at }
}
})
const sink: StructuredAgentSessionEventSink = {
journalStopDecidesTurn: (turnId, at) => personStopDecidesTurn(stopState, turnId, at),
appendItem: (...args) => run(() => appendItem(...args)),
tryReviseResolvedItem: revise,
tryReviseResolvedItemAndPublish: revise,
appendTombstone: () => {},
publish: vi.fn()
}
const turnRow = (turnId: string) =>
rows.get(agentJournalItemKey(claudeTurnLifecycleIdentity('claude-session', turnId)))
const items = () => [...rows.values()].sort((left, right) => left.sequence - right.sequence)
return { sink, clock, appends, rows, turnRow, items, scans, flush, queueStop }
}
export function frame(message: Record<string, unknown>, observedAt: number, startsTurn = false) {
return {
type: 'message' as const,
sessionId: 'orca-session',
observedAt,
...(startsTurn ? { startsTurn: true as const } : {}),
message: { session_id: 'claude-session', parent_tool_use_id: null, ...message }
}
}
export const userFrame = (uuid: string, at: number) =>
frame(
{ type: 'user', uuid, message: { role: 'user', content: [{ type: 'text', text: 'go' }] } },
at,
true
)
export function assistantFrame(
uuid: string,
at: number,
input: number,
parentToolUseId?: string,
model = 'claude-fable-5-1',
content: unknown[] = [{ type: 'text', text: uuid }]
) {
return frame(
{
type: 'assistant',
uuid,
...(parentToolUseId ? { parent_tool_use_id: parentToolUseId } : {}),
message: {
role: 'assistant',
model,
content,
usage: {
input_tokens: input,
cache_creation_input_tokens: 0,
cache_read_input_tokens: 0,
output_tokens: 4
}
}
},
at
)
}
export const resultFrame = (at: number, modelUsage: Record<string, unknown> = {}) =>
frame(
{
type: 'result',
subtype: 'success',
is_error: false,
result: 'done',
duration_ms: 10,
uuid: `result-${at}`,
modelUsage
},
at
)
export const initFrame = (model: string, at: number) =>
frame({ type: 'system', subtype: 'init', uuid: `init-${at}`, model }, at)
export const compactBoundary = (at: number) =>
frame(
{
type: 'system',
subtype: 'compact_boundary',
uuid: `compact-${at}`,
compact_metadata: { trigger: 'auto', pre_tokens: 150_000 }
},
at
)
export const turnIdentity = (turnId: string) =>
claudeTurnLifecycleIdentity('claude-session', turnId)
export function setup({
init = 'claude-fable-5-1[1m]',
deferred = false
}: { init?: string | null; deferred?: boolean } = {}) {
const state = journal({ deferred })
const translator = createClaudeJournalTranslator({ sink: state.sink, coalesceMs: 0 })
const requests: ClaudeContextReportTarget[] = []
translator.subscribeContextUsageRequests((target) => requests.push(target))
const handle = (event: Parameters<typeof translator.handle>[0]): void => {
state.clock.now = event.type === 'message' ? (event.observedAt ?? 0) : 0
translator.handle(event)
}
if (init) {
handle(initFrame(init, 500))
}
return { ...state, translator, requests, handle }
}
@@ -1,236 +0,0 @@
import { agentSessionConversationView } from '../../shared/agent-session/lifecycle/agent-session-conversation-view'
import {
agentSessionLeaseFixture,
agentSessionRecordFixture
} from '../../shared/agent-session/lifecycle/agent-session-record.test-fixture'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import type { AgentSessionHistoryPage } from '../../shared/agent-session/agent-session-wire'
import { readAgentJournalTurn } from '../../shared/agent-session/lifecycle/agent-session-turn-record'
import { MAX_RETAINED_OWN_ITEMS } from '../../shared/agent-session/view/structured-agent-session-item-retention'
import { selectStructuredAgentContextUsage } from '../../shared/agent-session/structured-agent-session-context-usage'
import {
EMPTY_STRUCTURED_AGENT_SESSION,
reduceStructuredAgentSession,
type StructuredAgentSessionState
} from '../../shared/agent-session/structured-agent-session-reducer'
import type { AgentSessionJournal } from '../native-chat/agent-session-journal/journal-store'
import { createTrackedJournalOpener } from '../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support'
import { readAgentSessionHistory } from '../native-chat/agent-session-wire/publication/history/agent-session-history-page'
import { createDeferredStructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink'
import type { StructuredAgentSessionMutationContext } from '../native-chat/agent-session-wire/operations/structured-agent-session-mutation-context'
import { readStructuredAgentSessionOptions } from '../native-chat/agent-session-wire/options/structured-agent-session-options-read'
import {
assistantFrame,
initFrame,
resultFrame,
userFrame
} from './claude-context-usage-test-support'
import { createClaudeJournalTranslator } from './structured/journal/claude-structured-journal-translation'
import { testEventSinkLogging } from '../native-chat/agent-session-wire/host/testing/structured-agent-session-logger-test-support'
import { claudeProviderHandle } from '../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding'
import { claudeAndCodexAgents } from '../native-chat/agent-session-wire/providers/testing/structured-agent-session-adapter-router-test-support'
import type { StructuredAgentRegistry } from '../native-chat/agent-session-wire/providers/structured-agent-registry'
const SESSION = 'orca-session'
const journals = createTrackedJournalOpener()
let root: string
beforeEach(async () => {
root = await mkdtemp(join(tmpdir(), 'orca-claude-context-unloaded-'))
})
afterEach(async () => {
await journals.closeAll()
await rm(root, { recursive: true, force: true })
})
async function openJournal(): Promise<AgentSessionJournal> {
return journals.open({
identity: {
sessionId: SESSION,
workspaceId: 'workspace-1',
hostId: 'local',
agent: 'claude',
providerHandle: claudeProviderHandle('claude-session', null)
},
now: () => 9_000,
stateDirectory: join(root, SESSION)
})
}
function translate(journal: AgentSessionJournal) {
const deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging())
const translator = createClaudeJournalTranslator({ sink: deferred.sink, coalesceMs: 0 })
deferred.bind({ journal, fence: 1, publish: () => {} })
const settle = async (): Promise<void> => {
await expect(deferred.drained()).resolves.toEqual({ ok: true })
}
return { translator, settle }
}
function runTurn(
translator: ReturnType<typeof translate>['translator'],
turnId: string,
at: number,
sizes: number[]
): void {
translator.handle(initFrame('claude-fable-5-1[1m]', at - 100))
translator.handle(userFrame(turnId, at))
sizes.forEach((size, index) => {
translator.handle(assistantFrame(`${turnId}-reply-${index}`, at + 100 * (index + 1), size))
})
}
function readOptions(journal: AgentSessionJournal, agents: StructuredAgentRegistry) {
const running = {
journal,
child: { fence: 1, generation: 'generation-1' },
params: { provider: 'claude' }
}
const record = {
...agentSessionRecordFixture(agentSessionLeaseFixture({ sessionId: SESSION, runtimeFence: 1 })),
options: { model: 'opus' }
}
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the options read touches only these members.
const context = {
deps: {
adapter: {
readOptions: async () => ({ models: [], current: { model: 'opus' } })
},
agents,
store: {
requireWritableRecord: () => record,
getConversation: () => agentSessionConversationView(record)
}
},
serialize: (_sessionId: string, task: () => Promise<unknown>) => task(),
openConversation: async () => running,
conversation: async () => running,
sessions: new Map([[SESSION, running]])
} as unknown as StructuredAgentSessionMutationContext
return readStructuredAgentSessionOptions(context, SESSION, { readsWithoutModel: true })
}
function attachTail(journal: AgentSessionJournal, limit: number): StructuredAgentSessionState {
const read = readAgentSessionHistory(journal, { sessionId: SESSION, direction: 'tail', limit })
if (!read.ok) {
throw new Error('tail read failed')
}
return reduceStructuredAgentSession(EMPTY_STRUCTURED_AGENT_SESSION, {
type: 'event',
event: { type: 'snapshot', sessionId: SESSION, fence: 1, page: read.page }
})
}
function applyLive(
journal: AgentSessionJournal,
state: StructuredAgentSessionState
): StructuredAgentSessionState {
const read = readAgentSessionHistory(journal, {
sessionId: SESSION,
direction: 'after',
cursor: state.cursor ?? undefined
})
if (!read.ok) {
throw new Error('live read failed')
}
const page: AgentSessionHistoryPage = read.page
return reduceStructuredAgentSession(state, {
type: 'event',
event: {
type: 'batch',
sessionId: SESSION,
batch: {
cursor: page.window.nextCursor,
items: page.items,
removedItemIds: page.removedItemIds,
submissions: page.submissions
}
}
})
}
const hasTurnRow = (state: StructuredAgentSessionState): boolean =>
state.items.some((item) => readAgentJournalTurn(item.body) !== null)
function catchUp(
journal: AgentSessionJournal,
state: StructuredAgentSessionState
): StructuredAgentSessionState {
let next = applyLive(journal, state)
while (next.cursor?.sequence !== state.cursor?.sequence) {
state = next
next = applyLive(journal, state)
}
return next
}
describe('context usage for a turn row outside the loaded page', () => {
it('marks a live context write on a turn row the window cannot take, and the host answer carries it', async () => {
const journal = await openJournal()
const { translator, settle } = translate(journal)
runTurn(translator, 'turn-a', 1_000, [120_000, 130_000, 140_000, 150_000])
translator.handle(resultFrame(2_000, { 'claude-fable-5-1[1m]': { contextWindow: 1_000_000 } }))
runTurn(translator, 'turn-b', 3_000, [200_000, 210_000, 220_000, 230_000])
await settle()
const attached = attachTail(journal, 3)
expect(hasTurnRow(attached)).toBe(false)
expect(attached.unloadedTurnRevisions).toBeUndefined()
translator.handle(assistantFrame('turn-b-reply-late', 4_000, 250_000))
await settle()
const live = applyLive(journal, attached)
expect(hasTurnRow(live)).toBe(false)
expect(live.unloadedTurnRevisions).toBe(1)
const options = await readOptions(journal, claudeAndCodexAgents())
expect(
selectStructuredAgentContextUsage(live.items, options.contextUsage?.current)
).toMatchObject({ usedTokens: 250_000, windowTokens: 1_000_000 })
})
it('keeps the ring on the newest facts while a live turn outgrows the retained window', async () => {
const journal = await openJournal()
const { translator, settle } = translate(journal)
runTurn(translator, 'turn-a', 1_000, [120_000])
translator.handle(resultFrame(2_000, { 'claude-fable-5-1[1m]': { contextWindow: 1_000_000 } }))
runTurn(translator, 'turn-b', 3_000, [])
await settle()
const hostAnswer = async () =>
(await readOptions(journal, claudeAndCodexAgents())).contextUsage?.current
let state = attachTail(journal, 200)
let host = await hostAnswer()
const respond = (index: number): void => {
translator.handle(assistantFrame(`turn-b-reply-${index}`, 4_000 + index, 200_000 + index))
}
let index = 0
for (; index < MAX_RETAINED_OWN_ITEMS - 20; index += 1) {
respond(index)
if (index % 100 === 99) {
await settle()
}
}
await settle()
state = catchUp(journal, state)
expect(hasTurnRow(state)).toBe(true)
let stepsAfterTrim = 0
while (stepsAfterTrim < 5 && index < 3_000) {
respond(index++)
await settle()
const seen = state.unloadedTurnRevisions
state = catchUp(journal, state)
if (state.unloadedTurnRevisions !== seen) {
host = await hostAnswer()
}
expect(selectStructuredAgentContextUsage(state.items, host)).toEqual(
selectStructuredAgentContextUsage(journal.snapshot().items)
)
stepsAfterTrim += hasTurnRow(state) ? 0 : 1
}
expect(hasTurnRow(state)).toBe(false)
})
})
@@ -1,105 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import { terminateDescendantSnapshotWithVerdict } from '../pty/process-retirement/pty-descendant-exit-verification'
import {
collectDescendantRows,
type DescendantSnapshot
} from '../pty/process-retirement/pty-descendant-termination'
import type { ProcessTableRow } from '../pty/process-retirement/pty-process-table-parser'
import { createClaudeChildTreeReaper } from './claude-agent-sdk-exit-proof'
const ROOT_PID = 500
const ORCA_PGID = 400
const ROOT_STARTED_AT = 'Thu Sep 3 18:04:50 2026'
const WALK_SECOND = 'Thu Sep 3 18:05:04 2026'
const WALK_MS = Date.parse(WALK_SECOND)
const EARLIER_SECOND = 'Thu Sep 3 18:05:03 2026'
/** The measured split: `s20` at :03.946 died, `s21` at :04.042 leaked. */
const EARLIER_BORN = [700, 701, 702]
const WALK_SECOND_BORN = [721, 722, 723, 724]
type Cohort = { pids: number[]; startedAt: string }
const LIVE_TREE: Cohort[] = [
{ pids: EARLIER_BORN, startedAt: EARLIER_SECOND },
{ pids: WALK_SECOND_BORN, startedAt: WALK_SECOND }
]
function rowsFor(cohorts: Cohort[]): ProcessTableRow[] {
return [
{ pid: ROOT_PID, ppid: 1, pgid: ORCA_PGID, startedAt: ROOT_STARTED_AT },
...cohorts.flatMap((cohort) =>
cohort.pids.map((pid) => ({
pid,
ppid: ROOT_PID,
pgid: ORCA_PGID,
startedAt: cohort.startedAt
}))
)
]
}
function walk(capturedAtMs: number, cohorts: Cohort[] = LIVE_TREE): DescendantSnapshot {
return collectDescendantRows(ROOT_PID, rowsFor(cohorts), capturedAtMs)
}
function killedPids(calls: [number, NodeJS.Signals][]): number[] {
return calls.flatMap(([pid, signal]) => (signal === 'SIGKILL' ? [pid] : [])).sort((a, b) => a - b)
}
function signalledPids(calls: [number, NodeJS.Signals][]): number[] {
return calls.flatMap(([pid, signal]) => (signal === 'SIGTERM' ? [pid] : [])).sort((a, b) => a - b)
}
/** Descendants survive SIGTERM in the mock table, forcing the real verifier to escalate. */
async function sweep(
captures: DescendantSnapshot[],
liveTree: Cohort[] = LIVE_TREE
): Promise<[number, NodeJS.Signals][]> {
const calls: [number, NodeJS.Signals][] = []
const captureDescendants = vi.fn()
for (const capture of captures) {
captureDescendants.mockResolvedValueOnce(capture)
}
const tree = createClaudeChildTreeReaper(
{ pid: ROOT_PID, kill: vi.fn(() => true) },
{
site: 'claude-structured-child-close',
platform: 'linux',
exited: () => false,
captureDescendants,
terminateDescendants: (snapshot) =>
terminateDescendantSnapshotWithVerdict(snapshot, {
requireIdentityBeforeSignal: true,
graceMs: 0,
verifyMs: 120,
sendSignal: (pid, signal) => calls.push([pid, signal]),
readTable: async () => ({ rows: rowsFor(liveTree), capturedAtMs: Date.now() })
})
}
)
await tree.capture()
await tree.refresh?.()
await tree.reap()
return calls
}
describe('Claude descendant forced-sweep fence', () => {
it('escalates a descendant forked in the same second as both close walks', async () => {
const calls = await sweep([walk(WALK_MS + 42), walk(WALK_MS + 140)])
expect(signalledPids(calls)).toEqual([...EARLIER_BORN, ...WALK_SECOND_BORN])
expect(killedPids(calls)).toEqual([...EARLIER_BORN, ...WALK_SECOND_BORN])
})
it('withholds the sweep from a row no walk re-derived, on its start second alone', async () => {
const retained = { pids: [900], startedAt: WALK_SECOND }
const firstWalk = walk(WALK_MS + 42, [...LIVE_TREE, retained])
const refresh = walk(WALK_MS + 140)
const calls = await sweep([firstWalk, refresh], [...LIVE_TREE, retained])
expect(signalledPids(calls)).toEqual([...EARLIER_BORN, ...WALK_SECOND_BORN, 900])
expect(killedPids(calls)).toEqual([...EARLIER_BORN, ...WALK_SECOND_BORN])
})
})
@@ -1,177 +0,0 @@
// Rebuild fold-steer captures with only dispatch and turn fields.
export type CapturedFoldFrame = { at: number; frame: Record<string, unknown> }
export type FoldCaptureIds = {
sessionId: string
/** Turn-opening client UUID adopted by the replay. */
first: string
steer: string
/** Present only for two-steer captures. */
secondSteer?: string
}
export function userReplay(
at: number,
sessionId: string,
uuid: string,
text: string
): CapturedFoldFrame {
return {
at,
frame: {
type: 'user',
session_id: sessionId,
parent_tool_use_id: null,
uuid,
isReplay: true,
message: { role: 'user', content: [{ type: 'text', text }] }
}
}
}
export function assistant(
at: number,
sessionId: string,
uuid: string,
content: unknown[],
userMessageUuids?: string[]
): CapturedFoldFrame {
return {
at,
frame: {
type: 'assistant',
session_id: sessionId,
parent_tool_use_id: null,
uuid,
message: { id: `msg-${uuid}`, role: 'assistant', content },
...(userMessageUuids && userMessageUuids.length > 0
? { user_message_uuid: userMessageUuids[0], user_message_uuids: userMessageUuids }
: {})
}
}
}
export function assistantToolUse(
at: number,
sessionId: string,
uuid: string,
toolUseId: string,
userMessageUuids?: string[]
): CapturedFoldFrame {
return assistant(
at,
sessionId,
uuid,
[{ type: 'tool_use', id: toolUseId, name: 'Bash', input: { command: 'sleep 5' } }],
userMessageUuids
)
}
export function assistantText(
at: number,
sessionId: string,
uuid: string,
text: string,
userMessageUuids?: string[]
): CapturedFoldFrame {
return assistant(at, sessionId, uuid, [{ type: 'text', text }], userMessageUuids)
}
export function toolResult(
at: number,
sessionId: string,
uuid: string,
toolUseId: string,
content = '(Bash completed with no output)',
isError = false
): CapturedFoldFrame {
return {
at,
frame: {
type: 'user',
session_id: sessionId,
parent_tool_use_id: null,
uuid,
message: {
role: 'user',
content: [{ type: 'tool_result', tool_use_id: toolUseId, content, is_error: isError }]
}
}
}
}
export function resultFrame(
at: number,
sessionId: string,
uuid: string,
fields: {
userMessageUuids: string[]
durationMs: number
numTurns: number
subtype?: string
isError?: boolean
terminalReason?: string
}
): CapturedFoldFrame {
return {
at,
frame: {
type: 'result',
subtype: fields.subtype ?? 'success',
session_id: sessionId,
uuid,
is_error: fields.isError ?? false,
terminal_reason: fields.terminalReason ?? 'completed',
duration_ms: fields.durationMs,
num_turns: fields.numTurns,
result: 'FIRST DONE',
...(fields.userMessageUuids.length > 0
? {
user_message_uuid: fields.userMessageUuids[0],
user_message_uuids: fields.userMessageUuids
}
: {})
}
}
}
export function sessionIdle(at: number, sessionId: string): CapturedFoldFrame {
return {
at,
frame: {
type: 'system',
subtype: 'session_state_changed',
state: 'idle',
session_id: sessionId,
uuid: `ssc-idle-${at}`
}
}
}
/** Root init marks each request cycle, including background wakes and manual compaction (p3 captures). */
export function initFrame(at: number, sessionId: string): CapturedFoldFrame {
return {
at,
frame: {
type: 'system',
subtype: 'init',
session_id: sessionId,
uuid: `init-${at}`,
model: 'claude-sonnet-5',
apiKeySource: 'none'
}
}
}
export function taskFrame(
at: number,
sessionId: string,
subtype: string,
fields: Record<string, unknown>
): CapturedFoldFrame {
return {
at,
frame: { type: 'system', subtype, session_id: sessionId, uuid: `${subtype}-${at}`, ...fields }
}
}
@@ -1,272 +0,0 @@
// Replay orders captured from Claude CLI 2.1.280; synthetic boundary cases are labeled separately.
import { describe, expect, it, vi, type Mock } from 'vitest'
import type {
AgentJournalItemBody,
AgentJournalMessageItem
} from '../../shared/agent-session/journal/agent-session-journal-types'
import type { AgentJournalItemIdentity } from '../../shared/agent-session/journal/agent-session-journal-identity'
import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink'
import { readAgentJournalTurn } from '../../shared/agent-session/lifecycle/agent-session-turn-record'
import { ClaudeStructuredSessionAdapter } from './structured/claude-structured-session-adapter'
import type {
ClaudeStructuredSessionAdapterDeps,
ClaudeStructuredSessionEvent
} from './structured/claude-structured-session-state'
import type { ClaudeStructuredLaunch } from './structured/launch/claude-structured-launch-resolution'
import {
fakeClaude,
identityFor,
PROVIDER_SESSION_ID
} from './structured/claude-structured-session-test-support'
import { claudeStartupSettled } from './structured/claude-structured-startup-settled-test-support'
import {
assistantText,
initFrame,
resultFrame,
userReplay,
type CapturedFoldFrame
} from './claude-fold-steer-frame-builders.test-fixture'
import {
FIRST_PROMPT,
SECOND_STEER_PROMPT,
STEER_PROMPT,
twoSteersCapture,
TWO_STEERS_SEND_AT
} from './claude-captured-fold-steer-frames.test-fixture'
const T0 = 1_700_000_100_000
type Rig = {
adapter: ClaudeStructuredSessionAdapter
claude: ReturnType<typeof fakeClaude>
events: ClaudeStructuredSessionEvent[]
settled: Mock
turns: () => NonNullable<ReturnType<typeof readAgentJournalTurn>>[]
deliver: (captured: CapturedFoldFrame) => void
/** Dispatch at the capture offset and return the client UUID adopted by the CLI. */
dispatchAt: (at: number, clientMessageId: string, text: string) => Promise<string>
}
async function riggedAdapter(
launch: Partial<ClaudeStructuredLaunch> = {},
claudeOptions: Parameters<typeof fakeClaude>[0] = {}
): Promise<Rig> {
let nowMs = T0
const appended: { identity: AgentJournalItemIdentity; body: AgentJournalItemBody }[] = []
const sink: StructuredAgentSessionEventSink = {
appendItem: (identity, body) => appended.push({ identity, body }),
appendTombstone: () => {},
publish: () => {}
}
const events: ClaudeStructuredSessionEvent[] = []
const settled = vi.fn()
const claude = fakeClaude({ replayUuid: null, ...claudeOptions })
const deps: ClaudeStructuredSessionAdapterDeps = {
resolveLaunch: async () => ({
pathToClaudeCodeExecutable: 'claude',
options: {},
cwd: '/work/repo',
claudeConfigDir: '/accounts/claude',
providerSessionId: PROVIDER_SESSION_ID,
resumeLeafUuid: null,
resumesTranscript: false,
cliFlag: async () => 'supported' as const,
continuesChain: false,
...launch
}),
onEvent: (event) => events.push(event),
openConnection: claude.openConnection,
readProcessStartTime: async () => T0 - 1_000,
now: () => nowMs,
persistHandle: async () => {},
onDispatchSettledLate: settled
}
const adapter = new ClaudeStructuredSessionAdapter(deps)
await adapter.acquire({ identity: identityFor(), fence: 7, spawnToken: 'spawn-9', events: sink })
await claudeStartupSettled(adapter, 'session-1')
return {
adapter,
claude,
events,
settled,
turns: () =>
appended.flatMap((item) => {
const turn = readAgentJournalTurn(item.body)
return turn ? [turn] : []
}),
deliver: (captured) => {
nowMs = T0 + captured.at
claude.connections[0]!.handlers.onMessage?.(captured.frame)
},
dispatchAt: async (at, clientMessageId, text) => {
nowMs = T0 + at
const body: AgentJournalMessageItem = {
kind: 'message',
role: 'user',
blocks: [{ type: 'text', text }]
}
const outcome = await adapter.dispatch({
sessionId: 'session-1',
clientMessageId,
body,
requestedAt: nowMs,
fence: 7
})
expect(outcome).toMatchObject({ state: 'admitted' })
const sentUuid = claude.connections[0]!.sent.at(-1)?.uuid
if (typeof sentUuid !== 'string') {
throw new Error('the fake connection recorded no sent uuid')
}
return sentUuid
}
}
}
function replayEventFor(events: ClaudeStructuredSessionEvent[], uuid: string) {
return events.find(
(event) =>
event.type === 'message' && event.message.type === 'user' && event.message.uuid === uuid
)
}
describe('Claude fold receipt for a mid-turn send (captured orders)', () => {
it('two-steers: both folded sends settle individually inside the one turn', async () => {
const rig = await riggedAdapter()
const first = await rig.dispatchAt(TWO_STEERS_SEND_AT.first, 'client-first', FIRST_PROMPT)
const framesFor = (steerUuid: string, secondSteerUuid: string) =>
twoSteersCapture({
sessionId: PROVIDER_SESSION_ID,
first,
steer: steerUuid,
secondSteer: secondSteerUuid
})
for (const captured of framesFor('pending', 'pending-2')) {
if (captured.at < TWO_STEERS_SEND_AT.steer) {
rig.deliver(captured)
}
}
const steer = await rig.dispatchAt(TWO_STEERS_SEND_AT.steer, 'client-steer', STEER_PROMPT)
const secondSteer = await rig.dispatchAt(
TWO_STEERS_SEND_AT.secondSteer,
'client-steer-2',
SECOND_STEER_PROMPT
)
for (const captured of framesFor(steer, secondSteer)) {
if (captured.at > TWO_STEERS_SEND_AT.secondSteer) {
rig.deliver(captured)
}
}
expect([...new Set(rig.turns().map((turn) => turn.turnId))]).toEqual([first])
expect(rig.turns().every((turn) => turn.state !== 'interrupted')).toBe(true)
expect(rig.settled).toHaveBeenCalledWith({
sessionId: 'session-1',
clientMessageId: 'client-steer',
providerIdentity: { provider: 'claude', sessionId: PROVIDER_SESSION_ID, uuid: steer }
})
expect(rig.settled).toHaveBeenCalledWith({
sessionId: 'session-1',
clientMessageId: 'client-steer-2',
providerIdentity: { provider: 'claude', sessionId: PROVIDER_SESSION_ID, uuid: secondSteer }
})
})
it('mid-turn auto-compaction emits no root init, so a steer after the boundary still folds', async () => {
// Captured with forced auto-compaction (p4): compacting, boundary, and synthetic continuation have no root init.
const rig = await riggedAdapter()
const first = await rig.dispatchAt(14, 'client-first', FIRST_PROMPT)
rig.deliver(initFrame(234, PROVIDER_SESSION_ID))
rig.deliver(userReplay(2_437, PROVIDER_SESSION_ID, first, FIRST_PROMPT))
rig.deliver(assistantText(2_864, PROVIDER_SESSION_ID, 'reply-1', 'reading files'))
rig.deliver({
at: 11_518,
frame: {
type: 'system',
subtype: 'status',
status: 'compacting',
session_id: PROVIDER_SESSION_ID,
uuid: 'status-compacting-1'
}
})
rig.deliver({
at: 26_584,
frame: {
type: 'system',
subtype: 'compact_boundary',
session_id: PROVIDER_SESSION_ID,
uuid: 'compact-boundary-1',
compact_metadata: { trigger: 'auto', pre_tokens: 69_960, post_tokens: 9_311 }
}
})
rig.deliver({
at: 26_585,
frame: {
type: 'user',
session_id: PROVIDER_SESSION_ID,
parent_tool_use_id: null,
uuid: 'continuation-1',
isSynthetic: true,
message: {
role: 'user',
content: [{ type: 'text', text: 'This session is being continued.' }]
}
}
})
const steer = await rig.dispatchAt(26_987, 'client-steer', STEER_PROMPT)
rig.deliver(userReplay(34_601, PROVIDER_SESSION_ID, steer, STEER_PROMPT))
rig.deliver(assistantText(37_824, PROVIDER_SESSION_ID, 'reply-2', 'FIRST DONE banana'))
rig.deliver(
resultFrame(37_828, PROVIDER_SESSION_ID, 'result-1', {
userMessageUuids: [first, steer],
durationMs: 37_616,
numTurns: 6
})
)
expect([...new Set(rig.turns().map((turn) => turn.turnId))]).toEqual([first])
expect(rig.turns().every((turn) => turn.state !== 'interrupted')).toBe(true)
expect(replayEventFor(rig.events, steer)).not.toHaveProperty('startsTurn')
expect(rig.settled).toHaveBeenCalledWith({
sessionId: 'session-1',
clientMessageId: 'client-steer',
providerIdentity: { provider: 'claude', sessionId: PROVIDER_SESSION_ID, uuid: steer }
})
})
})
describe('Claude fold receipt boundaries (synthetic orders)', () => {
it('a fresh replay uuid with user_message_uuid correlation keeps the opener path, not a fold receipt', async () => {
const rig = await riggedAdapter()
const uuidA = await rig.dispatchAt(10, 'client-a', 'first prompt')
rig.deliver(userReplay(1_000, PROVIDER_SESSION_ID, uuidA, 'first prompt'))
const uuidB = await rig.dispatchAt(1_500, 'client-b', STEER_PROMPT)
const fresh = userReplay(2_000, PROVIDER_SESSION_ID, 'fresh-turn-2', STEER_PROMPT)
rig.deliver({ ...fresh, frame: { ...fresh.frame, user_message_uuid: uuidB } })
expect([...new Set(rig.turns().map((turn) => turn.turnId))]).toEqual([uuidA, 'fresh-turn-2'])
expect(replayEventFor(rig.events, 'fresh-turn-2')).toMatchObject({ startsTurn: true })
expect(rig.settled).toHaveBeenCalledWith({
sessionId: 'session-1',
clientMessageId: 'client-b',
providerIdentity: { provider: 'claude', sessionId: PROVIDER_SESSION_ID, uuid: 'fresh-turn-2' }
})
})
it('plural result uuids: a result naming only settled sends does not claim an unnamed live waiter by queue order', async () => {
const rig = await riggedAdapter()
const uuidA = await rig.dispatchAt(10, 'client-a', 'first prompt')
rig.deliver(userReplay(1_000, PROVIDER_SESSION_ID, uuidA, 'first prompt'))
await rig.dispatchAt(1_500, 'client-b', STEER_PROMPT)
rig.deliver(
resultFrame(5_000, PROVIDER_SESSION_ID, 'result-1', {
userMessageUuids: [uuidA],
durationMs: 4_990,
numTurns: 1
})
)
expect(rig.settled).not.toHaveBeenCalledWith(
expect.objectContaining({ clientMessageId: 'client-b' })
)
})
})
@@ -1,68 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import { runProcess } from '@orca/process-host'
import { readManagedHookDetectionResult } from '../agent-hooks/installation/managed-hook-detection-commands'
import { getClaudeManagedHookPlan } from './claude-managed-hook-events'
vi.mock('@orca/process-host', () => ({ runProcess: vi.fn() }))
import { parseClaudeCliVersionOutput, probeClaudeCliVersion } from './claude-hook-event-versions'
describe('identified Claude version output', () => {
// Recorded macOS 2.1.310 / Windows 2.1.221 probes; historical releases' CLI source
// registers the same suffix (1.0.23, 1.0.64, 2.0.0 and 2.1.100).
it.each([
['2.1.310 (Claude Code)\n', '', '2.1.310', 16, 0],
['2.1.221 (Claude Code)\n', '', '2.1.221', 15, 1],
['1.0.23 (Claude Code)', '', '1.0.23', 2, 14],
['1.0.64 (Claude Code)', '', '1.0.64', 6, 10],
['2.0.0 (Claude Code)', '', '2.0.0', 6, 10],
['2.1.100 (Claude Code)', '', '2.1.100', 14, 2],
['launcher 11.17.0\n1.0.64 (Claude Code)', '', '1.0.64', 6, 10],
['launcher 0.1.0\n2.1.310 (Claude Code)', '', '2.1.310', 16, 0],
['launcher 0.1.0', '2.1.310 (Claude Code)\n', '2.1.310', 16, 0],
['', '2.1.310 (Claude Code)\n', '2.1.310', 16, 0],
['2.1.94-rc.1+build.2 (Claude Code)', '', '2.1.94-rc.1+build.2', 14, 2],
['11.17.0\n', '', null, 6, 0],
['2.30.0', '', null, 6, 0],
['2.1.310\nwrapper for (Claude Code)', '', null, 6, 0],
['2.1.310\n(Claude Code)', '', null, 6, 0],
['2.1 (Claude Code)', '', null, 6, 0]
] as const)(
'uses the identified version and hook plan for stdout=%s stderr=%s',
async (stdout, stderr, expected, installs, retirements) => {
vi.mocked(runProcess).mockResolvedValue({
stdout,
stderr,
code: 0,
signal: null,
timedOut: false
})
const local = await probeClaudeCliVersion('/bin/claude')
// Older guests send combined raw output, not canonical stored semver.
const remote = readManagedHookDetectionResult({
agents: ['claude'],
versions: { claude: `${stdout}\n${stderr}` }
})
expect(remote.agents).toEqual(['claude'])
expect(parseClaudeCliVersionOutput(`${stdout}\n${stderr}`)).toBe(expected)
for (const version of [local, remote.claudeVersion]) {
expect(version).toBe(expected)
const plan = getClaudeManagedHookPlan(version)
expect(plan.install).toHaveLength(installs)
expect(plan.retire).toHaveLength(retirements)
expect(plan.statusLine).toBe(expected === '1.0.23' ? 'retire' : 'install')
}
}
)
it('does not accept marked output from a failed probe', async () => {
vi.mocked(runProcess).mockResolvedValue({
stdout: '2.1.310 (Claude Code)\n',
stderr: '',
code: 1,
signal: null,
timedOut: false
})
expect(await probeClaudeCliVersion('/bin/claude')).toBeNull()
})
})
@@ -1,112 +0,0 @@
import { expect, it, vi } from 'vitest'
import { ClaudeJournalBoundDelivery } from './claude-journal-bound-delivery'
import { bindClaudeJournalReadingControl } from './structured/journal/claude-structured-session-journal-control'
import type {
StructuredAgentSessionEventSink,
StructuredAgentSessionReadingControl
} from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink'
function unboundSink() {
let notify: (() => void) | undefined
let control: StructuredAgentSessionReadingControl | undefined
let bound = false
const sink: StructuredAgentSessionEventSink = {
appendItem: () => {},
appendTombstone: () => {},
publish: () => {},
onJournalBound: (listener) => {
notify = listener
return () => {
notify = undefined
}
},
journalLinkage: () =>
bound
? {
epoch: 'test',
visitItemsWithLinkage: () => {},
threadGoal: () => null,
threadGoalSource: () => ({ goal: null, row: null })
}
: null,
bindReadingControl: (next) => {
control = next
return () => {}
}
}
return {
sink,
bind: () => {
bound = true
notify?.()
},
pressure: (paused: boolean) => control?.[paused ? 'pauseReading' : 'resumeReading']()
}
}
it('holds ordered interpretation until binding while preserving independent sink pressure', () => {
const state = unboundSink()
let published = false
const delivery = new ClaudeJournalBoundDelivery(state.sink, () => published)
const connection = { pauseReading: vi.fn(), resumeReading: vi.fn() }
bindClaudeJournalReadingControl(state.sink, connection, null, delivery)
const observed: string[] = []
delivery.deliver(() => {
observed.push('start')
delivery.deliver(() => observed.push('later'))
})
delivery.deliver(() => observed.push('terminal'))
published = true
delivery.flush()
state.pressure(true)
expect(observed).toEqual([])
state.bind()
expect(observed).toEqual(['start', 'terminal', 'later'])
expect(connection.resumeReading).not.toHaveBeenCalled()
state.pressure(false)
expect(connection.resumeReading).toHaveBeenCalledOnce()
})
it('terminates the uncommitted prefix on disposal and ignores a late binding', () => {
const state = unboundSink()
const delivery = new ClaudeJournalBoundDelivery(state.sink)
const interpret = vi.fn()
delivery.deliver(interpret)
delivery.dispose()
state.bind()
delivery.deliver(interpret)
expect(interpret).not.toHaveBeenCalled()
})
it('fails a bounded unbound prefix instead of silently losing or replaying observations', () => {
const state = unboundSink()
const delivery = new ClaudeJournalBoundDelivery(state.sink)
const failure = vi.fn()
const interpret = vi.fn()
delivery.onFailure = failure
const payload = 'x'.repeat(1024 * 1024)
expect(() => {
for (let index = 0; index < 33; index++) {
delivery.deliver(interpret, payload)
}
}).toThrow('capacity exceeded')
state.bind()
expect(failure).toHaveBeenCalledOnce()
expect(interpret).not.toHaveBeenCalled()
})
it('reports binding interpretation failure through its owning failure path', () => {
const state = unboundSink()
const delivery = new ClaudeJournalBoundDelivery(state.sink)
const failure = vi.fn()
delivery.onFailure = failure
const error = new Error('invalid saved identity')
delivery.deliver(() => {
throw error
})
const later = vi.fn()
delivery.deliver(later)
expect(() => state.bind()).not.toThrow()
expect(failure).toHaveBeenCalledWith(error)
expect(later).not.toHaveBeenCalled()
})
@@ -1,154 +0,0 @@
import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
import { PROVIDER_STDIN_END_GRACE_MS } from '../provider-process/provider-process-supervisor'
import { createClaudeModelCatalogProbe } from './claude-model-catalog-probe'
import { resolveStructuredAgentCommand } from '../native-chat/structured-agent-command-resolution'
import type { runAgentModelCatalogListing } from '../native-chat/agent-model-catalog/agent-model-catalog-probe-runner'
type ListingCall = Parameters<typeof runAgentModelCatalogListing>
const AUTH_POLICY = { account: 'system' } as const
const HOME = (path: string): { variable: string; path: string } => ({
variable: 'CLAUDE_CONFIG_DIR',
path
})
function probeDeps(command = `"${process.execPath}"`): {
resolveCommand: () => { command: string; prefixArgs: string[] }
resolveEnv: () => Record<string, string>
resolveInheritedEnv: () => Promise<Record<string, string>>
resolveAuthPolicy: () => typeof AUTH_POLICY
} {
return {
resolveCommand: () =>
resolveStructuredAgentCommand('claude', {
agentCmdOverrides: { claude: command }
}),
resolveEnv: () => ({ ANTHROPIC_MODEL_GATEWAY: 'https://gateway.example' }),
resolveInheritedEnv: async () => ({ PATH: '/resolved/bin', HOME: '/homes/user' }),
resolveAuthPolicy: () => AUTH_POLICY
}
}
const LISTED = `${JSON.stringify({
type: 'control_response',
response: {
subtype: 'success',
request_id: 'orca-model-discovery',
response: {
models: [
{
value: 'sonnet',
displayName: 'Sonnet',
supportsEffort: true,
supportedEffortLevels: ['low']
}
]
}
}
})}\n`
describe('claude model catalog probe', () => {
it.each([
[[], [], ['/orca-probe', '/orca-probe'], 'user,project,local'],
[['node_modules/claude/cli.js'], [], ['/chat-a', '/chat-b'], 'user'],
[[], ['--settings', 'settings.json'], ['/chat-a', '/chat-b'], 'user']
])(
'lists prefix %j with arguments %j from %j, reading %s settings',
async (prefixArgs, launchArgs, listedIn, sources) => {
// A user command line may name files in the chat's folder, so it runs there, but reads only
// user settings there so the project's own settings never narrow the account's list.
const calls: ListingCall[] = []
const probe = createClaudeModelCatalogProbe({
...probeDeps(),
resolveCommand: () => ({ command: process.execPath, prefixArgs }),
resolveLaunchArgs: async () => launchArgs,
runListing: async (...call) => {
calls.push(call)
return LISTED
}
})
const identities: unknown[] = []
for (const folder of ['/chat-a', '/chat-b']) {
const resolved = await probe.resolve?.(
HOME('/homes/a'),
'/orca-probe',
'snapshot',
undefined,
folder
)
identities.push(resolved?.identity)
await resolved?.run()
}
expect(calls.map(([launch]) => launch.cwd)).toEqual(listedIn)
const args = calls[0]?.[0].args ?? []
expect(args.slice(0, prefixArgs.length)).toEqual(prefixArgs)
expect(args.slice(args.length - launchArgs.length)).toEqual(launchArgs)
expect(args[args.indexOf('--setting-sources') + 1]).toBe(sources)
expect(JSON.stringify(identities[0]) === JSON.stringify(identities[1])).toBe(
listedIn[0] === listedIn[1]
)
}
)
it.runIf(process.platform !== 'win32')(
'lists through a supervised one-shot that answers after its input ends',
async () => {
const folder = mkdtempSync(join(tmpdir(), 'orca-claude-probe-'))
try {
const parentFile = join(folder, 'parent-pid')
const standIn = join(folder, 'claude')
// Delay beyond the stdin-end grace to verify supervised one-shot lifetime.
writeFileSync(
standIn,
`#!${process.execPath}
let input = ''
process.stdin.on('data', (chunk) => (input += chunk))
process.stdin.on('end', () => setTimeout(() => {
require('node:fs').writeFileSync(${JSON.stringify(parentFile)}, String(process.ppid))
const request = JSON.parse(input.trim().split('\\n').find(line => line.includes('list_models')))
if (request.request.subtype !== 'list_models') process.exit(2)
console.log(JSON.stringify({ type: 'control_response', response: { subtype: 'success',
request_id: request.request_id, response: { models: [{ value: 'sonnet', displayName: 'Sonnet' }] } } }))
}, ${PROVIDER_STDIN_END_GRACE_MS * 1.5}))
`
)
chmodSync(standIn, 0o755)
const probe = createClaudeModelCatalogProbe({
...probeDeps(),
resolveCommand: () => ({ command: standIn, prefixArgs: [] }),
resolveInheritedEnv: async () => ({ PATH: process.env.PATH ?? '', HOME: folder })
})
await expect(probe(HOME(join(folder, 'account')))).resolves.toMatchObject({
origin: 'probe',
models: [{ id: 'sonnet', label: 'Sonnet' }]
})
expect(Number(readFileSync(parentFile, 'utf8'))).not.toBe(process.pid)
} finally {
rmSync(folder, { recursive: true, force: true })
}
}
)
})
describe('Claude catalog availability', () => {
it('says the CLI is missing when the resolved executable is not there', async () => {
const folder = mkdtempSync(join(tmpdir(), 'orca-claude-missing-'))
try {
const missing = join(folder, 'claude with spaces', 'claude')
const probe = createClaudeModelCatalogProbe({
...probeDeps(),
resolveCommand: () => ({ command: missing, prefixArgs: [] })
})
await expect(probe(HOME('/homes/a'))).rejects.toMatchObject({
unavailable: { reason: 'cliMissing' }
})
} finally {
rmSync(folder, { recursive: true, force: true })
}
})
})
@@ -1,83 +0,0 @@
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { expect, it, vi } from 'vitest'
import { ClaudeProfileRouter } from '../claude-accounts/profiles/routing/claude-profile-router'
import * as installedRouter from '../claude-accounts/profiles/routing/claude-profile-installed-router'
import { agentSessionRecordFixture } from '../native-chat/agent-session-record-test-fixture'
import type { StructuredAgentLaunchSources } from '../runtime/agent-session/launch/structured-agent-launch-composition'
import { claudeNamingInvocation } from './claude-naming-invocation'
it('captures configured command, overlay and pure selected-account policy before awaited input resolution', async ({
onTestFinished
}) => {
const root = await mkdtemp(join(tmpdir(), 'orca-naming-inputs-'))
onTestFinished(async () => {
vi.restoreAllMocks()
await rm(root, { recursive: true, force: true })
})
const router = new ClaudeProfileRouter({
getSettings: () => ({
claudeManagedAccounts: [],
activeClaudeManagedAccountId: null,
agentStatusHooksEnabled: false,
disabledTuiAgents: []
}),
dataRoot: root,
userHome: root,
env: {}
})
const selected = join(root, 'selected-account')
const later = join(root, 'later-account')
const preparation = vi.spyOn(router, 'preparation').mockReturnValue({
configDir: selected,
runtime: 'host',
wslDistro: null,
wslLinuxConfigDir: null,
envPatch: { CLAUDE_CONFIG_DIR: selected },
provenance: 'profile:a'
})
const prepareLaunch = vi.spyOn(router, 'prepareLaunch')
vi.spyOn(installedRouter, 'getClaudeProfileRouter').mockReturnValue(router)
const record = agentSessionRecordFixture({
sessionId: 'chat',
accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: join(root, 'saved-account') }
})
const inherited = Promise.withResolvers<Record<string, string>>()
const settings = { agentCmdOverrides: { claude: `"${process.execPath}"` } }
const overlay = { CLAUDE_CONFIG_DIR: join(root, 'overlay-account'), NAMING_INPUT: 'accepted' }
const sources: StructuredAgentLaunchSources = {
store: {
selectWritableRecord: () => ({ kind: 'writable', record }),
requireWritableRecord: () => record,
pinLaunchDirectory: async () => record
},
resolveWorkspacePath: async () => root,
resolveBaseEnvironment: () => inherited.promise,
resolveAgentEnvironment: async () => overlay,
resolveAgentLaunchEnv: () => overlay,
resolveCommandSettings: () => settings
}
const snapshot = claudeNamingInvocation(sources, () => [])
const pending = snapshot(record)
settings.agentCmdOverrides.claude = 'does-not-exist-orca-naming'
overlay.NAMING_INPUT = 'changed'
preparation.mockReturnValue({
configDir: later,
runtime: 'host',
wslDistro: null,
wslLinuxConfigDir: null,
envPatch: { CLAUDE_CONFIG_DIR: later },
provenance: 'profile:b'
})
inherited.resolve({ HOME: root, PATH: process.env.PATH ?? '' })
expect(await pending).toMatchObject({
command: process.execPath,
home: selected,
cwd: root,
env: { CLAUDE_CONFIG_DIR: selected, NAMING_INPUT: 'accepted' }
})
expect(prepareLaunch).not.toHaveBeenCalled()
await expect(snapshot(record)).rejects.toThrow()
expect(prepareLaunch).not.toHaveBeenCalled()
})
@@ -1,11 +0,0 @@
// CLI 2.1.319, isolated real run: parent Stop, live child roster, then separate child Stop; IDs/paths sanitized.
import { readFileSync } from 'node:fs'
import type { CapturedFrame } from './claude-captured-frame-builders.test-fixture'
export const PARENT_TASK_STOP: CapturedFrame[] = readFileSync(
new URL('./__fixtures__/claude-parent-task-stop-2.1.319.jsonl', import.meta.url),
'utf8'
)
.trim()
.split('\n')
.map((line) => JSON.parse(line))
@@ -1,232 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import { invokeCanUseTool } from './claude-can-use-tool-test-support'
import {
PROVIDER_SESSION_ID,
USER_MESSAGE,
acquired,
claudeFrame,
fakeClaude,
tick,
type FakeConnection
} from './structured/claude-structured-session-test-support'
import { claudeStructuredPermissionOptions } from './structured/launch/claude-structured-launch-resolution'
async function pendingPlanApproval(
input: Record<string, unknown>,
initPermissionMode?: string,
requested?: 'full-access'
) {
const claude = fakeClaude({ replayUuid: 'turn-1', initPermissionMode })
const adapter = await acquired(
claude,
requested ? { options: claudeStructuredPermissionOptions(requested) } : {}
)
await adapter.dispatch({
sessionId: 'session-1',
clientMessageId: 'client-turn-1',
body: USER_MESSAGE,
fence: 7
})
const connection = claude.connections[0]
if (!connection) {
throw new Error('expected Claude connection')
}
claudeFrame(connection, { type: 'system', subtype: 'status', permissionMode: 'plan' })
if (requested) {
for (const frame of [
{
type: 'system',
subtype: 'status',
status: null,
permissionMode: 'plan',
session_id: PROVIDER_SESSION_ID
},
{
type: 'control_request',
request_id: 'permission-plan',
request: {
subtype: 'can_use_tool',
tool_name: 'ExitPlanMode',
input,
tool_use_id: 'tool-plan'
}
}
]) {
connection.handlers.onStdout?.(`${JSON.stringify(frame)}\n`)
}
}
const request = new AbortController()
const answered = invokeCanUseTool(connection, 'ExitPlanMode', 'permission-plan', 'tool-plan', {
input,
signal: request.signal
})
adapter.bindPromptItemId('session-1', 'journal-plan', 'permission-plan')
return { adapter, connection, answered, request }
}
describe('leaving Claude plan mode on an approved plan', () => {
it.each(['failed commit', 'lost ownership'])(
'does not change mode when approval has %s',
async (failure) => {
const { adapter, connection, answered, request } = await pendingPlanApproval({})
const setMode = vi.spyOn(connection, 'setPermissionMode')
await expect(
adapter.answerPrompt({
sessionId: 'session-1',
itemId: 'journal-plan',
kind: 'approval',
response: { kind: 'option', optionId: 'allow' },
fence: 7,
commit: async () => {
expect(setMode).not.toHaveBeenCalled()
expect(answered.settled()).toBe(false)
if (failure === 'failed commit') {
throw new Error('journal write failed')
}
request.abort()
}
})
).rejects.toThrow()
expect(setMode).not.toHaveBeenCalled()
if (failure === 'lost ownership') {
await expect(answered.promise).resolves.toBeNull()
} else {
expect(answered.settled()).toBe(false)
// The failed write released its claim, so a later approval still works.
await adapter.answerPrompt({
sessionId: 'session-1',
itemId: 'journal-plan',
kind: 'approval',
response: { kind: 'option', optionId: 'allow' },
fence: 7,
commit: async () => {}
})
await expect(answered.promise).resolves.toMatchObject({ behavior: 'allow' })
expect(setMode).toHaveBeenCalledOnce()
}
setMode.mockRestore()
}
)
it('restores Full access from the plan Claude reported on the wire, before presentation reads it', async () => {
// Init reported bypassPermissions through presentation; the later plan status is still unread there.
const claude = fakeClaude({ replayUuid: 'turn-1', initPermissionMode: 'bypassPermissions' })
const adapter = await acquired(claude, {
options: claudeStructuredPermissionOptions('full-access')
})
await adapter.dispatch({
sessionId: 'session-1',
clientMessageId: 'client-turn-1',
body: USER_MESSAGE,
fence: 7
})
const connection = claude.connections[0]!
const raw = (target: FakeConnection, frame: Record<string, unknown>): void =>
target.handlers.onStdout?.(`${JSON.stringify(frame)}\n`)
const request = (id: string, toolName: string, input: Record<string, unknown>) => {
raw(connection, {
type: 'control_request',
request_id: id,
request: { subtype: 'can_use_tool', tool_name: toolName, input, tool_use_id: `tool-${id}` }
})
return invokeCanUseTool(connection, toolName, id, `tool-${id}`, { input })
}
const status = (permissionMode: string) => ({
type: 'system',
subtype: 'status',
status: null,
permissionMode,
session_id: PROVIDER_SESSION_ID
})
raw(connection, status('plan'))
const plan = request('permission-plan', 'ExitPlanMode', { plan: '# Plan' })
adapter.bindPromptItemId('session-1', 'journal-plan', 'permission-plan')
const order: string[] = []
const setMode = vi.spyOn(connection, 'setPermissionMode').mockImplementation((mode) => {
order.push(`set_permission_mode:${mode}`)
// Never resolves: the approval must not wait for Claude to confirm the mode.
return new Promise(() => {})
})
const answered = plan.promise.then((result) => {
order.push('control_response')
return result
})
await adapter.answerPrompt({
sessionId: 'session-1',
itemId: 'journal-plan',
kind: 'approval',
response: { kind: 'option', optionId: 'allow' },
fence: 7,
commit: async () => {}
})
await expect(answered).resolves.toMatchObject({
behavior: 'allow',
toolUseID: 'tool-permission-plan'
})
expect(order).toEqual(['set_permission_mode:bypassPermissions', 'control_response'])
expect(setMode).toHaveBeenCalledOnce()
// Sending the restore grants nothing; Claude's own bypass report does.
const beforeReport = request('before-report', 'Bash', { command: 'ls' })
await tick()
expect(beforeReport.settled()).toBe(false)
raw(connection, status('bypassPermissions'))
const afterReport = request('after-report', 'Bash', { command: 'ls' })
await expect(afterReport.promise).resolves.toEqual({
behavior: 'allow',
updatedInput: { command: 'ls' },
toolUseID: 'tool-after-report'
})
setMode.mockRestore()
})
})
it.each([true, false])(
'uses the approved Build policy only after successful native restoration: %s',
async (restored) => {
const { adapter, connection, answered } = await pendingPlanApproval(
{},
'default',
'full-access'
)
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
const setMode = vi.spyOn(connection, 'setPermissionMode').mockImplementationOnce(async () => {
if (!restored) {
throw new Error('native restoration failed')
}
})
try {
await adapter.answerPrompt({
sessionId: 'session-1',
itemId: 'journal-plan',
kind: 'approval',
response: { kind: 'option', optionId: 'allow' },
fence: 7,
commit: async () => {}
})
await expect(answered.promise).resolves.toMatchObject({ behavior: 'allow' })
await tick()
expect(setMode).toHaveBeenCalledWith('bypassPermissions')
for (const clientMessageId of ['build-first', 'build-second']) {
claudeFrame(connection, { type: 'system', subtype: 'session_state_changed', state: 'idle' })
await adapter.readOptions({ sessionId: 'session-1', fence: 7 })
expect(
await adapter.dispatch({
sessionId: 'session-1',
clientMessageId,
body: USER_MESSAGE,
fence: 7,
executionOptions: { interactionMode: 'default' }
})
).toMatchObject({ state: 'admitted' })
expect(setMode).toHaveBeenLastCalledWith(restored ? 'bypassPermissions' : 'default', {
timeoutMs: undefined
})
}
} finally {
warn.mockRestore()
await adapter.closeAll()
}
}
)
@@ -1,121 +0,0 @@
import { listSessions } from '@anthropic-ai/claude-agent-sdk'
import { randomUUID } from 'node:crypto'
import * as fs from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import * as transcriptFs from '../native-chat/wsl-transcript-fs-access'
import { renameClaudeTranscript } from './claude-provider-session-rename'
let home: string
let conversation: string
let transcript: string
beforeEach(async () => {
home = await fs.mkdtemp(join(tmpdir(), 'orca-claude-rename-'))
conversation = randomUUID()
const project = join(home, 'projects', 'workspace')
await fs.mkdir(project, { recursive: true })
transcript = join(project, `${conversation}.jsonl`)
})
afterEach(async () => {
vi.restoreAllMocks()
await fs.rm(home, { recursive: true, force: true })
})
it.each([false, true])(
'appends both native names after a torn tail (earlier agent-name=%s)',
async (earlierName) => {
const user = {
type: 'user',
uuid: randomUUID(),
sessionId: conversation,
message: { role: 'user', content: 'ship it' }
}
const oldName = earlierName
? `${JSON.stringify({ type: 'agent-name', agentName: 'Earlier native name', sessionId: conversation })}\n`
: ''
const prefix = `${JSON.stringify(user)}\n${oldName}{"type":"assistant","mess`
await fs.writeFile(transcript, prefix)
const otherAccount = join(home, 'other-account', 'projects', 'workspace')
await fs.mkdir(otherAccount, { recursive: true })
const otherTranscript = join(otherAccount, `${conversation}.jsonl`)
await fs.writeFile(otherTranscript, 'another account\n')
const source = join(home, 'projects', 'workspace', `${randomUUID()}.jsonl`)
await fs.writeFile(source, 'unrelated source\n')
const inventory = vi.spyOn(transcriptFs, 'wslGatedReaddir')
const stat = vi.spyOn(transcriptFs, 'wslGatedStat')
const append = vi.spyOn(fs, 'appendFile')
const originalOpen = fs.open
const open = vi.spyOn(fs, 'open').mockImplementation(async (...args) => {
const handle = await originalOpen(...args)
vi.spyOn(handle, 'read')
return handle
})
await renameClaudeTranscript(home, conversation, ' Release notes ')
const result = await fs.readFile(transcript, 'utf8')
expect(result.slice(0, prefix.length + 1)).toBe(`${prefix}\n`)
const lines = result
.slice(prefix.length + 1)
.trim()
.split('\n')
expect(lines).toHaveLength(2)
const title = JSON.parse(lines[0] ?? '')
expect(title).toMatchObject({
type: 'custom-title',
sessionId: conversation,
customTitle: 'Release notes'
})
expect(title.uuid).toEqual(expect.any(String))
expect(title.timestamp).toEqual(expect.any(String))
expect(JSON.parse(lines[1] ?? '')).toEqual({
type: 'agent-name',
agentName: 'Release notes',
sessionId: conversation
})
expect(inventory).toHaveBeenCalledTimes(1)
expect(stat).toHaveBeenCalledTimes(1)
expect(open).toHaveBeenCalledExactlyOnceWith(transcript, 'r')
const handle = await open.mock.results[0]?.value
expect(handle?.read).toHaveBeenCalledExactlyOnceWith(
expect.any(Buffer),
0,
1,
Buffer.byteLength(prefix) - 1
)
expect(append).toHaveBeenCalledExactlyOnceWith(transcript, `\n${lines.join('\n')}\n`, {
flag: 'a'
})
expect(await fs.readFile(otherTranscript, 'utf8')).toBe('another account\n')
expect(await fs.readFile(source, 'utf8')).toBe('unrelated source\n')
const listed = await listSessions({
sessionStore: {
load: async () => [user, title],
append: async () => {},
listSessions: async () => [{ sessionId: conversation, mtime: 1_700_000_000_000 }]
}
})
expect(listed[0]?.customTitle).toBe('Release notes')
}
)
it('refuses missing, empty, multiple and incomplete inventories without mutating another candidate', async () => {
await expect(renameClaudeTranscript(home, conversation, 'Missing')).rejects.toThrow(
'no transcript'
)
await fs.writeFile(transcript, '')
await expect(renameClaudeTranscript(home, conversation, 'Empty')).rejects.toThrow('no transcript')
await fs.writeFile(transcript, 'old\n')
const second = join(home, 'projects', 'hash-or-worktree')
await fs.mkdir(second)
const duplicate = join(second, `${conversation}.jsonl`)
await fs.writeFile(duplicate, 'other\n')
await expect(renameClaudeTranscript(home, conversation, 'Ambiguous')).rejects.toThrow(
'multiple transcripts'
)
expect(await fs.readFile(transcript, 'utf8')).toBe('old\n')
expect(await fs.readFile(duplicate, 'utf8')).toBe('other\n')
const denied = Object.assign(new Error('denied'), { code: 'EACCES' })
vi.spyOn(transcriptFs, 'wslGatedStat').mockRejectedValue(denied)
await expect(renameClaudeTranscript(home, conversation, 'Denied')).rejects.toBe(denied)
expect(await fs.readFile(transcript, 'utf8')).toBe('old\n')
})
@@ -1,52 +0,0 @@
import { homedir } from 'node:os'
import { join } from 'node:path'
import { runProcessSync } from '@orca/process-host'
import type { ProcessResult } from '@orca/process-host/process-spec'
import { withCliRuntimeOnPath } from '../../shared/node-cli-command-resolution'
import { CLAUDE_AUTH_ENV_VARS } from '../claude-accounts/runtime-auth/environment'
import { resolveClaudeCommand } from '../codex-cli/command'
import { resolveRealClaudeCliGate } from './claude-real-cli-test-gate'
export const realClaudeCommand = resolveClaudeCommand()
// Match structured launches by using the CLI's paired Node runtime.
function probeRealClaude(args: string[]): ProcessResult | null {
try {
return runProcessSync({
program: realClaudeCommand,
args,
env: withCliRuntimeOnPath(realClaudeCommand, process.env),
stdio: ['ignore', 'pipe', 'pipe'],
timeoutMs: 5_000
})
} catch {
return null
}
}
export const realClaudeCliGate = resolveRealClaudeCliGate(process.env, (args) => {
const result = probeRealClaude([...args])
return { status: result?.code ?? null, stdout: result?.stdout ?? '' }
})
export const realClaudeAvailable = realClaudeCliGate.skipReason === null
/** Use the CLI's account report as an independent oracle for transcript paths. */
export const realClaudeAuthStatus = realClaudeCliGate.authStatus
export const realClaudeAuthenticated = realClaudeAuthStatus?.loggedIn === true
/** Restore the probed home and auth explicitly: connections strip inherited account state. */
export function realClaudeLaunchHome(): { claudeConfigDir: string; env: Record<string, string> } {
const env: Record<string, string> = {}
for (const key of CLAUDE_AUTH_ENV_VARS) {
const value = process.env[key]
if (value) {
env[key] = value
}
}
return {
claudeConfigDir: process.env.CLAUDE_CONFIG_DIR?.trim() || join(homedir(), '.claude'),
env
}
}
@@ -1,63 +0,0 @@
/** Opt-in for tests that drive the real `claude` CLI on this machine's signed-in account. */
export const REAL_CLAUDE_CLI_TEST_ENV = 'ORCA_REAL_CLAUDE_CLI_TEST'
export type ClaudeCliProbeResult = { status: number | null; stdout: string }
export type RealClaudeAuthStatus = { loggedIn?: boolean; projectsDirectory?: string }
export type RealClaudeCliGate = {
/** Null permits the real-CLI suite to run. */
skipReason: string | null
authStatus: RealClaudeAuthStatus | null
}
function parseAuthStatus(stdout: string): RealClaudeAuthStatus | null {
const start = stdout.search(/[[{]/)
if (start === -1) {
return null
}
// CLI warnings may precede the report, but another JSON value makes it ambiguous.
for (const line of stdout.slice(0, start).split('\n')) {
try {
JSON.parse(line)
return null
} catch {
continue
}
}
let parsed: unknown
try {
parsed = JSON.parse(stdout.slice(start))
} catch {
return null
}
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
return null
}
const status: RealClaudeAuthStatus = {}
if ('loggedIn' in parsed && typeof parsed.loggedIn === 'boolean') {
status.loggedIn = parsed.loggedIn
}
if ('projectsDirectory' in parsed && typeof parsed.projectsDirectory === 'string') {
status.projectsDirectory = parsed.projectsDirectory
}
return status
}
export function resolveRealClaudeCliGate(
env: NodeJS.ProcessEnv,
runClaude: (args: readonly string[]) => ClaudeCliProbeResult
): RealClaudeCliGate {
// Require opt-in before probing an account whose tests spend turns and write transcripts.
if (env[REAL_CLAUDE_CLI_TEST_ENV] !== '1') {
return {
skipReason: `set ${REAL_CLAUDE_CLI_TEST_ENV}=1 to run against the real claude CLI`,
authStatus: null
}
}
if (runClaude(['--version']).status !== 0) {
return { skipReason: '`claude --version` failed', authStatus: null }
}
const auth = runClaude(['auth', 'status', '--json'])
return { skipReason: null, authStatus: auth.status === 0 ? parseAuthStatus(auth.stdout) : null }
}
@@ -1,226 +0,0 @@
import './claude-conversation-worker.test-fixture'
import { randomUUID } from 'node:crypto'
import { mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { claudeProviderHandle } from '../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding'
import { AgentSessionRewindRecordSchema } from '../../shared/agent-session/lifecycle/agent-session-rewind'
import { agentSessionRecordFixture } from '../native-chat/agent-session-record-test-fixture'
import { createClaudeStructuredLaunchResolver } from '../runtime/agent-session/launch/structured-agent-launch-composition.test-support'
import { resolveClaudeRewindFork } from './claude-rewind-fork'
import { claudeSessionIdForRewind } from './structured/claude-structured-session-id'
let root: string
let home: string
let project: string
let source: string
let path: string
let original: string
let sourceRows: ReturnType<typeof transcriptRows>
function transcriptRows(contents: string) {
return contents
.trim()
.split('\n')
.map((line) => JSON.parse(line))
}
async function recordedTranscript(kind: 'hook' | 'informational') {
return readFile(new URL(`./__fixtures__/claude-rewind-${kind}.jsonl`, import.meta.url), 'utf8')
}
beforeEach(async () => {
root = await mkdtemp(join(tmpdir(), 'orca-rewind-transcript-'))
home = join(root, 'account')
project = join(home, 'projects', 'workspace')
await mkdir(project, { recursive: true })
original = await recordedTranscript('hook')
sourceRows = transcriptRows(original)
source = sourceRows[6].sessionId
path = join(project, `${source}.jsonl`)
await writeFile(path, original)
})
afterEach(async () => {
await rm(root, { recursive: true, force: true })
})
function forkBefore(uuid: string, rewindOperationId = randomUUID()) {
return resolveClaudeRewindFork({
orcaSessionId: 'orca-chat',
rewindOperationId,
head: claudeProviderHandle(source, sourceRows.at(-1)?.uuid),
prompt: { sessionId: source, uuid },
claudeConfigDirs: [join(root, 'other-account'), home]
})
}
describe('durable Claude rewind transcripts', () => {
it.each([
{ promptRow: 35, parentRow: 28, cursorRole: 'user' },
{ promptRow: 55, parentRow: 51, cursorRole: 'assistant' }
])(
'keeps the exact $cursorRole cursor before recorded prompt $promptRow',
async ({ promptRow, parentRow, cursorRole }) => {
const prompt = sourceRows[promptRow - 1]
const fork = await forkBefore(prompt.uuid)
expect(fork).toMatchObject({
materialized: true,
sourceSessionId: source,
throughEntryId: sourceRows[parentRow - 1].uuid
})
if (!fork) {
throw new Error('fork missing')
}
const forkPath = join(project, `${fork.sessionId}.jsonl`)
const contents = await readFile(forkPath, 'utf8')
const conversation = (rows: typeof sourceRows) =>
rows.filter((row) => row.type === 'user' || row.type === 'assistant')
const kept = conversation(transcriptRows(contents))
const expected = conversation(sourceRows.slice(0, parentRow))
expect(kept.map((row) => row.forkedFrom.messageUuid)).toEqual(expected.map((row) => row.uuid))
expect(kept.at(-1)).toMatchObject({ type: cursorRole, uuid: fork.resumeCursor })
expect(fork.resumeCursor).toBeTruthy()
expect(fork.resumeCursor).not.toBe(expected.at(-1)?.uuid)
expect(contents).not.toContain(prompt.uuid)
expect(await readFile(path, 'utf8')).toBe(original)
expect((await readdir(project)).sort()).toEqual(
[`${source}.jsonl`, `${fork.sessionId}.jsonl`].sort()
)
if (process.platform !== 'win32') {
expect((await stat(forkPath)).mode & 0o777).toBe(0o600)
}
}
)
it.each(['hook', 'informational', 'null'] as const)(
'starts and reloads an empty fork after a %s parent',
async (kind) => {
original = await recordedTranscript(kind === 'informational' ? 'informational' : 'hook')
sourceRows = transcriptRows(original)
const prompt = sourceRows.find((row) => row.type === 'user')
if (kind === 'null') {
prompt.parentUuid = null
original = `${sourceRows.map((row) => JSON.stringify(row)).join('\n')}\n`
}
await writeFile(path, original)
const operationId = randomUUID()
const fork = await forkBefore(prompt.uuid, operationId)
expect(fork).toStrictEqual({
sessionId: claudeSessionIdForRewind('orca-chat', operationId),
sourceSessionId: source,
replacesSessionId: source,
materialized: true,
coverage: []
})
if (!fork) {
throw new Error('fork missing')
}
expect(await readdir(project)).toEqual([`${source}.jsonl`])
const launchers = [true, false].map((prepared) => {
const handle = claudeProviderHandle(
prepared ? source : fork.sessionId,
prepared ? prompt.uuid : null
)
const record = agentSessionRecordFixture({
sessionId: 'orca-chat',
accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: home },
providerHandleChain: [
{ linkId: 'head', origin: 'created', mintedAtFence: 1, observedAt: 1, handle }
],
rewind: AgentSessionRewindRecordSchema.parse(
JSON.parse(
JSON.stringify({
operationId,
callerKey: 'desktop',
itemId: 'item-1',
expectedEpoch: 'epoch-1',
phase: prepared ? 'prepared' : 'completed',
providerFork: fork
})
)
)
})
const resolve = createClaudeStructuredLaunchResolver({
store: { getRecord: () => record, pinLaunchDirectory: vi.fn() },
resolveLaunchArgs: () => [],
resolveWorkspacePath: async () => project,
resolveCommand: () => ({ command: '/usr/local/bin/claude', prefixArgs: [] }),
resolveInheritedEnv: async () => ({ PATH: '/usr/bin' }),
resolveAuthPolicy: () => ({ account: 'system' })
})
return () =>
resolve({
identity: {
sessionId: record.sessionId,
workspaceId: 'workspace-1',
hostId: 'local',
agent: 'claude',
providerHandle: handle
}
})
})
for (const launch of launchers) {
const fresh = await launch()
expect(fresh.options.sessionId).toBe(fork.sessionId)
expect(fresh.resumesTranscript).toBe(false)
for (const key of ['resume', 'resumeSessionAt', 'forkSession']) {
expect(fresh.options).not.toHaveProperty(key)
}
}
await writeFile(
join(project, `${fork.sessionId}.jsonl`),
`${JSON.stringify({ ...prompt, sessionId: fork.sessionId, parentUuid: null })}\n`
)
for (const launch of launchers) {
const resumed = await launch()
expect(resumed.options.resume).toBe(fork.sessionId)
expect(resumed.options).not.toHaveProperty('resumeSessionAt')
expect(resumed.options).not.toHaveProperty('forkSession')
}
expect(await readFile(path, 'utf8')).toBe(original)
}
)
it('drops the local-command caveat when rewinding to a local command', async () => {
const turn = sourceRows[50]
const row = (uuid: string, parentUuid: string, content: string, isMeta?: true) => ({
...sourceRows[54],
uuid,
parentUuid,
isMeta,
message: { role: 'user', content }
})
const caveat = row(
randomUUID(),
turn.uuid,
'<local-command-caveat>The command below was run directly in Claude Code.</local-command-caveat>',
true
)
const command = row(randomUUID(), caveat.uuid, '<command-name>/usage</command-name>')
const stdout = row(
randomUUID(),
command.uuid,
'<local-command-stdout>ok</local-command-stdout>'
)
await writeFile(
path,
`${[...sourceRows.slice(0, 54), caveat, command, stdout].map((r) => JSON.stringify(r)).join('\n')}\n`
)
const fork = await forkBefore(command.uuid)
expect(fork).toMatchObject({ materialized: true, throughEntryId: turn.uuid })
const contents = await readFile(join(project, `${fork?.sessionId}.jsonl`), 'utf8')
expect(contents).not.toContain('local-command-caveat')
})
it('skips a torn transcript line instead of failing the rewind', async () => {
const damaged = `{broken-json}\n${original}{"type":`
await writeFile(path, damaged)
const fork = await forkBefore(sourceRows[34].uuid)
expect(fork).toMatchObject({ materialized: true, throughEntryId: sourceRows[27].uuid })
const contents = await readFile(join(project, `${fork?.sessionId}.jsonl`), 'utf8')
expect(contents).not.toContain(sourceRows[34].uuid)
expect(await readFile(path, 'utf8')).toBe(damaged)
})
})
@@ -1,164 +0,0 @@
// Registration fixture uses the real Claude adapter over scripted stream-json, including initialize handshake.
import { randomUUID } from 'node:crypto'
import { mkdirSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import type {
ClaudeStreamJsonConnection,
ClaudeStreamJsonLaunch,
openClaudeStreamJsonConnection
} from './claude-stream-json-connection'
import type {
ScriptedAgentChild,
ScriptedAgentChildFactory
} from '../runtime/agent-session/installation/structured-agent-scripted-child.test-fixture'
import { scriptedClaudeExitError } from '../runtime/agent-session/installation/structured-claude-scripted-runtime-test-support'
import { result, says } from './claude-captured-frame-builders.test-fixture'
type Spawned = {
connection: Omit<ClaudeStreamJsonConnection, 'closed' | 'exitVerdict'> & {
closed: boolean
exitVerdict: ClaudeStreamJsonConnection['exitVerdict']
}
answer: () => void
fail: (message: string) => void
}
function promptText(message: Record<string, unknown>): string {
const inner = message.message
const content =
inner && typeof inner === 'object' && 'content' in inner ? inner.content : undefined
const blocks = Array.isArray(content) ? content : []
return blocks
.map((block: unknown) =>
block && typeof block === 'object' && 'text' in block ? String(block.text) : ''
)
.join('')
}
/** The CLI writes its transcript as a conversation's first message lands; a later start resumes it. */
function writeTranscript(launch: ClaudeStreamJsonLaunch, providerSessionId: string): void {
const home = launch.env?.CLAUDE_CONFIG_DIR
if (!home) {
return
}
const folder = join(home, 'projects', 'scripted')
mkdirSync(folder, { recursive: true })
writeFileSync(join(folder, `${providerSessionId}.jsonl`), '{}\n')
}
export const claudeScriptedChild: ScriptedAgentChildFactory = () => {
const spawned: Spawned[] = []
const prompts: string[] = []
let resumes = 0
let closes = 0
const openConnection: typeof openClaudeStreamJsonConnection = async (launch, handlers = {}) => {
if (launch.options.resume !== undefined) {
resumes += 1
}
const providerSessionId = String(launch.options.sessionId ?? launch.options.resume)
const initialized = { models: [{ value: 'sonnet', displayName: 'Sonnet' }] }
let answer = (): void => {}
let reject = (_error: Error): void => {}
const init = new Promise<typeof initialized>((resolve, fail) => {
answer = () => {
handlers.onMessage?.({
type: 'system',
subtype: 'init',
session_id: providerSessionId,
model: 'claude-sonnet-5',
apiKeySource: 'none'
})
resolve(initialized)
}
reject = fail
})
if (!child.holdHandshakes) {
answer()
}
const connection: Spawned['connection'] = {
pid: 7000 + spawned.length,
closed: false,
exitVerdict: { root: 'live', tree: 'unverifiable' },
initializationResult: () => init,
getContextUsage: async () => ({}),
renameSession: async () => {},
getSettings: async () => ({ effective: {} }),
supportedModels: async () => [{ value: 'sonnet', displayName: 'Sonnet' }],
setModel: async () => {},
setPermissionMode: async () => {},
applyFlagSettings: async () => {},
interrupt: async () => undefined,
cancelAsyncMessage: async () => false,
stopTask: async () => {},
send: async (message, beforeDispatch) => {
await beforeDispatch?.()
prompts.push(promptText(message))
writeTranscript(launch, providerSessionId)
// The CLI echoes each message it takes under the client's uuid: Orca's proof of delivery.
handlers.onMessage?.({
type: 'user',
session_id: providerSessionId,
parent_tool_use_id: null,
uuid: message.uuid,
isReplay: true,
message: message.message
})
if (child.completeTurns) {
const id = randomUUID()
handlers.onMessage?.({ ...says(id, 'done', null), session_id: providerSessionId })
handlers.onMessage?.({ ...result('success'), session_id: providerSessionId, uuid: id })
}
},
close: async () => {
if (!connection.closed) {
connection.closed = true
closes += 1
connection.exitVerdict = { root: 'exited', tree: 'exited' }
handlers.onExit?.(new Error('closed by Orca'))
}
return true
}
}
spawned.push({
connection,
answer,
fail: (message) => {
const error = scriptedClaudeExitError(message)
connection.closed = true
connection.exitVerdict = { root: 'exited', tree: 'unverifiable' }
reject(error)
handlers.onExit?.(error)
}
})
return connection
}
const newest = (): Spawned => {
const latest = spawned.at(-1)
if (!latest) {
throw new Error('no Claude child was spawned')
}
return latest
}
const child: ScriptedAgentChild = {
deps: {
openClaudeConnection: openConnection,
readProcessStartTime: async (pid) =>
spawned.find((entry) => entry.connection.pid === pid)?.connection.exitVerdict.root ===
'exited'
? null
: pid * 10,
resolveClaudeCommand: () => ({ command: '/nonexistent/scripted-claude', prefixArgs: [] }),
resolveClaudeAuthPolicy: () => ({ account: 'system' })
},
holdHandshakes: true,
releaseHandshake: () => newest().answer(),
failHandshake: (message) => newest().fail(message),
completeTurns: true,
prompts: () => prompts,
spawns: () => spawned.length,
resumes: () => resumes,
closes: () => closes
}
return child
}
@@ -1,58 +0,0 @@
import { mkdtempSync, readFileSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import fixture from './__fixtures__/claude-hook-event-enums.json'
vi.mock('electron', () => ({
app: {
getPath: () => '/tmp/userData'
}
}))
import { ClaudeHookService } from './hook-service'
const enums: Record<string, string[]> = fixture.enums
const topLevelSettings: Record<string, { strict: boolean; keys: string[] }> =
fixture.topLevelSettings
const strictReleases = Object.keys(topLevelSettings).filter(
(version) => topLevelSettings[version].strict
)
describe('Claude settings written for a strict settings schema', () => {
let tmpHome: string
let settingsPath: string
beforeEach(() => {
tmpHome = mkdtempSync(join(tmpdir(), 'orca-claude-settings-schema-'))
settingsPath = join(tmpHome, '.claude', 'settings.json')
vi.stubEnv('HOME', tmpHome)
vi.stubEnv('USERPROFILE', tmpHome)
})
afterEach(() => {
vi.unstubAllEnvs()
rmSync(tmpHome, { recursive: true, force: true })
})
function expectAcceptedBy(version: string): void {
const written = JSON.parse(readFileSync(settingsPath, 'utf-8'))
const { keys } = topLevelSettings[version]
expect(Object.keys(written).filter((key) => !keys.includes(key))).toEqual([])
expect(
Object.keys(written.hooks ?? {}).filter((event) => !enums[version].includes(event))
).toEqual([])
}
it.each(strictReleases)('a fresh install writes only what Claude %s accepts', (version) => {
new ClaudeHookService().install({ claudeVersion: version })
expectAcceptedBy(version)
})
it.each(strictReleases)('a downgrade to Claude %s leaves only what it accepts', (version) => {
const service = new ClaudeHookService()
service.install({ claudeVersion: '2.1.261' })
service.install({ claudeVersion: version })
expectAcceptedBy(version)
})
})
@@ -1,189 +0,0 @@
import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'
import { createServer, type Server } from 'node:http'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import type * as osModule from 'node:os'
import { runProcess } from '@orca/process-host'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { removeTreeSync } from '../../shared/windows-transient-lock-removal'
import { parseClaudeStatusLineBody } from '../../shared/claude-statusline-rate-limits'
const { homedirMock } = vi.hoisted(() => ({
homedirMock: vi.fn<() => string>()
}))
vi.mock('electron', () => ({ app: { getPath: () => '/tmp/orca-user-data' } }))
vi.mock('os', async (importOriginal) => {
const actual = await importOriginal<typeof osModule>()
return { ...actual, homedir: homedirMock.mockImplementation(actual.homedir) }
})
import { findGitBash } from '../agent-hooks/installation/commands/testing/windows-git-bash-path.test-fixture'
import { ClaudeHookService } from './hook-service'
import { getManagedCommand } from './hook-settings'
const CURRENT_CLAUDE = { claudeVersion: '2.1.261 (Claude Code)' }
const PAYLOAD = JSON.stringify({
session_id: 'statusline-delivery',
model: { id: 'claude-opus-5-5', display_name: 'Opus' },
rate_limits: {
five_hour: { used_percentage: 42, resets_at: 1790000000 },
seven_day: { used_percentage: 7, resets_at: 1790500000 }
}
})
const EXPECTED_RATE_LIMITS = {
configDir: null,
fiveHour: { used_percentage: 42, resets_at: 1790000000 },
sevenDay: { used_percentage: 7, resets_at: 1790500000 }
}
const HOOK_TOKEN = 'statusline-delivery-token'
// Match Claude.exe's PowerShell flags.
const POWERSHELL_ARGS = ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command']
const LEGACY_COMMAND = getManagedCommand('claude-statusline.cmd')
type StatusLineSettings = { statusLine?: { type: string; command: string } }
function settingsPath(home: string): string {
return join(home, '.claude', 'settings.json')
}
function powershellPath(): string {
const systemRoot = process.env.SystemRoot ?? 'C:\\Windows'
return join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe')
}
async function startStatusLineListener(): Promise<{
server: Server
port: number
posts: Record<string, string>[]
}> {
const posts: Record<string, string>[] = []
const server = createServer((req, res) => {
let body = ''
req.setEncoding('utf8')
req.on('data', (chunk) => {
body += chunk
})
req.on('end', () => {
posts.push({ ...Object.fromEntries(new URLSearchParams(body)), path: req.url ?? '' })
res.writeHead(200)
res.end()
})
})
const port = await new Promise<number>((resolve) => {
server.listen(0, '127.0.0.1', () => {
const address = server.address()
resolve(typeof address === 'object' && address ? address.port : 0)
})
})
return { server, port, posts }
}
describe.skipIf(process.platform !== 'win32')('Claude statusLine delivery on Windows', () => {
let home = ''
let server: Server | null = null
afterEach(() => {
server?.close()
server = null
homedirMock.mockReset()
if (home) {
removeTreeSync(home)
home = ''
}
})
async function installInto(prefix: string, seed?: StatusLineSettings) {
home = mkdtempSync(join(tmpdir(), prefix))
homedirMock.mockReturnValue(home)
// Satisfy developer cmd AutoRun entries that reference this file.
writeFileSync(join(home, '.cmd_aliases.cmd'), '@rem\r\n', 'utf8')
if (seed) {
mkdirSync(join(home, '.claude'), { recursive: true })
writeFileSync(settingsPath(home), JSON.stringify(seed))
}
new ClaudeHookService().install(CURRENT_CLAUDE)
const settings: StatusLineSettings = JSON.parse(readFileSync(settingsPath(home), 'utf-8'))
const command = settings.statusLine?.command
if (!command) {
throw new Error('Missing managed statusLine command')
}
const listener = await startStatusLineListener()
server = listener.server
const baseEnv = Object.fromEntries(
// Isolate live Orca endpoints and inherited daemon-worker guards.
Object.entries(process.env).filter(([key]) => !/^(ORCA|CLAUDE)_/.test(key))
)
const run = (program: string, args: string[], paneId: number) =>
runProcess({
program,
args,
input: PAYLOAD,
timeoutMs: 15_000,
env: {
...baseEnv,
USERPROFILE: home,
HOME: home,
// Keep throttle stamps inside the fixture.
TEMP: home,
TMP: home,
ORCA_BACKGROUND_LAUNCH: '1',
ORCA_AGENT_HOOK_PORT: String(listener.port),
ORCA_AGENT_HOOK_TOKEN: HOOK_TOKEN,
ORCA_PANE_KEY: `tab-1:00000000-0000-4000-8000-00000000000${paneId}`
}
})
return { command, posts: listener.posts, run }
}
it('upgrades the runtime-home entry to one Windows PowerShell 5.1 and Git Bash both post through', async () => {
const { command, posts, run } = await installInto('orca-claude-statusline-run-', {
statusLine: { type: 'command', command: LEGACY_COMMAND }
})
expect(command).toBe(
join(home, '.orca', 'agent-hooks', 'claude-statusline.cmd').replaceAll('\\', '/')
)
const legacy = await run(powershellPath(), [...POWERSHELL_ARGS, LEGACY_COMMAND], 0)
expect(legacy.code).not.toBe(0)
expect(posts).toHaveLength(0)
const shells = [
{
name: 'Windows PowerShell',
program: powershellPath(),
args: [...POWERSHELL_ARGS, command]
},
{ name: 'Git Bash', program: findGitBash(), args: ['-c', command] }
]
for (const [index, shell] of shells.entries()) {
const result = await run(shell.program, shell.args, index + 1)
expect(result.timedOut, `${shell.name} timed out`).toBe(false)
expect(result.code, `${shell.name} exit code`).toBe(0)
expect(result.stdout, `${shell.name} stdout`).toBe('')
expect(result.stderr, `${shell.name} stderr`).toBe('')
expect(posts[index]?.path, `${shell.name} posted`).toBe('/statusline/claude')
expect(parseClaudeStatusLineBody(posts[index])).toEqual(EXPECTED_RATE_LIMITS)
}
expect(posts).toHaveLength(shells.length)
}, 60_000)
it('starts no PowerShell per tick for a profile path with a space', async () => {
const { command, posts, run } = await installInto('orca claude statusline space ')
expect(command).toBe(LEGACY_COMMAND)
const result = await run(findGitBash(), ['-xc', command], 1)
expect(result.code).toBe(0)
expect(result.stdout).toBe('')
expect(result.stderr).not.toMatch(/powershell|-EncodedCommand/i)
expect(posts).toHaveLength(1)
expect(parseClaudeStatusLineBody(posts[0])).toEqual(EXPECTED_RATE_LIMITS)
// PowerShell-only hosts with unsafe paths rely on OAuth polling.
await run(powershellPath(), [...POWERSHELL_ARGS, command], 2)
expect(posts).toHaveLength(1)
}, 60_000)
})
@@ -1,139 +0,0 @@
// SDK control replies can overtake queued frames even when the CLI wrote task completion first.
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { spawnProcess } from '@orca/process-host'
import { createAgentChildWorkAdmission } from '../../shared/agent-status/child-work/agent-status-child-work-admission'
import type { AgentChildWorkEvidence } from '../../shared/agent-status/child-work/agent-status-child-work-evidence'
import { reconcileAgentChildWorkEvidence } from '../../shared/agent-status/child-work/agent-status-child-work-reconciliation'
import { createAgentStatusStore } from '../../shared/agent-status/store/agent-status-store'
import { makeStructuredAgentStatusSubject } from '../../shared/agent-status/contracts/agent-status-subject'
import { ClaudeChildWorkDecoder } from './claude-child-work-decoder'
import {
openClaudeStreamJsonConnection,
type ClaudeStreamJsonConnection
} from './claude-stream-json-connection'
import { stopClaudeBackgroundTasks } from './structured/claude-structured-control-actions'
import { CLAUDE_STRUCTURED_BASE_OPTIONS } from './structured/launch/claude-structured-launch-resolution'
import type { ClaudeSession } from './structured/claude-structured-session-state'
const FAKE_CLI = join(__dirname, '__fixtures__', 'claude-agent-sdk-scripted-cli.mjs')
const SESSION_ID = '5348c19f-6a54-4c2e-9c68-9c2b1a3d4e5f'
const parent = makeStructuredAgentStatusSubject(
{ executionHostId: 'local', wslDistro: null, workspaceId: 'ws-1', workspaceKind: 'folder' },
'session-1'
)
const STARTED = {
type: 'system',
subtype: 'task_started',
task_id: 'task-1',
tool_use_id: 'toolu_1',
task_type: 'local_bash',
is_backgrounded: true,
description: 'npm test',
session_id: SESSION_ID,
uuid: 'started-1'
}
const COMPLETED = {
type: 'system',
subtype: 'task_notification',
task_id: 'task-1',
tool_use_id: 'toolu_1',
status: 'completed',
summary: 'all 12 tests passed',
session_id: SESSION_ID,
uuid: 'completed-1'
}
const scratch: string[] = []
const connections: ClaudeStreamJsonConnection[] = []
afterEach(async () => {
for (const connection of connections.splice(0)) {
await connection.close()
}
for (const dir of scratch.splice(0)) {
rmSync(dir, { recursive: true, force: true })
}
})
function streamed(count: number): Record<string, unknown>[] {
return Array.from({ length: count }, (_, index) => ({
type: 'stream_event',
event: { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'x' } },
session_id: SESSION_ID,
uuid: `stream-${index}`
}))
}
async function until(done: () => boolean): Promise<void> {
for (let attempt = 0; attempt < 500 && !done(); attempt += 1) {
await new Promise((resolve) => setTimeout(resolve, 10))
}
expect(done()).toBe(true)
}
/** Emit streamed frames and task completion before the stop reply in one write. */
async function stoppedAsItCompleted(ahead: number) {
const dir = mkdtempSync(join(tmpdir(), 'claude-stop-ack-race-'))
scratch.push(dir)
const scenarioPath = join(dir, 'scenario.json')
writeFileSync(
scenarioPath,
JSON.stringify({
steps: [{ emit: STARTED }, { delayMs: 10_000 }],
controlResponses: { stop_task: {} },
controlResponseLeadingFrames: { stop_task: [...streamed(ahead), COMPLETED] }
})
)
const decoder = new ClaudeChildWorkDecoder()
const evidence: AgentChildWorkEvidence[] = []
const seen: string[] = []
const connection = await openClaudeStreamJsonConnection(
{
pathToClaudeCodeExecutable: FAKE_CLI,
options: { ...CLAUDE_STRUCTURED_BASE_OPTIONS, sessionId: SESSION_ID },
cwd: dir,
env: {
PATH: process.env.PATH ?? '',
ORCA_SDK_CONTRACT_SCENARIO_PATH: scenarioPath,
ORCA_SDK_CONTRACT_REPORT_PATH: join(dir, 'report.json')
}
},
{
onMessage: (message) => {
seen.push(`${String(message.type)}:${String(message.subtype ?? '')}`)
decoder.observe(message)
evidence.push(...decoder.drain(seen.length))
}
},
spawnProcess
)
connections.push(connection)
await until(() => seen.includes('system:task_started'))
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a background stop reads only the session's connection and its child-work decoder.
const session = { connection, childWork: decoder } as unknown as ClaudeSession
await stopClaudeBackgroundTasks(session, 5_000, () => true, ['task-1'])
evidence.push(...decoder.drain(seen.length))
await until(() => seen.includes('system:task_notification'))
const store = createAgentStatusStore({ epoch: 'epoch-1', mode: 'authority' })
store.applyMutation({ parent: { subject: parent } })
let minted = 0
const admission = createAgentChildWorkAdmission(store, {
mintChildWorkId: () => `child-${++minted}`
})
reconcileAgentChildWorkEvidence({ store, admission, parent, provider: 'claude', evidence })
return store.getChildren(parent)
}
describe('a Stop acknowledged ahead of the task’s own earlier completion', () => {
for (const ahead of [0, 1, 5, 50]) {
it(`keeps the task's own outcome and summary with ${ahead} frames ahead of it`, async () => {
expect(await stoppedAsItCompleted(ahead)).toMatchObject([
{ membership: 'settled', outcome: 'succeeded', lastMessage: 'all 12 tests passed' }
])
}, 20_000)
}
})
@@ -1,205 +0,0 @@
import { EventEmitter } from 'node:events'
import { PassThrough } from 'node:stream'
import type { ChildProcessWithoutNullStreams } from 'node:child_process'
import { describe, expect, it, vi } from 'vitest'
import type * as ManagedProviderProcessModule from '../provider-process/managed-provider-process'
import type { query } from '@anthropic-ai/claude-agent-sdk'
import {
CLAUDE_READER_DRAIN_AFTER_EXIT_MS,
openClaudeStreamJsonConnection
} from './claude-stream-json-connection'
const mocks = vi.hoisted(() => {
const refresh = vi.fn()
const closeWriter = vi.fn()
const tree = {
capture: vi.fn(async () => {}),
refresh: (...args: unknown[]) => refresh(...args),
reap: vi.fn(async () => 'exited' as const),
treeVerdict: 'unverifiable' as const,
forcedReapAttempted: false
}
return { closeWriter, refresh, tree }
})
vi.mock('./claude-agent-sdk-exit-proof', () => ({
createClaudeChildTreeReaper: vi.fn(() => mocks.tree)
}))
vi.mock('../provider-process/managed-provider-process', async (importOriginal) => {
const original = await importOriginal<typeof ManagedProviderProcessModule>()
return {
...original,
spawnManagedProviderProcess: (
...args: Parameters<typeof original.spawnManagedProviderProcess>
) => {
const managed = original.spawnManagedProviderProcess(...args)
managed.closeWriter = async () =>
(await mocks.closeWriter())
? { root: 'exited', tree: 'exited' }
: { root: 'live', tree: 'unverifiable' }
return managed
}
}
})
function fakeChild(
streams: { stdout: PassThrough; stderr: PassThrough } = {
stdout: new PassThrough(),
stderr: new PassThrough()
}
): ChildProcessWithoutNullStreams {
const child = new EventEmitter()
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The connection reads only pid, the three pipes and kill, which this fake carries.
return Object.assign(child, {
pid: 424242,
stdin: new PassThrough(),
stdout: streams.stdout,
stderr: streams.stderr,
kill: vi.fn()
}) as unknown as ChildProcessWithoutNullStreams
}
describe('Claude stream-json close ordering', () => {
it('stops pulling SDK messages until reading resumes', async () => {
mocks.refresh.mockReset()
mocks.closeWriter.mockReset()
mocks.refresh.mockResolvedValue(undefined)
mocks.closeWriter.mockResolvedValue(true)
const child = fakeChild()
const first = Promise.withResolvers<Record<string, unknown>>()
const next = vi
.fn<() => Promise<IteratorResult<Record<string, unknown>>>>()
.mockImplementationOnce(async () => ({ value: await first.promise, done: false }))
.mockResolvedValueOnce({ value: { type: 'second' }, done: false })
.mockResolvedValue({ value: undefined, done: true })
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This injected query exercises only the async iterator used by the connection.
const queryImpl = ((params: Parameters<typeof query>[0]) => {
params.options?.spawnClaudeCodeProcess?.({
command: 'claude',
args: [],
env: {},
signal: new AbortController().signal
})
return {
[Symbol.asyncIterator]: () => ({ next })
}
}) as unknown as typeof query
const seen: string[] = []
let connection: Awaited<ReturnType<typeof openClaudeStreamJsonConnection>>
connection = await openClaudeStreamJsonConnection(
{ pathToClaudeCodeExecutable: 'claude', options: {}, cwd: '/work/repo' },
{
onMessage: (message) => {
seen.push(String(message.type))
if (message.type === 'first') {
connection.pauseReading?.()
}
}
},
() => child,
queryImpl
)
first.resolve({ type: 'first' })
await vi.waitFor(() => expect(seen).toEqual(['first']))
await new Promise((resolve) => setImmediate(resolve))
expect(next).toHaveBeenCalledOnce()
connection.resumeReading?.()
await vi.waitFor(() => expect(seen).toEqual(['first', 'second']))
expect(next).toHaveBeenCalledTimes(3)
await expect(connection.close()).resolves.toBe(true)
})
it('releases a pulled frame when provider exit is reported', async () => {
mocks.refresh.mockReset()
mocks.closeWriter.mockReset()
mocks.refresh.mockResolvedValue(undefined)
mocks.closeWriter.mockResolvedValue(true)
const child = fakeChild()
const first = Promise.withResolvers<Record<string, unknown>>()
const next = vi
.fn<() => Promise<IteratorResult<Record<string, unknown>>>>()
.mockImplementationOnce(async () => ({ value: await first.promise, done: false }))
.mockResolvedValue({ value: undefined, done: true })
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This injected query exercises only the async iterator used by the connection.
const queryImpl = ((params: Parameters<typeof query>[0]) => {
params.options?.spawnClaudeCodeProcess?.({
command: 'claude',
args: [],
env: {},
signal: new AbortController().signal
})
return {
[Symbol.asyncIterator]: () => ({ next })
}
}) as unknown as typeof query
const events: string[] = []
const connection = await openClaudeStreamJsonConnection(
{ pathToClaudeCodeExecutable: 'claude', options: {}, cwd: '/work/repo' },
{
onMessage: (message) => events.push(`message:${String(message.type)}`),
onExit: () => events.push('exit')
},
() => child,
queryImpl
)
connection.pauseReading?.()
first.resolve({ type: 'task_notification' })
await vi.waitFor(() => expect(next).toHaveBeenCalledOnce())
expect(events).toEqual([])
child.emit('exit', 1, null)
await vi.waitFor(() => expect(events).toEqual(['exit', 'message:task_notification']))
await expect(connection.close()).resolves.toBe(true)
})
// Inherited pipes must not keep sends and Stops waiting after proven exit.
it('resolves a proven close though the output never ends', async () => {
mocks.refresh.mockReset()
mocks.closeWriter.mockReset()
mocks.refresh.mockResolvedValue(undefined)
mocks.closeWriter.mockResolvedValue(true)
const child = fakeChild()
const next = vi.fn(() => new Promise<IteratorResult<Record<string, unknown>>>(() => {}))
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This injected query exercises only the async iterator used by the connection.
const queryImpl = ((params: Parameters<typeof query>[0]) => {
params.options?.spawnClaudeCodeProcess?.({
command: 'claude',
args: [],
env: {},
signal: new AbortController().signal
})
return {
[Symbol.asyncIterator]: () => ({ next })
}
}) as unknown as typeof query
const connection = await openClaudeStreamJsonConnection(
{ pathToClaudeCodeExecutable: 'claude', options: {}, cwd: '/work/repo' },
{},
() => child,
queryImpl
)
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
vi.useFakeTimers()
try {
let closed: boolean | undefined
void connection.close().then((value) => {
closed = value
})
await vi.advanceTimersByTimeAsync(CLAUDE_READER_DRAIN_AFTER_EXIT_MS - 1)
expect(closed).toBeUndefined()
await vi.advanceTimersByTimeAsync(1)
expect(closed).toBe(true)
expect(warn).toHaveBeenCalledWith(
'[claude-stream-json] output still open after the proven exit:',
expect.anything()
)
} finally {
vi.useRealTimers()
warn.mockRestore()
}
})
})
@@ -1,34 +1,31 @@
import { withOrcaClaudeChatEntrypoint } from '../../shared/agent-launch/startup/claude-chat-entrypoint'
import { claudeStartupAnswerObservation } from './claude-startup-answer-observation'
import { claudeStartupAnswerObservation } from './child-process/claude-startup-answer-observation'
import type { PipedProcessSpawner } from '@orca/process-host/process-spec'
import type * as ClaudeAgentSdk from '@anthropic-ai/claude-agent-sdk'
import type { CanUseTool, OnUserDialog, SDKUserMessage } from '@anthropic-ai/claude-agent-sdk'
import { spawnProcess } from '@orca/process-host'
import { buildClaudeChildProcessEnv } from './claude-child-process-environment'
import { withoutInheritedClaudeConfigDir } from './claude-config-dir-pin'
import { withoutRejectedClaudeApiKey } from './claude-rejected-api-key'
import { buildClaudeChildProcessEnv } from './child-process/claude-child-process-environment'
import { withoutInheritedClaudeConfigDir } from './structured/launch/claude-config-dir-pin'
import { withoutRejectedClaudeApiKey } from './configuration/claude-rejected-api-key'
import {
ClaudeControlRequestError,
createClaudeControlSurface,
type ClaudeControlSurface
} from './claude-agent-sdk-control-requests'
import { createClaudeChildTreeReaper } from './claude-agent-sdk-exit-proof'
} from './sdk-transport/claude-agent-sdk-control-requests'
import { createClaudeChildTreeReaper } from './child-process/claude-agent-sdk-exit-proof'
import { withTimeout } from '../../shared/promise-timeout-fallback'
import type { DescendantTreeVerdict } from '../pty/process-retirement/pty-descendant-exit-verification'
import { claudeChildCloseProven } from './claude-child-exit-proof-ladder'
import { createClaudeCodeProcessSpawn } from './claude-agent-sdk-process-spawn'
import { claudeChildCloseProven } from './child-process/claude-child-exit-proof-ladder'
import { createClaudeCodeProcessSpawn } from './child-process/claude-agent-sdk-process-spawn'
import {
claudeUnwrittenUserMessageError,
createClaudeUserMessageQueue
} from './claude-agent-sdk-user-message-queue'
} from './sdk-transport/claude-agent-sdk-user-message-queue'
import type { ClaudeStructuredSdkOptions } from './structured/launch/claude-structured-launch-resolution'
import { withProviderSpawnAbsence } from '../provider-process/provider-executable-missing'
import { claudeStreamJsonExitError } from './claude-stream-json-exit-error'
import { claudeStreamJsonExitError } from './sdk-transport/claude-stream-json-exit-error'
import { withObservedProviderExit } from '../native-chat/agent-session-wire/startup/structured-agent-session-failure-text'
import type { ProviderProcessCloseOptions } from '../provider-process/provider-process-close'
export { ClaudeControlRequestError }
/** Bound output draining after proven exit so inherited pipes cannot hold close open. */
export const CLAUDE_READER_DRAIN_AFTER_EXIT_MS = 2_000
@@ -1,97 +0,0 @@
import { expect, it, vi } from 'vitest'
import { ClaudeControlRequestTimeoutError } from './claude-agent-sdk-control-requests'
import type { ClaudeStructuredSessionEvent } from './structured/claude-structured-session-state'
import {
acquired,
claudeFrame,
fakeClaude,
tick,
USER_MESSAGE
} from './structured/claude-structured-session-test-support'
it.each(['before-settlement', 'after-settlement'])(
'retires result settings begun during an uncertain control: %s',
async (release) => {
const control = Promise.withResolvers<void>()
const report = Promise.withResolvers<unknown>()
const events: ClaudeStructuredSessionEvent[] = []
const native = fakeClaude({ routes: { set_model: () => control.promise } })
const adapter = await acquired(native, {}, events)
const connection = native.connections[0]!
const session = adapter['sessions'].get('session-1')!
const read = () => adapter.readOptions({ sessionId: 'session-1', fence: 7 })
const finishTurn = () =>
claudeFrame(connection, {
type: 'result',
subtype: 'success',
result: 'previous turn completed',
is_error: false
})
try {
await adapter.setOption({ sessionId: 'session-1', fence: 7, key: 'fastMode', value: 'true' })
await tick()
await adapter.dispatch({
sessionId: 'session-1',
fence: 7,
clientMessageId: 'first',
body: USER_MESSAGE
})
finishTurn()
await tick()
const writing = adapter.dispatch({
sessionId: 'session-1',
fence: 7,
clientMessageId: 'next',
body: USER_MESSAGE,
executionOptions: { model: 'claude-opus-5' }
})
await vi.waitFor(() =>
expect(connection.calls.some((call) => call.subtype === 'set_model')).toBe(true)
)
const settings = vi.spyOn(connection, 'getSettings').mockReturnValueOnce(report.promise)
finishTurn()
await vi.waitFor(() => expect(settings).toHaveBeenCalledOnce())
const stale = {
applied: { model: 'claude-sonnet-5', effort: 'low' },
effective: { effortLevel: 'low', fastMode: false }
}
if (release === 'before-settlement') {
report.resolve(stale)
await tick()
expect((await read()).current.fastMode).toBe(true)
expect(session.appliedOptions).toBeUndefined()
}
control.reject(new ClaudeControlRequestTimeoutError('set_model'))
expect(await writing).toMatchObject({ state: 'rejected' })
report.resolve(stale)
await tick()
const current = (await read()).current
expect(current).toMatchObject({ effort: 'high', fastMode: true })
expect(current.confirmed ?? []).not.toContain('fastMode')
expect(session.appliedOptions).toBeUndefined()
expect(Object.fromEntries(session.appliedInputOptions)).toEqual({})
expect(
events.some(
(event) => event.type === 'options-reported' && event.reportedOptions.effort === 'low'
)
).toBe(false)
native.routes.set_model = () => undefined
await adapter.setOption({ sessionId: 'session-1', fence: 7, key: 'model', value: 'opus' })
settings.mockResolvedValueOnce({
applied: { model: 'claude-opus-5', effort: 'medium' },
effective: { effortLevel: 'medium', fastMode: true }
})
finishTurn()
await vi.waitFor(async () =>
expect((await read()).current).toMatchObject({ effort: 'medium', fastMode: true })
)
expect(session.appliedInputOptions.get('model')).toBe('opus')
expect(session.appliedOptions).toEqual({ model: 'claude-opus-5', effort: 'medium' })
} finally {
report.resolve(null)
control.resolve()
await adapter.closeSession('session-1')
}
}
)
@@ -1,398 +0,0 @@
// Real CLI captures verify waiting children have durable cards and child waits do not alter parent status.
import { readFileSync } from 'node:fs'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { isDeepStrictEqual } from 'node:util'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { parseAgentJournalItemKey } from '../../shared/agent-session/journal/agent-session-journal-item-key'
import type {
AgentJournalRenderItem,
AgentJournalResolution
} from '../../shared/agent-session/journal/agent-session-journal-types'
import type { AgentChildWorkEvidence } from '../../shared/agent-status/child-work/agent-status-child-work-evidence'
import type { AgentStatusStructuredSessionSubject } from '../../shared/agent-status/contracts/agent-status-subject'
import { AgentHookServer } from '../agent-hooks/server/agent-hook-server'
import type { AgentSessionJournal } from '../native-chat/agent-session-journal/journal-store'
import { createTrackedJournalOpener } from '../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support'
import { StructuredAgentSessionCurrentWork } from '../native-chat/agent-session-wire/observations/structured-agent-session-current-work'
import { createDeferredStructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink'
import { testEventSinkLogging } from '../native-chat/agent-session-wire/host/testing/structured-agent-session-logger-test-support'
import { createStructuredAgentSessionLogger } from '../native-chat/agent-session-wire/host/structured-agent-session-logger'
import { StructuredAgentSessionStatusFeed } from '../native-chat/agent-session-wire/observations/structured-agent-session-status-feed'
import { indexedStatusFeedSession } from '../native-chat/agent-session-wire/observations/testing/structured-agent-session-status-feed-test-session'
import { invokeCanUseTool } from './claude-can-use-tool-test-support'
import { ClaudeStructuredSessionAdapter } from './structured/claude-structured-session-adapter'
import type { ClaudeStructuredSessionEvent } from './structured/claude-structured-session-state'
import {
fakeClaude,
identityFor,
PROVIDER_SESSION_ID
} from './structured/claude-structured-session-test-support'
import { claudeStartupSettled } from './structured/claude-structured-startup-settled-test-support'
const SESSION = 'session-1'
const FENCE = 7
type Captured = { from: 'cli' | 'orca'; frame: Record<string, unknown> }
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
function text(value: unknown): string {
return typeof value === 'string' ? value : ''
}
function captured(name: string): Captured[] {
const path = join(__dirname, '__fixtures__', 'claude-subagent-permission-frames.json')
const parsed: unknown = JSON.parse(readFileSync(path, 'utf8'))
const events = isRecord(parsed) && isRecord(parsed.scenarios) ? parsed.scenarios[name] : null
if (!Array.isArray(events)) {
throw new Error(`no captured scenario ${name}`)
}
return events.flatMap((event) =>
isRecord(event) && (event.from === 'cli' || event.from === 'orca') && isRecord(event.frame)
? [{ from: event.from, frame: event.frame }]
: []
)
}
function askerOf(name: string): string {
return text(captured(name).find((event) => event.frame.subtype === 'task_started')?.frame.task_id)
}
const ASKER = askerOf('fg-allow')
function withoutWaits(evidence: AgentChildWorkEvidence[]): AgentChildWorkEvidence[] {
return evidence.map((edge) =>
edge.type === 'live' && edge.child.state === 'waiting'
? { ...edge, child: { ...edge.child, state: 'working' } }
: edge
)
}
function parentRow(server: AgentHookServer) {
const row = server.getStatusSnapshot()[0]
return (
row && {
state: row.state,
workingMode: row.workingMode,
mainAgent: row.mainAgent,
stateStartedAt: row.stateStartedAt
}
)
}
function pendingCards(items: readonly AgentJournalRenderItem[]): AgentJournalRenderItem[] {
return items.filter(
(item) =>
(item.body.kind === 'approval' || item.body.kind === 'question') &&
item.body.resolution.state === 'pending'
)
}
const journals = createTrackedJournalOpener()
let root: string
const hooks: { onEvent?: (event: ClaudeStructuredSessionEvent) => void } = {}
beforeEach(async () => {
root = await mkdtemp(join(tmpdir(), 'orca-claude-subagent-request-'))
})
afterEach(async () => {
hooks.onEvent = undefined
await journals.closeAll()
await rm(root, { recursive: true, force: true })
})
type Publish = { waiting: string[]; askers: string[]; row: unknown; unwaited: unknown }
async function pipeline() {
let clock = 1_700_000_000_000
const now = () => (clock += 1)
const journal: AgentSessionJournal = await journals.open({
identity: identityFor(SESSION),
now,
stateDirectory: join(root, SESSION)
})
const server = new AgentHookServer()
const unwaited = new AgentHookServer()
const publishes: Publish[] = []
let published: AgentStatusStructuredSessionSubject | undefined
const viewOf = (providerId: string) =>
published &&
server.getStructuredChildWorkViews(published).find((view) => view.providerId === providerId)
const record = (subject: AgentStatusStructuredSessionSubject): void => {
published = subject
const cards = pendingCards(journal.snapshot().items)
publishes.push({
waiting: server
.getStructuredChildWorkViews(subject)
.flatMap((view) =>
view.state === 'waiting' && view.membership === 'live' ? [view.providerId ?? '?'] : []
),
askers: cards.flatMap((card) => (card.agentId ? [card.agentId] : [])),
row: parentRow(server),
unwaited: parentRow(unwaited)
})
}
const feed = new StructuredAgentSessionStatusFeed({
logger: createStructuredAgentSessionLogger(),
sessions: new Map([
[
SESSION,
indexedStatusFeedSession({
journal,
child: { generation: 'spawn-9', fence: FENCE, phase: 'ready' },
provider: 'claude'
})
]
]),
getConversation: () => null,
now,
statusSink: () => ({
publish: (summary, subject) => {
server.ingestStructuredStatus(summary, subject)
unwaited.ingestStructuredStatus(summary, subject)
record(subject)
},
forget: (subject) => {
server.dropStructuredStatus(subject)
unwaited.dropStructuredStatus(subject)
},
publishChildWork: (subject, evidence, provider) => {
server.ingestStructuredChildWork(subject, evidence, provider)
unwaited.ingestStructuredChildWork(subject, withoutWaits(evidence), provider)
},
readChildWork: (subject) => server.getStructuredChildWorkViews(subject)
})
})
// Match host publication on sink publish and deferred journal commits.
const deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging(SESSION))
const publishStatus = () => feed.publish(SESSION, journal)
const target = { journal, fence: FENCE, publish: publishStatus }
deferred.bind(target)
let queued = false
journal.observeCommits(() => {
if (!queued) {
queued = true
queueMicrotask(() => {
queued = false
feed.publish(SESSION, journal)
})
}
})
const claude = fakeClaude()
const adapter = new ClaudeStructuredSessionAdapter({
resolveLaunch: async () => ({
pathToClaudeCodeExecutable: 'claude',
options: {},
cwd: '/work/repo',
claudeConfigDir: '/accounts/claude',
providerSessionId: PROVIDER_SESSION_ID,
resumeLeafUuid: null,
resumesTranscript: false,
cliFlag: async () => 'supported' as const,
continuesChain: false
}),
openConnection: claude.openConnection,
readProcessStartTime: async () => 1_700_000_000_000,
now,
persistHandle: async () => {},
onChildWorkEvidence: (sessionId, evidence) => feed.publishChildWork(sessionId, evidence),
onEvent: (event) => hooks.onEvent?.(event)
})
await adapter.acquire({
identity: identityFor(SESSION),
fence: FENCE,
spawnToken: 'spawn-9',
events: deferred.sink
})
await claudeStartupSettled(adapter, SESSION)
const settle = async (): Promise<void> => {
for (let round = 0; round < 3; round += 1) {
expect(await deferred.drained()).toEqual({ ok: true })
await new Promise((resolve) => setTimeout(resolve, 0))
}
}
const hostRecords =
(resolution: Pick<AgentJournalResolution, 'state' | 'selectedOptionId'>, itemId = cardId()) =>
async (): Promise<void> => {
await deferred.drained()
const card = pendingCards(journal.snapshot().items).find((item) => item.itemId === itemId)
const identity = card && parseAgentJournalItemKey(card.itemId)
if (card?.body.kind !== 'approval' || !identity) {
throw new Error('no pending card to record')
}
await journal.appendItem(
identity,
{ ...card.body, resolution: { ...resolution, resolvedBy: 'client-1', resolvedAt: now() } },
{
fence: FENCE,
turnScope: new StructuredAgentSessionCurrentWork(journal, FENCE).turnScope()
}
)
}
const cardId = (): string => {
const card = pendingCards(journal.snapshot().items)[0]
if (!card) {
throw new Error('no pending card')
}
return card.itemId
}
const connection = claude.connections[0]!
const aborts = new Map<string, AbortController>()
const step = async (
{ from, frame }: Captured,
options: { withoutAgentId?: boolean } = {}
): Promise<void> => {
const request = isRecord(frame.request) ? frame.request : null
if (frame.type === 'control_request' && request?.subtype === 'can_use_tool') {
const controller = new AbortController()
aborts.set(text(frame.request_id), controller)
const agentId = options.withoutAgentId ? '' : text(request.agent_id)
invokeCanUseTool(
connection,
text(request.tool_name),
text(frame.request_id),
text(request.tool_use_id),
{
input: isRecord(request.input) ? request.input : {},
signal: controller.signal,
...(agentId ? { agentID: agentId } : {})
}
)
} else if (from === 'cli') {
connection.handlers.onMessage?.({ ...frame, session_id: PROVIDER_SESSION_ID })
}
await settle()
}
const ask = async (name: string, options: { withoutAgentId?: boolean } = {}): Promise<void> => {
const events = captured(name)
const at = events.findIndex((event) => event.frame.type === 'control_request')
for (const event of events.slice(0, at + 1)) {
await step(event, options)
}
}
const violations = () =>
publishes.filter(
(entry) =>
entry.waiting.some((id) => !entry.askers.includes(id)) ||
!isDeepStrictEqual(entry.row, entry.unwaited)
)
const raise = (requestId: string, toolUseId: string, agentId?: string): void => {
const controller = new AbortController()
aborts.set(requestId, controller)
invokeCanUseTool(connection, 'Bash', requestId, toolUseId, {
input: { command: `echo ${requestId}` },
signal: controller.signal,
...(agentId ? { agentID: agentId } : {})
})
}
return {
adapter,
journal,
deferred,
target,
publishStatus,
connection,
now,
raise,
publishes,
violations,
viewOf,
settle,
step,
ask,
cardId,
hostRecords,
aborts
}
}
type Pipeline = Awaited<ReturnType<typeof pipeline>>
function answer(
run: Pipeline,
optionId: 'allow' | 'deny',
commit = run.hostRecords({ state: 'resolved', selectedOptionId: optionId }),
itemId = run.cardId()
) {
return run.adapter.answerPrompt({
sessionId: SESSION,
itemId,
kind: 'approval',
response: { kind: 'option', optionId },
fence: FENCE,
commit
})
}
describe("a Claude subagent's permission request", () => {
it('waits only once its card is written, though the write waits for the journal', async () => {
const run = await pipeline()
const events = captured('fg-allow')
const at = events.findIndex((event) => event.frame.type === 'control_request')
for (const event of events.slice(0, at)) {
await run.step(event)
}
run.deferred.unbind()
run.raise('req-late', 'toolu_late', ASKER)
await new Promise((resolve) => setTimeout(resolve, 0))
run.publishStatus()
expect(run.publishes.at(-1)?.waiting).toEqual([])
run.deferred.bind(run.target)
await run.settle()
expect(run.publishes.at(-1)?.waiting).toEqual([ASKER])
expect(run.violations()).toEqual([])
})
it('waits again, beside its card, when the host fails to record the answer', async () => {
const run = await pipeline()
await run.ask('fg-allow')
await expect(
answer(run, 'allow', async () => {
throw new Error('journal write failed')
})
).rejects.toThrow('journal write failed')
await run.settle()
expect(run.publishes.at(-1)?.waiting).toEqual([ASKER])
expect(run.violations()).toEqual([])
})
it('waits each asking subagent beside its own card, and only those', async () => {
const run = await pipeline()
await run.ask('fg-allow')
const started = captured('fg-allow').find((event) => event.frame.subtype === 'task_started')
await run.step({
from: 'cli',
frame: { ...started?.frame, task_id: 'agent-two', uuid: 'u-two', tool_use_id: 'toolu_two' }
})
run.raise('req-two', 'toolu_two_bash', 'agent-two')
await run.settle()
expect([...(run.publishes.at(-1)?.waiting ?? [])].sort()).toEqual([ASKER, 'agent-two'].sort())
const cardOf = (agentId: string) =>
pendingCards(run.journal.snapshot().items).find((card) => card.agentId === agentId)?.itemId
const first = cardOf(ASKER)
await answer(
run,
'allow',
run.hostRecords({ state: 'resolved', selectedOptionId: 'allow' }, first),
first
)
await run.settle()
expect(run.publishes.at(-1)?.waiting).toEqual(['agent-two'])
const second = cardOf('agent-two')
await answer(
run,
'allow',
run.hostRecords({ state: 'resolved', selectedOptionId: 'allow' }, second),
second
)
await run.settle()
expect(run.publishes.at(-1)?.waiting).toEqual([])
expect(run.violations()).toEqual([])
})
})

Some files were not shown because too many files have changed in this diff Show More