From 532304d4230db91bf96de0bfb2e17551e9723e9c Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 12 Nov 2026 04:11:10 -0800 Subject: [PATCH] refactor(cli): group command handlers and support by feature owner --- .github/workflows/computer-e2e.yml | 6 +- config/flaky-test-pattern-baseline.txt | 2 +- .../process-host-direct-import-baseline.txt | 2 +- config/reliability-gates.jsonc | 18 +- .../cli-runtime-client-deferral-benchmark.mjs | 258 -------- ...li-runtime-client-deferral-equivalence.mjs | 446 -------------- .../account-add-process.test.ts | 2 +- .../account-list-format.ts | 0 .../account-selection.ts | 6 +- .../account-wsl-location.ts | 0 .../{handlers => accounts}/account.test.ts | 2 +- src/cli/{handlers => accounts}/account.ts | 6 +- .../data-account-commands.test.ts | 5 +- .../data-account-commands.ts | 6 +- .../interactive-login-interruption.test.ts | 64 ++ .../interactive-login-interruption.ts | 0 .../opencode-account-login-command.test.ts | 0 .../opencode-account-login-command.ts | 2 +- .../{handlers => agents}/agent-hooks.test.ts | 23 +- src/cli/{handlers => agents}/agent-hooks.ts | 12 +- .../{ => agents}/agent-launch-process.test.ts | 2 +- src/cli/{ => agents}/agent-launch-recovery.ts | 6 +- src/cli/{ => agents}/agent-launch-request.ts | 24 +- .../agent-launch-test-fixtures.ts | 4 +- src/cli/{handlers => agents}/agent-launch.ts | 6 +- src/cli/{handlers => agents}/chat.test.ts | 2 +- src/cli/{handlers => agents}/chat.ts | 4 +- src/cli/{ => artifacts}/artifact-format.ts | 2 +- src/cli/{handlers => artifacts}/artifacts.ts | 6 +- .../automation-destination.ts | 20 +- .../automation-extra-agent-args-flag.ts | 2 +- .../{ => automations}/automation-format.ts | 16 +- .../automation-handler-flags.ts | 2 +- .../automation-host-support.ts | 6 +- .../automation-owner-conflict-recovery.ts | 2 +- .../automation-runs-paging.ts | 7 +- .../automation-setup-flag.ts | 2 +- .../{handlers => automations}/automations.ts | 10 +- src/cli/browser/browser-capture.ts | 2 +- src/cli/browser/browser-cookie.ts | 2 +- src/cli/browser/browser-env.ts | 2 +- src/cli/browser/browser-extension.ts | 2 +- src/cli/browser/browser-identity.ts | 2 +- src/cli/browser/browser-interact.ts | 2 +- src/cli/browser/browser-nav.ts | 2 +- src/cli/browser/browser-profile.ts | 2 +- src/cli/browser/browser-storage.ts | 2 +- src/cli/browser/browser-tab.ts | 2 +- src/cli/cli-error.ts | 2 +- ....test.ts => command-result-output.test.ts} | 2 +- src/cli/command-result-output.ts | 15 + .../computer-action-flag-validation.ts | 2 +- .../computer-action-flags.ts | 2 +- .../computer-action-validation.test.ts | 112 +--- src/cli/{ => computer}/computer-format.ts | 10 +- .../computer-state-formatting.test.ts | 26 +- .../computer-tree-query.test.ts | 6 - src/cli/{ => computer}/computer-tree-query.ts | 2 +- src/cli/{handlers => computer}/computer.ts | 12 +- .../{ => emulator}/emulator-logcat-format.ts | 0 .../emulator-permissions-args.ts | 4 +- src/cli/emulator/emulator.test.ts | 90 +++ src/cli/{handlers => emulator}/emulator.ts | 8 +- .../file-absolute-paths.test.ts | 22 +- src/cli/{handlers => files}/file-open-call.ts | 3 +- .../{handlers => files}/file-open-position.ts | 2 +- src/cli/{handlers => files}/file.test.ts | 26 +- src/cli/{handlers => files}/file.ts | 6 +- src/cli/format.ts | 146 ----- src/cli/handler-group-manifest.ts | 26 +- .../handlers/automation-owner-fencing.test.ts | 76 --- src/cli/handlers/connector.ts | 2 +- src/cli/handlers/core.ts | 3 +- src/cli/handlers/diagnostics.ts | 3 +- src/cli/handlers/emulator.test.ts | 185 ------ src/cli/handlers/environment.ts | 11 +- .../handlers/folder-workspace-mutations.ts | 3 +- .../interactive-login-interruption.test.ts | 136 ----- src/cli/handlers/linear.test.ts | 557 ------------------ src/cli/handlers/managed-server-reconnect.ts | 2 +- src/cli/handlers/managed-server.ts | 2 +- .../orchestration-caller-identity-cli.test.ts | 197 +------ .../orchestration-check-identity.test.ts | 35 +- ...ration-federated-legacy-settlement.test.ts | 53 +- .../orchestration-legacy-read-only.test.ts | 35 +- ...estration-lifecycle-json-rejection.test.ts | 2 +- .../orchestration-lifecycle-rejection.test.ts | 149 +---- .../orchestration-task-list-brief.test.ts | 17 +- .../handlers/orchestration-worker-cli.test.ts | 4 +- src/cli/handlers/orchestration.test.ts | 4 +- src/cli/handlers/orchestration/agent-view.ts | 2 +- .../handlers/orchestration/gate-handlers.ts | 2 +- .../orchestration/message-check-handler.ts | 2 +- .../orchestration/message-inbox-handlers.ts | 2 +- .../orchestration/message-send-handler.ts | 2 +- .../orchestration/question-handler.ts | 2 +- .../handlers/orchestration/run-handlers.ts | 2 +- .../handlers/orchestration/task-handlers.ts | 2 +- .../orchestration/worker-launch-handler.ts | 2 +- .../worker-observation-handlers.ts | 2 +- .../orchestration/worker-terminal-handlers.ts | 2 +- src/cli/handlers/pair.ts | 2 +- src/cli/handlers/profile-state.ts | 2 +- src/cli/handlers/project.ts | 6 +- src/cli/handlers/reference.ts | 2 +- src/cli/handlers/repo.ts | 3 +- src/cli/handlers/serve-restore.ts | 2 +- src/cli/handlers/skill-sharing.ts | 2 +- src/cli/handlers/speech.ts | 2 +- src/cli/handlers/terminal-close.ts | 4 +- src/cli/handlers/terminal-daemon.ts | 2 +- src/cli/handlers/terminal-send.ts | 3 +- src/cli/handlers/terminal.ts | 6 +- src/cli/handlers/worktree-activate.ts | 2 +- .../handlers/worktree-create-agent-launch.ts | 7 +- src/cli/handlers/worktree.ts | 5 +- src/cli/hosts/host-format.ts | 47 ++ src/cli/index-agent-launch.test.ts | 2 +- src/cli/{ => jira}/jira-format.ts | 2 +- src/cli/{ => jira}/jira-handler-group.ts | 4 +- src/cli/{ => jira}/jira-target.ts | 14 +- src/cli/{handlers => jira}/jira-write.test.ts | 2 +- src/cli/{handlers => jira}/jira-write.ts | 9 +- src/cli/{handlers => jira}/jira.ts | 8 +- .../linear-comment-write.ts | 8 +- src/cli/{ => linear}/linear-format.ts | 22 +- src/cli/{ => linear}/linear-handler-group.ts | 4 +- .../linear-list-issues.ts | 8 +- .../linear-relation-write.ts | 10 +- .../{ => linear}/linear-request-builders.ts | 12 +- .../{ => linear}/linear-save-issue-request.ts | 6 +- .../{handlers => linear}/linear-save-issue.ts | 12 +- src/cli/linear/linear.test.ts | 164 ++++++ src/cli/{handlers => linear}/linear.ts | 22 +- .../orchestration-session-caller-cli.test.ts | 210 +------ ...ion-structured-session-no-identity.test.ts | 11 +- src/cli/reference-input.ts | 2 +- src/cli/runtime/cli-status-format.ts | 27 + src/cli/runtime/client-recovery.test.ts | 2 +- .../agent-session-search-format.ts | 6 +- .../search-command-arguments.test.ts | 6 +- .../search-command-arguments.ts | 10 +- .../{handlers => session-search}/search.ts | 8 +- src/cli/{ => workspace-ports}/ports-format.ts | 2 +- .../{handlers => workspace-ports}/ports.ts | 14 +- .../cli-runtime-boundary.test.ts | 4 +- tests/e2e/agent-launch-cli.unit.test.ts | 45 +- 147 files changed, 741 insertions(+), 3037 deletions(-) delete mode 100644 config/scripts/performance/transport/cli-runtime-client-deferral-benchmark.mjs delete mode 100644 config/scripts/performance/transport/cli-runtime-client-deferral-equivalence.mjs rename src/cli/{ => accounts}/account-add-process.test.ts (99%) rename src/cli/{handlers => accounts}/account-list-format.ts (100%) rename src/cli/{handlers => accounts}/account-selection.ts (98%) rename src/cli/{handlers => accounts}/account-wsl-location.ts (100%) rename src/cli/{handlers => accounts}/account.test.ts (99%) rename src/cli/{handlers => accounts}/account.ts (98%) rename src/cli/{handlers => accounts}/data-account-commands.test.ts (96%) rename src/cli/{handlers => accounts}/data-account-commands.ts (97%) create mode 100644 src/cli/accounts/interactive-login-interruption.test.ts rename src/cli/{handlers => accounts}/interactive-login-interruption.ts (100%) rename src/cli/{handlers => accounts}/opencode-account-login-command.test.ts (100%) rename src/cli/{handlers => accounts}/opencode-account-login-command.ts (99%) rename src/cli/{handlers => agents}/agent-hooks.test.ts (96%) rename src/cli/{handlers => agents}/agent-hooks.ts (96%) rename src/cli/{ => agents}/agent-launch-process.test.ts (98%) rename src/cli/{ => agents}/agent-launch-recovery.ts (93%) rename src/cli/{ => agents}/agent-launch-request.ts (86%) rename src/cli/{ => agents}/agent-launch-test-fixtures.ts (80%) rename src/cli/{handlers => agents}/agent-launch.ts (93%) rename src/cli/{handlers => agents}/chat.test.ts (97%) rename src/cli/{handlers => agents}/chat.ts (95%) rename src/cli/{ => artifacts}/artifact-format.ts (88%) rename src/cli/{handlers => artifacts}/artifacts.ts (97%) rename src/cli/{ => automations}/automation-destination.ts (84%) rename src/cli/{handlers => automations}/automation-extra-agent-args-flag.ts (90%) rename src/cli/{ => automations}/automation-format.ts (91%) rename src/cli/{handlers => automations}/automation-handler-flags.ts (99%) rename src/cli/{handlers => automations}/automation-host-support.ts (88%) rename src/cli/{ => automations}/automation-owner-conflict-recovery.ts (95%) rename src/cli/{ => automations}/automation-runs-paging.ts (89%) rename src/cli/{handlers => automations}/automation-setup-flag.ts (95%) rename src/cli/{handlers => automations}/automations.ts (98%) rename src/cli/{format.test.ts => command-result-output.test.ts} (96%) create mode 100644 src/cli/command-result-output.ts rename src/cli/{handlers => computer}/computer-action-flag-validation.ts (98%) rename src/cli/{handlers => computer}/computer-action-flags.ts (99%) rename src/cli/{handlers => computer}/computer-action-validation.test.ts (63%) rename src/cli/{ => computer}/computer-format.ts (96%) rename src/cli/{handlers => computer}/computer-state-formatting.test.ts (88%) rename src/cli/{ => computer}/computer-tree-query.test.ts (82%) rename src/cli/{ => computer}/computer-tree-query.ts (97%) rename src/cli/{handlers => computer}/computer.ts (97%) rename src/cli/{ => emulator}/emulator-logcat-format.ts (100%) rename src/cli/{ => emulator}/emulator-permissions-args.ts (88%) create mode 100644 src/cli/emulator/emulator.test.ts rename src/cli/{handlers => emulator}/emulator.ts (97%) rename src/cli/{handlers => files}/file-absolute-paths.test.ts (80%) rename src/cli/{handlers => files}/file-open-call.ts (90%) rename src/cli/{handlers => files}/file-open-position.ts (95%) rename src/cli/{handlers => files}/file.test.ts (84%) rename src/cli/{handlers => files}/file.ts (98%) delete mode 100644 src/cli/format.ts delete mode 100644 src/cli/handlers/automation-owner-fencing.test.ts delete mode 100644 src/cli/handlers/emulator.test.ts delete mode 100644 src/cli/handlers/interactive-login-interruption.test.ts delete mode 100644 src/cli/handlers/linear.test.ts create mode 100644 src/cli/hosts/host-format.ts rename src/cli/{ => jira}/jira-format.ts (98%) rename src/cli/{ => jira}/jira-handler-group.ts (81%) rename src/cli/{ => jira}/jira-target.ts (84%) rename src/cli/{handlers => jira}/jira-write.test.ts (97%) rename src/cli/{handlers => jira}/jira-write.ts (96%) rename src/cli/{handlers => jira}/jira.ts (97%) rename src/cli/{handlers => linear}/linear-comment-write.ts (91%) rename src/cli/{ => linear}/linear-format.ts (93%) rename src/cli/{ => linear}/linear-handler-group.ts (85%) rename src/cli/{handlers => linear}/linear-list-issues.ts (92%) rename src/cli/{handlers => linear}/linear-relation-write.ts (82%) rename src/cli/{ => linear}/linear-request-builders.ts (96%) rename src/cli/{ => linear}/linear-save-issue-request.ts (93%) rename src/cli/{handlers => linear}/linear-save-issue.ts (57%) create mode 100644 src/cli/linear/linear.test.ts rename src/cli/{handlers => linear}/linear.ts (97%) create mode 100644 src/cli/runtime/cli-status-format.ts rename src/cli/{ => session-search}/agent-session-search-format.ts (95%) rename src/cli/{ => session-search}/search-command-arguments.test.ts (95%) rename src/cli/{ => session-search}/search-command-arguments.ts (93%) rename src/cli/{handlers => session-search}/search.ts (90%) rename src/cli/{ => workspace-ports}/ports-format.ts (98%) rename src/cli/{handlers => workspace-ports}/ports.ts (94%) diff --git a/.github/workflows/computer-e2e.yml b/.github/workflows/computer-e2e.yml index d2c6add6c4a..fd3d586c8d2 100644 --- a/.github/workflows/computer-e2e.yml +++ b/.github/workflows/computer-e2e.yml @@ -97,9 +97,9 @@ jobs: src/main/computer/macos-native/macos-native-provider-client.test.ts src/main/providers/windows-shell-preflight-runtime.windows.test.ts src/main/computer/desktop-script/actions/desktop-script-provider-actions.test.ts - src/cli/format.test.ts - src/cli/handlers/computer-action-validation.test.ts - src/cli/handlers/computer-state-formatting.test.ts + src/cli/command-result-output.test.ts + src/cli/computer/computer-action-validation.test.ts + src/cli/computer/computer-state-formatting.test.ts src/cli/index.test.ts src/cli/runtime/envelope-schema.test.ts src/shared/remote-runtime/remote-runtime-client.test.ts diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index 1485eab2a40..af6ef5c37d5 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -570,7 +570,7 @@ 4 test-no-wall-clock:tests/e2e/cross-version-wire/release-checkout.unit.test.ts 2 test-no-wall-clock:tests/e2e/cross-version-wire/release-source-retention.unit.test.ts 1 test-no-wall-clock:tests/e2e/host-cold-park-remote-subscriber.unit.test.ts -1 test-timeout-needs-reason:src/cli/agent-launch-process.test.ts +1 test-timeout-needs-reason:src/cli/agents/agent-launch-process.test.ts 1 test-timeout-needs-reason:src/cli/runtime/serve-pid1-init-reaper.test.ts 1 test-timeout-needs-reason:src/cli/skills-install.test.ts 2 test-timeout-needs-reason:src/main/acp/journal/acp-structured-broken-stream.test.ts diff --git a/config/process-host-direct-import-baseline.txt b/config/process-host-direct-import-baseline.txt index 9d4ce1367dd..f01185f213e 100644 --- a/config/process-host-direct-import-baseline.txt +++ b/config/process-host-direct-import-baseline.txt @@ -2,7 +2,7 @@ # Existing production source files importing child_process at runtime outside @orca/process-host. # Migration debt: this list may only shrink; new callers use the package public API. src/cli/handlers/core.ts -src/cli/handlers/interactive-login-interruption.ts +src/cli/accounts/interactive-login-interruption.ts src/cli/runtime/launch.ts src/main/agent-hooks/installation/locking/managed-hook-owner-identity.ts src/main/ai-vault/scan-service/session-scanner-service-spawn.ts diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index 79e2d5a8f67..e5f32953ffe 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -10542,7 +10542,7 @@ "providers": ["local", "daemon", "ssh", "wsl", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": [], - "coverageNotes": "Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. The complete federation-lifecycle-settlement suite is removed, losing its fake remote settlement/protocol/acknowledgment examples. Its exact standalone command, testFiles entry and complete assertionRef are retired and prior fields archived. Existing receipts select unrelated migration and compiled CLI journeys and retain original scopes. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit2923 accepts loss of the first/replayed attested legacy worker_done CLI acceptance alarms, including exact send parameters, sender pane proof, lifecycle-wait flag and minted mutation identity. The removed fixture supplied settled runtime verdicts; it did not execute settlement authority, durable replay or outage recovery. Reduced selectors have no new execution, fault-control or equivalent replacement credit. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. NEXT136 retains only unchanged execution receipts at their original scopes. Reduced-source selectors and retained static assertions have no new execution or equivalent replacement credit.", + "coverageNotes": "CLI ownership cleanup retires low-value test cases, including explicit-current no-read, legacy success/idempotent acceptance, and caller-pane routing examples. Retained refusal and recovery assertions are listed below; dated receipts keep their original scopes. Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. The complete federation-lifecycle-settlement suite is removed, losing its fake remote settlement/protocol/acknowledgment examples. Its exact standalone command, testFiles entry and complete assertionRef are retired and prior fields archived. Existing receipts select unrelated migration and compiled CLI journeys and retain original scopes. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit2923 accepts loss of the first/replayed attested legacy worker_done CLI acceptance alarms, including exact send parameters, sender pane proof, lifecycle-wait flag and minted mutation identity. The removed fixture supplied settled runtime verdicts; it did not execute settlement authority, durable replay or outage recovery. Reduced selectors have no new execution, fault-control or equivalent replacement credit. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. NEXT136 retains only unchanged execution receipts at their original scopes. Reduced-source selectors and retained static assertions have no new execution or equivalent replacement credit.", "motivatingLinks": [ "https://github.com/stablyai/orca/pull/11107#discussion_r3663321387", "https://github.com/stablyai/orca/issues/13858", @@ -10590,12 +10590,10 @@ { "file": "src/cli/handlers/orchestration-lifecycle-rejection.test.ts", "assertions": [ - "an explicit current worker_done verdict completes without a compatibility read", - "a worker_done response without a lifecycle verdict checks the exact authoritative Dispatch and report receipt", - "legacy succeeded and failed reports require matching terminal Task and Dispatch state", + "a worker_done response without a lifecycle verdict fails closed when authoritative Dispatch and report state cannot confirm settlement", "stopped or stale Dispatches cannot impersonate report settlement", - "an idempotent retry accepts the first authoritative report from the same worker", - "a Run-home relay rejection reaches the CLI error boundary" + "a Run-home relay rejection reaches the CLI error boundary", + "post-verification failure preserves the worker_done mutation identity for recovery" ] }, { @@ -10604,10 +10602,7 @@ }, { "file": "src/cli/handlers/orchestration-check-identity.test.ts", - "assertions": [ - "implicit check carries the caller pane key with a potentially stale environment handle", - "explicit legacy terminal inspection does not inherit the caller pane key" - ] + "assertions": ["an empty explicit --terminal is refused before reading a mailbox"] }, { "file": "src/main/runtime/rpc/methods/orchestration/messaging/check.test.ts", @@ -10747,7 +10742,8 @@ "Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. The complete federation-lifecycle-settlement suite is removed, losing its fake remote settlement/protocol/acknowledgment examples. Its exact standalone command, testFiles entry and complete assertionRef are retired and prior fields archived. Existing receipts select unrelated migration and compiled CLI journeys and retain original scopes. All prior notes and dated/archived evidence retain original scopes.", "Complete prior commands before federation-lifecycle suite retirement: [\"ORCA_BACKGROUND_LAUNCH=1 npx vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/messaging/check-worker-federated-attachment.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/cli/handlers/orchestration.test.ts src/cli/handlers/orchestration-check-identity.test.ts src/cli/handlers/orchestration-worker-cli.test.ts src/main/runtime/rpc/methods/orchestration/worker/composed-workers.test.ts src/main/runtime/rpc/methods/orchestration/messaging/check.test.ts src/main/runtime/rpc/methods/orchestration/messaging/send.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/cli/handlers/orchestration-lifecycle-rejection.test.ts src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/federation/federation.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/federation/federation-lifecycle-settlement.test.ts --reporter=dot\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orchestration/db/federation/federation-acknowledgment-migration.test.ts --reporter=dot\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts\",\"pnpm run test:e2e -- tests/e2e/orchestration-worker-terminal-visibility.spec.ts --workers=1\",\"pnpm run build:cli && SKIP_BUILD=1 pnpm exec playwright test tests/e2e/orchestration-worker-settlement-release-cli.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"]", "Complete prior testFiles before federation-lifecycle suite retirement: [\"src/main/runtime/rpc/methods/orchestration/messaging/check-worker-federated-attachment.test.ts\",\"src/main/runtime/construction/orca-runtime.test.ts\",\"src/cli/handlers/orchestration.test.ts\",\"src/cli/handlers/orchestration-lifecycle-rejection.test.ts\",\"src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts\",\"src/cli/handlers/orchestration-check-identity.test.ts\",\"src/cli/handlers/orchestration-worker-cli.test.ts\",\"src/main/runtime/rpc/methods/orchestration/worker/composed-workers.test.ts\",\"src/main/runtime/rpc/methods/orchestration/messaging/check.test.ts\",\"src/main/runtime/rpc/methods/orchestration/messaging/send.test.ts\",\"src/main/runtime/rpc/methods/orchestration/federation/federation.test.ts\",\"src/main/runtime/rpc/methods/orchestration/federation/federation-lifecycle-settlement.test.ts\",\"src/main/runtime/orchestration/db/federation/federation-acknowledgment-migration.test.ts\",\"tests/e2e/orchestration-worker-terminal-visibility.spec.ts\",\"tests/e2e/orchestration-worker-settlement-release-cli.spec.ts\"]", - "Complete prior assertionRefs before federation-lifecycle suite retirement: [{\"file\":\"src/main/runtime/rpc/methods/orchestration/messaging/check-worker-federated-attachment.test.ts\",\"assertions\":[\"replays the coordinator instruction and takes its ack after the app restarts\",\"files loopback mail once under the local Dispatch Run without replacing its owner\"]},{\"file\":\"src/cli/handlers/orchestration-lifecycle-rejection.test.ts\",\"assertions\":[\"an explicit current worker_done verdict completes without a compatibility read\",\"a worker_done response without a lifecycle verdict checks the exact authoritative Dispatch and report receipt\",\"legacy succeeded and failed reports require matching terminal Task and Dispatch state\",\"stopped or stale Dispatches cannot impersonate report settlement\",\"an idempotent retry accepts the first authoritative report from the same worker\",\"a Run-home relay rejection reaches the CLI error boundary\"]},{\"file\":\"src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts\",\"assertions\":[\"a rejected lifecycle verdict is emitted as a JSON ok=false envelope\"]},{\"file\":\"src/cli/handlers/orchestration-check-identity.test.ts\",\"assertions\":[\"implicit check carries the caller pane key with a potentially stale environment handle\",\"explicit legacy terminal inspection does not inherit the caller pane key\"]},{\"file\":\"src/main/runtime/rpc/methods/orchestration/messaging/check.test.ts\",\"assertions\":[\"Run delivery resolves through a stable coordinator pane after handle remint\",\"a live handle cannot be retargeted by mismatched pane metadata\"]},{\"file\":\"src/main/runtime/rpc/methods/orchestration/messaging/send.test.ts\",\"assertions\":[\"Dispatch delivery resolves through a stable worker pane after handle remint\"]},{\"file\":\"src/main/runtime/rpc/methods/orchestration/federation/federation-lifecycle-settlement.test.ts\",\"assertions\":[\"a remote worker_done waits for Run-home settlement even when an older CLI omits the wait hint\",\"a current Run home still completes reports from legacy protocol v1/v2 worker servers\",\"persisted protocol v1/v2 workers retain legacy-compatible completion after their worker server updates\",\"preexisting same-outcome terminal ACK batches settle atomically while conflicting outcomes acknowledge nothing\",\"an aborted settlement wait returns operation_unknown instead of accepted success\",\"a Run-home terminal verdict settles the remote attachment and revokes its capability\",\"a terminal verdict cannot settle an unrelated relay item\",\"a terminal verdict cannot contradict the exact queued worker report outcome\",\"a rejected report replays its exact verdict without mutating durable rejection mail twice\"]},{\"file\":\"src/main/runtime/orchestration/db/federation/federation-acknowledgment-migration.test.ts\",\"assertions\":[\"a v26 database gains a zeroed durable home-to-worker acknowledgment watermark\",\"a complete v26 database starts migration at v26 rather than replaying v7-v26\",\"the migration advances schema version without losing the imported relay cursor\"]},{\"file\":\"tests/e2e/orchestration-worker-terminal-visibility.spec.ts\",\"assertions\":[\"worker-start exposes one inactive worker tab before workspace navigation\",\"the coordinator tab remains active\",\"ACK delivery reaches a stable coordinator pane through a stale handle\",\"one spawn remains live with no interruption event\",\"PTY/incarnation, tab, leaf, worktree, Task, and Dispatch identities remain stable\",\"workspace re-entry does not duplicate the worker tab or print Conversation interrupted\"]},{\"file\":\"tests/e2e/orchestration-worker-settlement-release-cli.spec.ts\",\"assertions\":[\"a compiled CLI worker_done with the wrong identity exits nonzero with ok=false\",\"the exact Task and Dispatch remain dispatched after rejection\",\"the correct worker identity receives an explicit completed lifecycle verdict\",\"an independent runtime read observes the Dispatch completed\"]}]" + "Complete prior assertionRefs before federation-lifecycle suite retirement: [{\"file\":\"src/main/runtime/rpc/methods/orchestration/messaging/check-worker-federated-attachment.test.ts\",\"assertions\":[\"replays the coordinator instruction and takes its ack after the app restarts\",\"files loopback mail once under the local Dispatch Run without replacing its owner\"]},{\"file\":\"src/cli/handlers/orchestration-lifecycle-rejection.test.ts\",\"assertions\":[\"an explicit current worker_done verdict completes without a compatibility read\",\"a worker_done response without a lifecycle verdict checks the exact authoritative Dispatch and report receipt\",\"legacy succeeded and failed reports require matching terminal Task and Dispatch state\",\"stopped or stale Dispatches cannot impersonate report settlement\",\"an idempotent retry accepts the first authoritative report from the same worker\",\"a Run-home relay rejection reaches the CLI error boundary\"]},{\"file\":\"src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts\",\"assertions\":[\"a rejected lifecycle verdict is emitted as a JSON ok=false envelope\"]},{\"file\":\"src/cli/handlers/orchestration-check-identity.test.ts\",\"assertions\":[\"implicit check carries the caller pane key with a potentially stale environment handle\",\"explicit legacy terminal inspection does not inherit the caller pane key\"]},{\"file\":\"src/main/runtime/rpc/methods/orchestration/messaging/check.test.ts\",\"assertions\":[\"Run delivery resolves through a stable coordinator pane after handle remint\",\"a live handle cannot be retargeted by mismatched pane metadata\"]},{\"file\":\"src/main/runtime/rpc/methods/orchestration/messaging/send.test.ts\",\"assertions\":[\"Dispatch delivery resolves through a stable worker pane after handle remint\"]},{\"file\":\"src/main/runtime/rpc/methods/orchestration/federation/federation-lifecycle-settlement.test.ts\",\"assertions\":[\"a remote worker_done waits for Run-home settlement even when an older CLI omits the wait hint\",\"a current Run home still completes reports from legacy protocol v1/v2 worker servers\",\"persisted protocol v1/v2 workers retain legacy-compatible completion after their worker server updates\",\"preexisting same-outcome terminal ACK batches settle atomically while conflicting outcomes acknowledge nothing\",\"an aborted settlement wait returns operation_unknown instead of accepted success\",\"a Run-home terminal verdict settles the remote attachment and revokes its capability\",\"a terminal verdict cannot settle an unrelated relay item\",\"a terminal verdict cannot contradict the exact queued worker report outcome\",\"a rejected report replays its exact verdict without mutating durable rejection mail twice\"]},{\"file\":\"src/main/runtime/orchestration/db/federation/federation-acknowledgment-migration.test.ts\",\"assertions\":[\"a v26 database gains a zeroed durable home-to-worker acknowledgment watermark\",\"a complete v26 database starts migration at v26 rather than replaying v7-v26\",\"the migration advances schema version without losing the imported relay cursor\"]},{\"file\":\"tests/e2e/orchestration-worker-terminal-visibility.spec.ts\",\"assertions\":[\"worker-start exposes one inactive worker tab before workspace navigation\",\"the coordinator tab remains active\",\"ACK delivery reaches a stable coordinator pane through a stale handle\",\"one spawn remains live with no interruption event\",\"PTY/incarnation, tab, leaf, worktree, Task, and Dispatch identities remain stable\",\"workspace re-entry does not duplicate the worker tab or print Conversation interrupted\"]},{\"file\":\"tests/e2e/orchestration-worker-settlement-release-cli.spec.ts\",\"assertions\":[\"a compiled CLI worker_done with the wrong identity exits nonzero with ok=false\",\"the exact Task and Dispatch remain dispatched after rejection\",\"the correct worker identity receives an explicit completed lifecycle verdict\",\"an independent runtime read observes the Dispatch completed\"]}]", + "CLI ownership cleanup intentionally removes the retired success, routing and work-count alarms without replacement. Prior CLI assertion references: [{\"file\":\"src/cli/handlers/orchestration-lifecycle-rejection.test.ts\",\"assertions\":[\"an explicit current worker_done verdict completes without a compatibility read\",\"a worker_done response without a lifecycle verdict checks the exact authoritative Dispatch and report receipt\",\"legacy succeeded and failed reports require matching terminal Task and Dispatch state\",\"stopped or stale Dispatches cannot impersonate report settlement\",\"an idempotent retry accepts the first authoritative report from the same worker\",\"a Run-home relay rejection reaches the CLI error boundary\"]},{\"file\":\"src/cli/handlers/orchestration-check-identity.test.ts\",\"assertions\":[\"implicit check carries the caller pane key with a potentially stale environment handle\",\"explicit legacy terminal inspection does not inherit the caller pane key\"]}]" ], "demotionRule": "Keep experimental or demote if either Electron journey flakes without a product or harness defect, if local worker-start can return before tab materialization without an explicit reveal warning, if focus moves to the worker, if restart or workspace re-entry spawns/resumes/duplicates/interferes with the worker, if retained output becomes unreadable, or if pane-stable delivery reads the wrong mailbox." }, diff --git a/config/scripts/performance/transport/cli-runtime-client-deferral-benchmark.mjs b/config/scripts/performance/transport/cli-runtime-client-deferral-benchmark.mjs deleted file mode 100644 index 21e3e86cabc..00000000000 --- a/config/scripts/performance/transport/cli-runtime-client-deferral-benchmark.mjs +++ /dev/null @@ -1,258 +0,0 @@ -#!/usr/bin/env node -// Compare real CLI emits before/after deferring RuntimeClient’s Zod/ws/tweetnacl/store graph until after flag validation. -// Restore seven baseline files; use fresh processes to measure cold graphs, alternate arm order, and verify output/exit equality before timing. -import { execFileSync, spawnSync } from 'node:child_process' -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { join } from 'node:path' -import { performance } from 'node:perf_hooks' -import { fileURLToPath } from 'node:url' - -const REPO = fileURLToPath(new URL('../../../..', import.meta.url)) - -const ROUNDS = Number(process.env.ORCA_CLI_DEFER_BENCH_ROUNDS ?? '30') -const WARMUP = Number(process.env.ORCA_CLI_DEFER_BENCH_WARMUP ?? '3') - -for (const [name, value] of [ - ['ORCA_CLI_DEFER_BENCH_ROUNDS', ROUNDS], - ['ORCA_CLI_DEFER_BENCH_WARMUP', WARMUP] -]) { - if (!Number.isSafeInteger(value) || value <= 0) { - throw new Error(`${name} must be a positive integer, received ${value}`) - } -} -if (ROUNDS % 2 !== 0) { - // Why: arms alternate which one leads; an odd count biases one arm. - throw new Error(`ORCA_CLI_DEFER_BENCH_ROUNDS must be even, received ${ROUNDS}`) -} - -const TOUCHED = [ - 'src/cli/args.ts', - 'src/cli/dispatch.ts', - 'src/cli/flags.ts', - 'src/cli/format.ts', - 'src/cli/index.ts', - 'src/cli/runtime/client.ts', - 'src/cli/selectors.ts' -] - -// Re-read production call forms so reverting deferral cannot make both arms identical; prose mentions must not satisfy the guard. -function assertMarkersFresh() { - const checks = [ - ['src/cli/index.ts', "await import('./runtime-client.js')"], - ['src/cli/index.ts', 'await loadRuntimeClientClass()'], - ['src/cli/index.ts', "import type { RuntimeClient } from './runtime-client'"], - ['src/cli/runtime/client.ts', "await import('./websocket-transport.js')"], - ['src/cli/runtime/client.ts', 'await loadSendWebSocketRequest()'], - ['src/cli/args.ts', "import { RuntimeClientError } from './runtime/types'"], - ['src/cli/flags.ts', "import { RuntimeClientError } from './runtime/types'"], - ['src/cli/dispatch.ts', "import { RuntimeClientError } from './runtime/types'"], - ['src/cli/selectors.ts', "import { RuntimeClientError } from './runtime/types'"], - ['src/cli/format.ts', "} from './runtime/types'"] - ] - for (const [file, marker] of checks) { - if (!readFileSync(join(REPO, file), 'utf8').includes(marker)) { - throw new Error( - `${file} no longer contains \`${marker}\` — cli-runtime-client-deferral-benchmark.mjs is stale` - ) - } - } -} - -function buildArm(label, baselineRev) { - // Build inside repo so emitted modules resolve its node_modules. - const outDir = join(REPO, `.bench-out-${label}`) - rmSync(outDir, { recursive: true, force: true }) - const restore = [] - try { - if (baselineRev) { - for (const file of TOUCHED) { - const path = join(REPO, file) - restore.push([path, readFileSync(path)]) - writeFileSync( - path, - execFileSync('git', ['show', `${baselineRev}:${file}`], { - cwd: REPO, - maxBuffer: 64 * 1024 * 1024 - }) - ) - } - } - execFileSync( - 'npx', - [ - 'tsc', - '-p', - 'config/tsconfig.cli.json', - '--outDir', - outDir, - '--composite', - 'false', - '--incremental', - 'false' - ], - { cwd: REPO, stdio: 'inherit' } - ) - } finally { - for (const [path, contents] of restore) { - writeFileSync(path, contents) - } - } - return join(outDir, 'cli/index.js') -} - -function run(entry, argv, env) { - const result = spawnSync(process.execPath, [entry, ...argv], { - cwd: REPO, - env: { ...process.env, ...env }, - encoding: 'buffer' - }) - if (result.error) { - throw result.error - } - return { - status: result.status, - stdout: result.stdout.toString('utf8'), - stderr: result.stderr.toString('utf8') - } -} - -// Count eager CJS graph in a child via Module._load, measuring the graph deferral actually moves. -function countEagerModules(entry) { - const probe = ` - const Module = require('module') - const original = Module._load - const seen = new Set() - Module._load = function (request, parent, isMain) { - try { seen.add(Module._resolveFilename(request, parent, isMain)) } catch { seen.add(request) } - return original.apply(this, arguments) - } - require(${JSON.stringify(entry)}) - const all = [...seen] - process.stdout.write(JSON.stringify({ - total: all.length, - nodeModules: all.filter((p) => p.includes('node_modules')).length - })) - ` - const result = spawnSync(process.execPath, ['-e', probe], { cwd: REPO, encoding: 'utf8' }) - if (result.status !== 0) { - throw new Error(`module probe failed: ${result.stderr}`) - } - return JSON.parse(result.stdout) -} - -const median = (values) => { - const sorted = [...values].sort((a, b) => a - b) - return sorted[Math.floor(sorted.length / 2)] -} - -const baselineIndex = process.argv.indexOf('--baseline') -const baselineRev = baselineIndex === -1 ? 'HEAD' : process.argv[baselineIndex + 1] - -assertMarkersFresh() - -const userDataPath = mkdtempSync(join(REPO, '.bench-userdata-')) - -try { - console.log(`Building eager baseline (${baselineRev}) …`) - const eagerEntry = buildArm('eager', baselineRev) - console.log('Building deferred (working tree) …') - const deferredEntry = buildArm('deferred', null) - - const eagerGraph = countEagerModules(eagerEntry) - const deferredGraph = countEagerModules(deferredEntry) - console.log( - `\nEager modules at process load: ${eagerGraph.total} -> ${deferredGraph.total} ` + - `(node_modules ${eagerGraph.nodeModules} -> ${deferredGraph.nodeModules})` - ) - if (deferredGraph.total >= eagerGraph.total) { - throw new Error( - 'deferred arm loads no fewer modules — the fixture does not exercise the change' - ) - } - - // Use empty user-data dirs for deterministic runtime-dependent cases. - const isolated = { ORCA_USER_DATA_PATH: userDataPath } - /** @type {Array<[string, string[], Record]>} */ - const cases = [ - ['orca --help', ['--help'], {}], - ['orca help worktree', ['help', 'worktree'], {}], - ['orca (no args)', [], {}], - ['unknown command', ['no-such-command'], {}], - ['unknown flag', ['worktree', 'list', '--nope'], {}], - ['orca agent-context --json', ['agent-context', '--json'], {}], - ['orca status --json', ['status', '--json'], isolated], - ['orca worktree list --json', ['worktree', 'list', '--json'], isolated] - ] - - // Compare output/exit before timing or a broken arm printing nothing appears fastest. - for (const [label, argv, env] of cases) { - const before = run(eagerEntry, argv, env) - const after = run(deferredEntry, argv, env) - if ( - before.status !== after.status || - before.stdout !== after.stdout || - before.stderr !== after.stderr - ) { - throw new Error(`arms disagree for "${label}" — refusing to report a timing`) - } - if (before.stdout.length + before.stderr.length === 0) { - throw new Error(`"${label}" produced no output on either arm; it proves nothing`) - } - } - - const pad = (value, width) => String(value).padStart(width) - console.log('\nFresh process per sample, wall clock. Lower is better.') - console.log(`rounds=${ROUNDS} warmup=${WARMUP} (per-arm median, arms alternate lead)`) - console.log(`${pad('case', 26)} ${pad('eager', 10)} ${pad('deferred', 10)} ${pad('speedup', 9)}`) - - // Accumulated so V8 cannot treat the spawn loop as dead code. - let consumed = 0 - - for (const [label, argv, env] of cases) { - for (let index = 0; index < WARMUP; index += 1) { - consumed += run(eagerEntry, argv, env).stdout.length - consumed += run(deferredEntry, argv, env).stdout.length - } - const samples = { eager: [], deferred: [] } - for (let round = 0; round < ROUNDS; round += 1) { - // Alternate which arm leads so a drifting machine load cannot be - // attributed to one arm. - const order = - round % 2 === 0 - ? [ - ['eager', eagerEntry], - ['deferred', deferredEntry] - ] - : [ - ['deferred', deferredEntry], - ['eager', eagerEntry] - ] - for (const [arm, entry] of order) { - const started = performance.now() - const result = run(entry, argv, env) - samples[arm].push(performance.now() - started) - consumed += result.stdout.length - } - } - const eagerMs = median(samples.eager) - const deferredMs = median(samples.deferred) - console.log( - `${pad(label, 26)} ${pad(`${eagerMs.toFixed(1)} ms`, 10)} ${pad(`${deferredMs.toFixed(1)} ms`, 10)} ${pad(`${(eagerMs / deferredMs).toFixed(2)}x`, 9)}` - ) - } - - if (consumed === 0) { - throw new Error('no output consumed — the timing loop was optimised away') - } - console.log( - '\nThe help and error rows are the ones the change targets: they return\n' + - 'before any client construction, so they drop the whole graph. `status` and\n' + - '`worktree list` still construct a client, so they only save the eager parse\n' + - 'of the parts the local path never uses (ws/tweetnacl via websocket-transport).' - ) -} finally { - rmSync(userDataPath, { recursive: true, force: true }) - for (const label of ['eager', 'deferred']) { - rmSync(join(REPO, `.bench-out-${label}`), { recursive: true, force: true }) - } -} diff --git a/config/scripts/performance/transport/cli-runtime-client-deferral-equivalence.mjs b/config/scripts/performance/transport/cli-runtime-client-deferral-equivalence.mjs deleted file mode 100644 index a3d06d5f9d6..00000000000 --- a/config/scripts/performance/transport/cli-runtime-client-deferral-equivalence.mjs +++ /dev/null @@ -1,446 +0,0 @@ -#!/usr/bin/env node -// Compare stdout/stderr/exit byte-for-byte across two real CLI emits: current tree and selected files restored from baseline (default HEAD~). -// Usage: node config/scripts/cli-runtime-client-deferral-equivalence.mjs [--baseline ] -import { execFileSync, spawnSync } from 'node:child_process' -import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync, readFileSync } from 'node:fs' -import { join, resolve } from 'node:path' -import { fileURLToPath } from 'node:url' - -const REPO = fileURLToPath(new URL('../../../..', import.meta.url)) - -// Restore only these baseline files; remove baseline-absent files (e.g. cli-error.ts), then restore the working tree. -const TOUCHED = [ - 'src/cli/args.ts', - 'src/cli/cli-error.ts', - 'src/cli/dispatch.ts', - 'src/cli/flags.ts', - 'src/cli/format.ts', - 'src/cli/index.ts', - 'src/cli/runtime/client.ts', - 'src/cli/selectors.ts' -] - -// Fail if real deferral call shapes change or baseline/current could become identical and pass vacuously. -function assertMarkersFresh() { - const index = readFileSync(join(REPO, 'src/cli/index.ts'), 'utf8') - const client = readFileSync(join(REPO, 'src/cli/runtime/client.ts'), 'utf8') - const checks = [ - ['src/cli/index.ts', index, 'await loadRuntimeClientClass()'], - ['src/cli/index.ts', index, "await import('./runtime-client.js')"], - ['src/cli/index.ts', index, "import type { RuntimeClient } from './runtime-client'"], - ['src/cli/runtime/client.ts', client, 'await loadSendWebSocketRequest()'], - ['src/cli/runtime/client.ts', client, "await import('./websocket-transport.js')"] - ] - for (const [file, source, marker] of checks) { - // Match calls so prose mentions cannot satisfy the guard. - if (!source.includes(marker)) { - throw new Error( - `${file} no longer contains \`${marker}\` — cli-runtime-client-deferral-equivalence.mjs is stale` - ) - } - } - const repointed = ['src/cli/args.ts', 'src/cli/flags.ts', 'src/cli/dispatch.ts'] - for (const file of repointed) { - const source = readFileSync(join(REPO, file), 'utf8') - if (!source.includes("import { RuntimeClientError } from './runtime/types'")) { - throw new Error(`${file} no longer repoints RuntimeClientError at ./runtime/types — stale`) - } - } -} - -function buildTree(label, baselineRev) { - // Build inside repo so emitted modules resolve its node_modules. - const outDir = join(REPO, `.equiv-out-${label}`) - rmSync(outDir, { recursive: true, force: true }) - const restored = [] - try { - if (baselineRev) { - for (const file of TOUCHED) { - const path = join(REPO, file) - restored.push([path, existsSync(path) ? readFileSync(path) : null]) - const old = spawnSync('git', ['show', `${baselineRev}:${file}`], { - cwd: REPO, - maxBuffer: 64 * 1024 * 1024 - }) - if (old.status === 0) { - writeFileSync(path, old.stdout) - } else { - rmSync(path, { force: true }) - } - } - } - execFileSync( - 'npx', - [ - 'tsc', - '-p', - 'config/tsconfig.cli.json', - '--outDir', - outDir, - '--composite', - 'false', - '--incremental', - 'false' - ], - { cwd: REPO, stdio: 'inherit' } - ) - } finally { - for (const [path, contents] of restored) { - if (contents === null) { - rmSync(path, { force: true }) - } else { - writeFileSync(path, contents) - } - } - } - return join(outDir, 'cli/index.js') -} - -// Every case must exit itself; bound spawnSync so reaching a blocking command fails instead of stalling forever. -const RUN_TIMEOUT_MS = 30_000 - -function run(entry, argv, env) { - const result = spawnSync(process.execPath, [entry, ...argv], { - cwd: REPO, - env: { ...process.env, ...env }, - encoding: 'buffer', - timeout: RUN_TIMEOUT_MS, - killSignal: 'SIGKILL' - }) - if (result.error) { - if (result.error.code === 'ETIMEDOUT') { - throw new Error( - `orca ${argv.join(' ')} did not exit within ${RUN_TIMEOUT_MS} ms — it reached a blocking command` - ) - } - throw result.error - } - return { - status: result.status, - stdout: result.stdout.toString('utf8'), - stderr: result.stderr.toString('utf8') - } -} - -// Require identical bytes; empty user-data dirs make runtime-dependent cases deterministically report not running. -function buildCases(isolatedUserData) { - const isolated = { ORCA_USER_DATA_PATH: isolatedUserData } - const cases = [ - // Paths that must never load the runtime client at all. - [[], {}], - [['--help'], {}], - [['help'], {}], - [['help', 'worktree'], {}], - [['help', 'browser'], {}], - [['worktree', '--help'], {}], - [['help', 'no-such-command'], {}], - [['no-such-command'], {}], - [['no-such-command'], { ORCA_PAIRING_CODE: 'garbage' }], - [['wrktree', 'list'], {}], - [['agent-context'], {}], - [['agent-context', '--json'], {}], - // Flag validation must still fire before any runtime lookup. - [['worktree', 'list', '--nonexistent-flag'], {}], - [['worktree', 'list', '--nonexistent-flag', '--json'], {}], - [['browser', 'snapshot', '--nonexistent-flag'], {}], - // resolveRemotePairing throws from the RuntimeClient CONSTRUCTOR. - [['status', '--pairing-code', 'x', '--environment', 'y'], isolated], - [['status', '--pairing-code', 'x', '--environment', 'y', '--json'], isolated], - [['status', '--pairing-code', 'not-a-pairing-code'], isolated], - [['status', '--pairing-code', 'not-a-pairing-code', '--json'], isolated], - [['status', '--pairing-code', 'orca://pair?code=zzzz'], isolated], - [['status', '--environment', 'no-such-environment'], isolated], - [['status', '--environment', 'no-such-environment', '--json'], isolated], - [['worktree', 'list', '--environment', 'no-such-environment', '--json'], isolated], - // The env-var fallback must stay live for non-suppressed commands... - [['status', '--json'], { ...isolated, ORCA_PAIRING_CODE: 'not-a-pairing-code' }], - [['status', '--json'], { ...isolated, ORCA_REMOTE_PAIRING: 'not-a-pairing-code' }], - [['status', '--json'], { ...isolated, ORCA_ENVIRONMENT: 'no-such-environment' }], - // Keep suppression for local-only groups. Do not invoke agent hooks on/off: they modify real ~/.claude configuration outside ORCA_USER_DATA_PATH. - [['environment', 'list', '--json'], { ...isolated, ORCA_ENVIRONMENT: 'no-such-environment' }], - [['environment', 'list', '--json'], { ...isolated, ORCA_PAIRING_CODE: 'not-a-pairing-code' }], - [['agent-context', '--json'], { ...isolated, ORCA_PAIRING_CODE: 'not-a-pairing-code' }], - // Runtime-unavailable reporting (RuntimeClientError formatting). - [['status'], isolated], - [['status', '--json'], isolated], - [['worktree', 'list', '--json'], isolated], - [['terminal', 'list', '--json'], isolated] - ] - // Seed fuzzing for reproducibility; all pool tokens must be safe to execute, checked against UNSAFE_TOKENS before running any case. - const tokens = [ - 'worktree', - 'list', - 'status', - 'browser', - 'snapshot', - 'terminal', - 'environment', - 'agent', - 'agent-context', - 'vm', - '--json', - '--help', - '--pairing-code', - '--environment', - '--worktree', - 'orca://pair?code=!!!', - '', - '-', - '--', - '--=', - 'a'.repeat(300), - 'näme-ünicode', - '💥', - '../..', - 'x\ty' - ] - let seed = 0x9e3779b9 - const next = () => { - seed ^= seed << 13 - seed ^= seed >>> 17 - seed ^= seed << 5 - return (seed >>> 0) / 0x100000000 - } - // Check entire pool, not just sampled cases: serve once survived review here and escaped the per-case scan by chance. - assertTokensSafe(tokens, 'fuzz token pool') - assertFuzzPoolDeclaredReadOnly(tokens) - for (let index = 0; index < 400; index += 1) { - const length = 1 + Math.floor(next() * 4) - const argv = [] - for (let part = 0; part < length; part += 1) { - argv.push(tokens[Math.floor(next() * tokens.length)]) - } - cases.push([argv, isolated]) - } - for (const [argv] of cases) { - assertTokensSafe(argv, `argv ${JSON.stringify(argv)}`) - } - return cases -} - -// Cases run real CLI with developer HOME/PATH: deny foreground commands, surviving children, config/registry writes and real UI input. -// Deny mixed read/write groups (capture/intercept/label/relation) wholesale; fuzzing cannot distinguish their subcommands. -const FOREGROUND_TOKENS = ['serve', 'open', 'claude-teams', 'exec', 'eval', 'launch', 'attach'] -const MUTATING_TOKENS = [ - // persistent config and registry state - 'on', - 'off', - 'hooks', - 'create', - 'remove', - 'rm', - 'delete', - 'add', - 'edit', - 'set', - 'set-value', - 'set-base-ref', - 'setup-clone', - 'setup-create', - 'setup-update', - 'setup-delete', - 'setup-existing-folder', - 'install', - 'uninstall', - 'reinstall', - 'update', - 'clone', - 'apply', - 'write', - 'reset', - 'clear', - 'enable', - 'disable', - 'use-default', - 'permissions', - // process and pane lifecycle - 'run', - 'run-stop', - 'start', - 'stop', - 'kill', - 'shutdown', - 'close', - 'split', - 'switch', - 'rename', - 'focus', - // orchestration writes - 'send', - 'reply', - 'dispatch', - 'task-create', - 'task-update', - 'gate-create', - 'gate-resolve', - // issue-tracker writes - 'save-issue', - 'comment', - 'label', - 'relation', - 'assignee', - 'priority', - 'estimate', - 'due-date', - // browser / computer / emulator input and navigation - 'goto', - 'back', - 'forward', - 'reload', - 'click', - 'dblclick', - 'hover', - 'fill', - 'type', - 'type-text', - 'select', - 'select-all', - 'uncheck', - 'keypress', - 'press-key', - 'inserttext', - 'hotkey', - 'paste-text', - 'perform-secondary-action', - 'drag', - 'scroll', - 'scrollintoview', - 'wheel', - 'move', - 'up', - 'down', - 'tap', - 'gesture', - 'button', - 'rotate', - 'upload', - 'download', - 'dismiss', - 'accept', - 'highlight', - 'viewport', - 'geolocation', - 'headers', - 'credentials', - 'offline', - 'media', - 'device', - 'capture', - 'intercept' -] - -const UNSAFE_TOKENS = new Map([ - ...FOREGROUND_TOKENS.map((token) => [token, 'runs in the foreground or spawns a process']), - ...MUTATING_TOKENS.map((token) => [token, 'can write outside ORCA_USER_DATA_PATH']) -]) - -// Deny lists miss new verbs (serve once escaped); require explicit read-only allowlisting for every pool token too. -const READ_ONLY_FUZZ_TOKENS = new Set([ - // command tokens: every path they can form is a list/show or a parse error - 'agent', - 'agent-context', - 'browser', - 'environment', - 'list', - 'snapshot', - 'status', - 'terminal', - 'vm', - 'worktree', - // global flags and hostile strings, which reach no handler at all - '--json', - '--help', - '--pairing-code', - '--environment', - '--worktree', - 'orca://pair?code=!!!', - '', - '-', - '--', - '--=', - 'a'.repeat(300), - 'näme-ünicode', - '💥', - '../..', - 'x\ty' -]) - -function assertTokensSafe(tokens, context) { - for (const token of tokens) { - const reason = UNSAFE_TOKENS.get(token) - if (reason) { - throw new Error(`Refusing to run ${context}: "${token}" ${reason}`) - } - } -} - -// Reject neither/both-list membership before any case runs; sampling cannot prove pool safety. -function assertFuzzPoolDeclaredReadOnly(tokens) { - for (const token of tokens) { - if (!READ_ONLY_FUZZ_TOKENS.has(token)) { - throw new Error( - `Fuzz token ${JSON.stringify(token)} is not declared in READ_ONLY_FUZZ_TOKENS — declare it read-only or drop it` - ) - } - } - for (const token of READ_ONLY_FUZZ_TOKENS) { - if (UNSAFE_TOKENS.has(token)) { - throw new Error( - `Token ${JSON.stringify(token)} is declared both read-only and unsafe — the two lists disagree` - ) - } - } -} - -const baselineIndex = process.argv.indexOf('--baseline') -const baselineRev = baselineIndex === -1 ? 'HEAD' : process.argv[baselineIndex + 1] - -assertMarkersFresh() - -const isolatedUserData = mkdtempSync(join(REPO, '.equiv-userdata-')) -mkdirSync(join(isolatedUserData, 'empty'), { recursive: true }) - -let oldEntry -let newEntry -try { - // Build cases and check safety before expensive tsc compiles so unsafe tokens fail immediately. - const cases = buildCases(isolatedUserData) - - console.log(`Building baseline (${baselineRev}) …`) - oldEntry = buildTree('old', baselineRev) - console.log('Building working tree …') - newEntry = buildTree('new', null) - - console.log(`Comparing ${cases.length} invocations byte for byte …`) - let mismatches = 0 - for (const [argv, env] of cases) { - const before = run(oldEntry, argv, env) - const after = run(newEntry, argv, env) - if ( - before.status !== after.status || - before.stdout !== after.stdout || - before.stderr !== after.stderr - ) { - mismatches += 1 - console.error(`\nMISMATCH argv=${JSON.stringify(argv)} env=${JSON.stringify(env)}`) - console.error(` exit before=${before.status} after=${after.status}`) - if (before.stdout !== after.stdout) { - console.error(` stdout before=${JSON.stringify(before.stdout.slice(0, 400))}`) - console.error(` after =${JSON.stringify(after.stdout.slice(0, 400))}`) - } - if (before.stderr !== after.stderr) { - console.error(` stderr before=${JSON.stringify(before.stderr.slice(0, 400))}`) - console.error(` after =${JSON.stringify(after.stderr.slice(0, 400))}`) - } - } - } - if (mismatches > 0) { - throw new Error(`${mismatches} of ${cases.length} invocations differ`) - } - console.log(`\nAll ${cases.length} invocations byte-identical (stdout, stderr, exit code).`) -} finally { - rmSync(isolatedUserData, { recursive: true, force: true }) - for (const label of ['old', 'new']) { - rmSync(resolve(REPO, `.equiv-out-${label}`), { recursive: true, force: true }) - } -} diff --git a/src/cli/account-add-process.test.ts b/src/cli/accounts/account-add-process.test.ts similarity index 99% rename from src/cli/account-add-process.test.ts rename to src/cli/accounts/account-add-process.test.ts index e790e076eb9..acb3159aa4b 100644 --- a/src/cli/account-add-process.test.ts +++ b/src/cli/accounts/account-add-process.test.ts @@ -9,7 +9,7 @@ import { delimiter, dirname, join, resolve } from 'node:path' import { runProcess, spawnProcess } from '@orca/process-host' import { expect, it } from 'vitest' import { z } from 'zod' -import { DATA_ACCOUNT_RUNTIME_CAPABILITY } from '../shared/account-runtime-capabilities' +import { DATA_ACCOUNT_RUNTIME_CAPABILITY } from '../../shared/account-runtime-capabilities' const eventSchema = z.object({ name: z.string(), diff --git a/src/cli/handlers/account-list-format.ts b/src/cli/accounts/account-list-format.ts similarity index 100% rename from src/cli/handlers/account-list-format.ts rename to src/cli/accounts/account-list-format.ts diff --git a/src/cli/handlers/account-selection.ts b/src/cli/accounts/account-selection.ts similarity index 98% rename from src/cli/handlers/account-selection.ts rename to src/cli/accounts/account-selection.ts index bce8995f3b0..4fd07123fd8 100644 --- a/src/cli/handlers/account-selection.ts +++ b/src/cli/accounts/account-selection.ts @@ -1,6 +1,6 @@ import type { HandlerContext } from '../dispatch' -import { printResult } from '../format' -import { RuntimeClientError } from '../runtime-client' +import { printResult } from '../command-result-output' +import { RuntimeClientError } from '../runtime/types' import { ANTIGRAVITY_ACCOUNTS_RUNTIME_CAPABILITY } from '../../shared/account-runtime-capabilities' import type { AntigravityAccountState, @@ -12,7 +12,7 @@ import type { ManagedDataAccountProvider, ManagedDataAccountsState } from '../../shared/managed-account-types' -import type { RuntimeStatus } from '../../shared/runtime-types' +import type { RuntimeStatus } from '../../shared/runtime-session-contracts' import { getWslAccountTarget } from './account-wsl-location' import { formatAccountsBlock, diff --git a/src/cli/handlers/account-wsl-location.ts b/src/cli/accounts/account-wsl-location.ts similarity index 100% rename from src/cli/handlers/account-wsl-location.ts rename to src/cli/accounts/account-wsl-location.ts diff --git a/src/cli/handlers/account.test.ts b/src/cli/accounts/account.test.ts similarity index 99% rename from src/cli/handlers/account.test.ts rename to src/cli/accounts/account.test.ts index 99d39d92022..76891f3fc98 100644 --- a/src/cli/handlers/account.test.ts +++ b/src/cli/accounts/account.test.ts @@ -64,7 +64,7 @@ vi.mock('../../shared/windows-console-input', () => ({ import { ACCOUNT_HANDLERS } from './account' import { REPEATED_FLAG_SEPARATOR } from '../args' import type { HandlerContext } from '../dispatch' -import type { RuntimeClient } from '../runtime-client' +import type { RuntimeClient } from '../runtime/client' import { ACCOUNT_IMPORT_RUNTIME_CAPABILITY, ANTIGRAVITY_ACCOUNTS_RUNTIME_CAPABILITY, diff --git a/src/cli/handlers/account.ts b/src/cli/accounts/account.ts similarity index 98% rename from src/cli/handlers/account.ts rename to src/cli/accounts/account.ts index 3f2fc1ecb8d..d8358e377b9 100644 --- a/src/cli/handlers/account.ts +++ b/src/cli/accounts/account.ts @@ -3,8 +3,8 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { delimiter, join } from 'node:path' import type { CommandHandler, HandlerContext } from '../dispatch' -import { printResult } from '../format' -import { RuntimeClientError } from '../runtime-client' +import { printResult } from '../command-result-output' +import { RuntimeClientError } from '../runtime/types' import { stripElectronRunAsNode } from '../runtime/orca-app-executable' import { rejectRemoteSelectionFlags } from '../remote-selection-flag-rejection' import { buildWslExecArgs, buildWslLoginShellCommand } from '../../shared/wsl-login-shell-command' @@ -20,7 +20,7 @@ import { ACCOUNT_IMPORT_RUNTIME_CAPABILITY, CLAUDE_SIGN_IN_RUNTIME_CAPABILITY } from '../../shared/account-runtime-capabilities' -import type { RuntimeStatus } from '../../shared/runtime-types' +import type { RuntimeStatus } from '../../shared/runtime-session-contracts' import type { ClaudeAccountSignIn, ClaudeRateLimitAccountsState, diff --git a/src/cli/handlers/data-account-commands.test.ts b/src/cli/accounts/data-account-commands.test.ts similarity index 96% rename from src/cli/handlers/data-account-commands.test.ts rename to src/cli/accounts/data-account-commands.test.ts index b0d881fe4e6..f7368f79416 100644 --- a/src/cli/handlers/data-account-commands.test.ts +++ b/src/cli/accounts/data-account-commands.test.ts @@ -2,9 +2,10 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { existsSync } from 'node:fs' import { dirname, join } from 'node:path' import { tmpdir } from 'node:os' -import { parseArgs, specPaths } from '../args' +import { parseArgs } from '../args' +import { specPaths } from '../command-spec' import { ACCOUNT_COMMAND_SPECS } from '../specs/account' -import { RuntimeClient } from '../runtime-client' +import { RuntimeClient } from '../runtime/client' import { DATA_ACCOUNT_RUNTIME_CAPABILITY } from '../../shared/account-runtime-capabilities' import { addDataAccount } from './data-account-commands' diff --git a/src/cli/handlers/data-account-commands.ts b/src/cli/accounts/data-account-commands.ts similarity index 97% rename from src/cli/handlers/data-account-commands.ts rename to src/cli/accounts/data-account-commands.ts index 40d7e96479d..309a77d8783 100644 --- a/src/cli/handlers/data-account-commands.ts +++ b/src/cli/accounts/data-account-commands.ts @@ -3,10 +3,10 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import type { HandlerContext } from '../dispatch' import { REPEATED_FLAG_SEPARATOR } from '../args' -import { printResult } from '../format' -import { RuntimeClientError } from '../runtime-client' +import { printResult } from '../command-result-output' +import { RuntimeClientError } from '../runtime/types' import { DATA_ACCOUNT_RUNTIME_CAPABILITY } from '../../shared/account-runtime-capabilities' -import type { RuntimeStatus } from '../../shared/runtime-types' +import type { RuntimeStatus } from '../../shared/runtime-session-contracts' import type { ManagedDataAccountProvider, ManagedDataAccountsState diff --git a/src/cli/accounts/interactive-login-interruption.test.ts b/src/cli/accounts/interactive-login-interruption.test.ts new file mode 100644 index 00000000000..9c2e2ca2b10 --- /dev/null +++ b/src/cli/accounts/interactive-login-interruption.test.ts @@ -0,0 +1,64 @@ +import { EventEmitter } from 'node:events' +import type { ChildProcess } from 'node:child_process' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { terminateInteractiveLoginProcess } from './interactive-login-interruption' + +function loginChild(pid = 4321): ChildProcess & EventEmitter { + return Object.assign(new EventEmitter(), { + kill: vi.fn(), + pid + }) as unknown as ChildProcess & EventEmitter +} + +afterEach(() => { + vi.useRealTimers() +}) + +describe('terminateInteractiveLoginProcess', () => { + it('waits for both Windows tree termination and physical wrapper close', async () => { + const child = loginChild() + let finishTreeKill: (() => void) | undefined + const killWindowsTree = vi.fn( + () => + new Promise((resolve) => { + finishTreeKill = resolve + }) + ) + let terminated = false + + const pending = terminateInteractiveLoginProcess(child, 'SIGTERM', { + platform: 'win32', + killWindowsTree + }).then(() => { + terminated = true + }) + + expect(killWindowsTree).toHaveBeenCalledWith(4321) + child.emit('close', 1) + await Promise.resolve() + expect(terminated).toBe(false) + + finishTreeKill?.() + await pending + expect(child.kill).not.toHaveBeenCalled() + }) + + it('forwards the interrupt signal to a direct POSIX child and awaits close', async () => { + const child = loginChild() + let terminated = false + + const pending = terminateInteractiveLoginProcess(child, 'SIGHUP', { + platform: 'linux' + }).then(() => { + terminated = true + }) + + expect(child.kill).toHaveBeenCalledWith('SIGHUP') + await Promise.resolve() + expect(terminated).toBe(false) + + child.emit('close', 1) + await pending + expect(child.kill).toHaveBeenCalledOnce() + }) +}) diff --git a/src/cli/handlers/interactive-login-interruption.ts b/src/cli/accounts/interactive-login-interruption.ts similarity index 100% rename from src/cli/handlers/interactive-login-interruption.ts rename to src/cli/accounts/interactive-login-interruption.ts diff --git a/src/cli/handlers/opencode-account-login-command.test.ts b/src/cli/accounts/opencode-account-login-command.test.ts similarity index 100% rename from src/cli/handlers/opencode-account-login-command.test.ts rename to src/cli/accounts/opencode-account-login-command.test.ts diff --git a/src/cli/handlers/opencode-account-login-command.ts b/src/cli/accounts/opencode-account-login-command.ts similarity index 99% rename from src/cli/handlers/opencode-account-login-command.ts rename to src/cli/accounts/opencode-account-login-command.ts index 52eeac1cdd2..f3a6bbc4c49 100644 --- a/src/cli/handlers/opencode-account-login-command.ts +++ b/src/cli/accounts/opencode-account-login-command.ts @@ -7,7 +7,7 @@ import { import { inFlightWindowsTreeKill } from '@orca/process-host/windows-tree-kill' import { createOutputSink } from '@orca/process-host/bounded-output-sink' import { resolveCliCommand, withCliRuntimeOnPath } from '../../shared/node-cli-command-resolution' -import { RuntimeClientError } from '../runtime-client' +import { RuntimeClientError } from '../runtime/types' import { type InteractiveLoginSession, LOGIN_PROCESS_POSIX_GRACE_MS, diff --git a/src/cli/handlers/agent-hooks.test.ts b/src/cli/agents/agent-hooks.test.ts similarity index 96% rename from src/cli/handlers/agent-hooks.test.ts rename to src/cli/agents/agent-hooks.test.ts index 1b0f1481104..1d577678da6 100644 --- a/src/cli/handlers/agent-hooks.test.ts +++ b/src/cli/agents/agent-hooks.test.ts @@ -1,3 +1,4 @@ +import type * as RuntimeMetadata from '../runtime/metadata' import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import type * as fs from 'node:fs' import { tmpdir } from 'node:os' @@ -46,7 +47,7 @@ const { getManagedAgentHookStatusesMock: vi.fn() })) -vi.mock('../runtime-client', () => { +vi.mock('../runtime/client', () => { class RuntimeClient { call = callMock async getOfflineRuntimeAdmission() { @@ -59,22 +60,14 @@ vi.mock('../runtime-client', () => { } } - class RuntimeClientError extends Error { - readonly code: string - - constructor(code: string, message: string) { - super(message) - this.code = code - } - } - - return { - RuntimeClient, - RuntimeClientError, - getDefaultUserDataPath: getDefaultUserDataPathMock - } + return { RuntimeClient } }) +vi.mock('../runtime/metadata', async (importOriginal) => ({ + ...(await importOriginal()), + getDefaultUserDataPath: getDefaultUserDataPathMock +})) + vi.mock('../../main/agent-hooks/installation/managed-agent-hook-controls', () => ({ applyAgentStatusHooksEnabled: applyAgentStatusHooksEnabledMock, getManagedAgentHookStatuses: getManagedAgentHookStatusesMock diff --git a/src/cli/handlers/agent-hooks.ts b/src/cli/agents/agent-hooks.ts similarity index 96% rename from src/cli/handlers/agent-hooks.ts rename to src/cli/agents/agent-hooks.ts index 44134094920..8c36a35c5c4 100644 --- a/src/cli/handlers/agent-hooks.ts +++ b/src/cli/agents/agent-hooks.ts @@ -1,13 +1,11 @@ import { join } from 'node:path' import type { CommandHandler } from '../dispatch' -import { printResult } from '../format' +import { printResult } from '../command-result-output' import { rejectRemoteSelectionFlags } from '../remote-selection-flag-rejection' -import { - RuntimeClientError, - type RuntimeClient, - type RuntimeRpcSuccess, - getDefaultUserDataPath -} from '../runtime-client' +import { RuntimeClientError } from '../runtime/types' +import type { RuntimeClient } from '../runtime/client' +import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope' +import { getDefaultUserDataPath } from '../runtime/metadata' import type { AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' import { DEFAULT_LOCAL_ORCA_PROFILE_ID } from '../../shared/orca-profiles' import type { GlobalSettings } from '../../shared/global-settings-types' diff --git a/src/cli/agent-launch-process.test.ts b/src/cli/agents/agent-launch-process.test.ts similarity index 98% rename from src/cli/agent-launch-process.test.ts rename to src/cli/agents/agent-launch-process.test.ts index 3ee338d04af..b2f7d24a35f 100644 --- a/src/cli/agent-launch-process.test.ts +++ b/src/cli/agents/agent-launch-process.test.ts @@ -10,7 +10,7 @@ import { z } from 'zod' import { AGENT_LAUNCH_RUNTIME_CAPABILITIES, AGENT_LAUNCH_SURFACE_RUNTIME_CAPABILITY -} from '../shared/agent-launch/contracts/agent-launch-runtime-capability' +} from '../../shared/agent-launch/contracts/agent-launch-runtime-capability' import { agentLaunchFixture } from './agent-launch-test-fixtures' it('real CLI processes carry surface choices and refuse invalid or unsupported picks before mutation', async () => { diff --git a/src/cli/agent-launch-recovery.ts b/src/cli/agents/agent-launch-recovery.ts similarity index 93% rename from src/cli/agent-launch-recovery.ts rename to src/cli/agents/agent-launch-recovery.ts index 2311b86f86e..22537ab0bfb 100644 --- a/src/cli/agent-launch-recovery.ts +++ b/src/cli/agents/agent-launch-recovery.ts @@ -1,9 +1,9 @@ -import { RuntimeClientError, RuntimeRpcFailureError } from './runtime-client' -import { classifyAgentLaunchReplayRefusal } from '../shared/agent-launch/contracts/agent-launch-replay-refusal' +import { RuntimeClientError, RuntimeRpcFailureError } from '../runtime/types' +import { classifyAgentLaunchReplayRefusal } from '../../shared/agent-launch/contracts/agent-launch-replay-refusal' import { recoverableOrchestrationArgs, resolveOrchestrationCliExecutable -} from './runtime/orchestration-recovery-command' +} from '../runtime/orchestration-recovery-command' /** A lost reply never authorizes a new launch, even on hosts without a replay ledger. */ export async function withCliAgentLaunchRecovery( diff --git a/src/cli/agent-launch-request.ts b/src/cli/agents/agent-launch-request.ts similarity index 86% rename from src/cli/agent-launch-request.ts rename to src/cli/agents/agent-launch-request.ts index df2508164af..43126b478a4 100644 --- a/src/cli/agent-launch-request.ts +++ b/src/cli/agents/agent-launch-request.ts @@ -4,31 +4,33 @@ import { randomUUID } from 'node:crypto' import type { AgentLaunchPrompt, AgentLaunchResult -} from '../shared/agent-launch/contracts/agent-launch-intent' +} from '../../shared/agent-launch/contracts/agent-launch-intent' import { AGENT_LAUNCH_SURFACES, type AgentLaunchSurface -} from '../shared/agent-launch/contracts/agent-launch-surface' -import { checkAgentLaunchModelPreferences } from '../shared/agent-launch/choices/agent-launch-model-preferences' +} from '../../shared/agent-launch/contracts/agent-launch-surface' +import { checkAgentLaunchModelPreferences } from '../../shared/agent-launch/choices/agent-launch-model-preferences' import { AGENT_LAUNCH_RUNTIME_CAPABILITY, AGENT_LAUNCH_PROMPT_CARRY_RUNTIME_CAPABILITY, AGENT_LAUNCH_LOCAL_PRESENTATION_RUNTIME_CAPABILITY, AGENT_LAUNCH_REPLAY_REQUIRED_RUNTIME_CAPABILITY, AGENT_LAUNCH_SURFACE_RUNTIME_CAPABILITY -} from '../shared/agent-launch/contracts/agent-launch-runtime-capability' -import { createStructuredAgentSessionOperationId } from '../shared/agent-session/lifecycle/structured-agent-session-mutation' -import { parseAgentSessionOperationTimestamp } from '../shared/agent-session/agent-session-host-authority' -import type { RuntimeStatus } from '../shared/runtime-types' -import type { TuiAgent } from '../shared/agent-launch/catalog/tui-agent' -import { isTuiAgent } from '../shared/agent-launch/catalog/tui-agent-config' +} from '../../shared/agent-launch/contracts/agent-launch-runtime-capability' +import { createStructuredAgentSessionOperationId } from '../../shared/agent-session/lifecycle/structured-agent-session-mutation' +import { parseAgentSessionOperationTimestamp } from '../../shared/agent-session/agent-session-host-authority' +import type { RuntimeStatus } from '../../shared/runtime-session-contracts' +import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent' +import { isTuiAgent } from '../../shared/agent-launch/catalog/tui-agent-config' import { getOptionalStringFlag, getRequiredStringFlag, getRequiredStringFlagAllowingEmpty, rejectValuelessFlag -} from './flags' -import { RuntimeClientError, type RuntimeClient, type RuntimeRpcSuccess } from './runtime-client' +} from '../flags' +import { RuntimeClientError } from '../runtime/types' +import type { RuntimeClient } from '../runtime/client' +import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope' import { withCliAgentLaunchRecovery } from './agent-launch-recovery' type Flags = Map diff --git a/src/cli/agent-launch-test-fixtures.ts b/src/cli/agents/agent-launch-test-fixtures.ts similarity index 80% rename from src/cli/agent-launch-test-fixtures.ts rename to src/cli/agents/agent-launch-test-fixtures.ts index f8ead416d7a..d4ab7ebca3b 100644 --- a/src/cli/agent-launch-test-fixtures.ts +++ b/src/cli/agents/agent-launch-test-fixtures.ts @@ -1,5 +1,5 @@ -import { AGENT_LAUNCH_RUNTIME_CAPABILITIES } from '../shared/agent-launch/contracts/agent-launch-runtime-capability' -import { okFixture } from './test-fixtures' +import { AGENT_LAUNCH_RUNTIME_CAPABILITIES } from '../../shared/agent-launch/contracts/agent-launch-runtime-capability' +import { okFixture } from '../test-fixtures' export function agentLaunchHostFixture() { return okFixture('req_status', { capabilities: [...AGENT_LAUNCH_RUNTIME_CAPABILITIES] }) diff --git a/src/cli/handlers/agent-launch.ts b/src/cli/agents/agent-launch.ts similarity index 93% rename from src/cli/handlers/agent-launch.ts rename to src/cli/agents/agent-launch.ts index df4f2536ba5..0e661f3d894 100644 --- a/src/cli/handlers/agent-launch.ts +++ b/src/cli/agents/agent-launch.ts @@ -5,10 +5,10 @@ import { getAgentLaunchCapabilities, parseCliAgent, readCliAgentLaunch -} from '../agent-launch-request' +} from './agent-launch-request' import { getRequiredStringFlag } from '../flags' -import { printResult } from '../format' -import { RuntimeClientError } from '../runtime-client' +import { printResult } from '../command-result-output' +import { RuntimeClientError } from '../runtime/types' import { getRequiredWorktreeSelector, resolveCurrentWorktreeSelector } from '../selectors' export const AGENT_LAUNCH_HANDLERS: Record = { diff --git a/src/cli/handlers/chat.test.ts b/src/cli/agents/chat.test.ts similarity index 97% rename from src/cli/handlers/chat.test.ts rename to src/cli/agents/chat.test.ts index 50005f098b6..3bd0a5a8e12 100644 --- a/src/cli/handlers/chat.test.ts +++ b/src/cli/agents/chat.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import { RuntimeClient } from '../runtime-client' +import { RuntimeClient } from '../runtime/client' import { CHAT_HANDLERS } from './chat' function chatClient(isRemote: boolean): { client: RuntimeClient; call: ReturnType } { diff --git a/src/cli/handlers/chat.ts b/src/cli/agents/chat.ts similarity index 95% rename from src/cli/handlers/chat.ts rename to src/cli/agents/chat.ts index f9303026a8d..3d9b6671bbd 100644 --- a/src/cli/handlers/chat.ts +++ b/src/cli/agents/chat.ts @@ -1,7 +1,7 @@ import type { CommandHandler } from '../dispatch' import { getPresentStringFlag, getRequiredStringFlag } from '../flags' -import { printResult } from '../format' -import { RuntimeClientError } from '../runtime-client' +import { printResult } from '../command-result-output' +import { RuntimeClientError } from '../runtime/types' import { readInjectedAgentSessionId } from '../../shared/agent-session/lifecycle/agent-session-caller-env' type ChatRenameResult = { name: string | null; applied: boolean } diff --git a/src/cli/artifact-format.ts b/src/cli/artifacts/artifact-format.ts similarity index 88% rename from src/cli/artifact-format.ts rename to src/cli/artifacts/artifact-format.ts index ae60711014c..3eee947aecd 100644 --- a/src/cli/artifact-format.ts +++ b/src/cli/artifacts/artifact-format.ts @@ -1,4 +1,4 @@ -import type { ArtifactListItem, ArtifactListPage } from '../shared/artifacts/artifacts' +import type { ArtifactListItem, ArtifactListPage } from '../../shared/artifacts/artifacts' export function formatArtifactList(artifacts: readonly ArtifactListItem[]): string { if (artifacts.length === 0) { diff --git a/src/cli/handlers/artifacts.ts b/src/cli/artifacts/artifacts.ts similarity index 97% rename from src/cli/handlers/artifacts.ts rename to src/cli/artifacts/artifacts.ts index 173317475fa..28aa1498561 100644 --- a/src/cli/handlers/artifacts.ts +++ b/src/cli/artifacts/artifacts.ts @@ -19,9 +19,9 @@ import { } from '../../shared/artifacts/artifact-sharing-gate' import type { CommandHandler, HandlerContext } from '../dispatch' import { rejectRemoteSelectionFlags } from '../remote-selection-flag-rejection' -import { RuntimeClientError } from '../runtime-client' -import { formatArtifactListPage, formatArtifactShared } from '../artifact-format' -import { printResult } from '../format' +import { RuntimeClientError } from '../runtime/types' +import { formatArtifactListPage, formatArtifactShared } from './artifact-format' +import { printResult } from '../command-result-output' function stringFlag(ctx: HandlerContext, name: string): string | undefined { const value = ctx.flags.get(name) diff --git a/src/cli/automation-destination.ts b/src/cli/automations/automation-destination.ts similarity index 84% rename from src/cli/automation-destination.ts rename to src/cli/automations/automation-destination.ts index ffddcb351ae..1178b63cc45 100644 --- a/src/cli/automation-destination.ts +++ b/src/cli/automations/automation-destination.ts @@ -3,16 +3,16 @@ import { AUTOMATION_OWNER_CONFLICT_CODES, AutomationOwnerConflictError -} from '../shared/automations/ownership/automation-owner-conflict' -import type { AutomationDestination } from '../shared/automations/ownership/automation-owner-precondition' -import type { RuntimeWorktreeRecord } from '../shared/runtime-types' -import type { SshTargetSummary } from '../shared/ssh-types' -import type { Repo } from '../shared/repo-types' -import { getRepoRoutingConnectionId } from '../shared/execution-host' -import { getManagedOrcadSshTargetId } from '../shared/execution-host/managed-orcad-execution-host' -import { listEnvironments } from '../shared/remote-runtime/host-store/runtime-environment-store' -import { RuntimeClient } from './runtime-client' -import { fetchSshTargetSummaries } from './host-selector-alternatives' +} from '../../shared/automations/ownership/automation-owner-conflict' +import type { AutomationDestination } from '../../shared/automations/ownership/automation-owner-precondition' +import type { RuntimeWorktreeRecord } from '../../shared/runtime-worktree-contracts' +import type { SshTargetSummary } from '../../shared/ssh-types' +import type { Repo } from '../../shared/repo-types' +import { getRepoRoutingConnectionId } from '../../shared/execution-host' +import { getManagedOrcadSshTargetId } from '../../shared/execution-host/managed-orcad-execution-host' +import { listEnvironments } from '../../shared/remote-runtime/host-store/runtime-environment-store' +import { RuntimeClient } from '../runtime/client' +import { fetchSshTargetSummaries } from '../host-selector-alternatives' /** Empty selectors mean the execution host cannot change. */ export type AutomationDestinationTarget = { repo?: string; workspace?: string } diff --git a/src/cli/handlers/automation-extra-agent-args-flag.ts b/src/cli/automations/automation-extra-agent-args-flag.ts similarity index 90% rename from src/cli/handlers/automation-extra-agent-args-flag.ts rename to src/cli/automations/automation-extra-agent-args-flag.ts index 11bf80e81fa..c9e2ed15e61 100644 --- a/src/cli/handlers/automation-extra-agent-args-flag.ts +++ b/src/cli/automations/automation-extra-agent-args-flag.ts @@ -1,4 +1,4 @@ -import { RuntimeClientError } from '../runtime-client' +import { RuntimeClientError } from '../runtime/types' /** An explicit empty value clears saved extras. */ export function getExtraAgentArgsFlag(flags: Map): string | undefined { diff --git a/src/cli/automation-format.ts b/src/cli/automations/automation-format.ts similarity index 91% rename from src/cli/automation-format.ts rename to src/cli/automations/automation-format.ts index 844d2b2a0cd..48b410f1ecf 100644 --- a/src/cli/automation-format.ts +++ b/src/cli/automations/automation-format.ts @@ -1,13 +1,13 @@ // Use authority-projected owners: stored target fields survive host removal and re-registration. -import type { Automation } from '../shared/automations/automation-definition' -import type { AutomationRun } from '../shared/automations/history/automation-run' -import type { AutomationListItem } from '../shared/automations/ownership/automation-list-scope' -import type { AutomationOwnerPrecondition } from '../shared/automations/ownership/automation-owner-precondition' -import { getAutomationLegacyRepoId } from '../shared/automations/history/automation-run-identity' -import { formatAutomationPrecheckTimeout } from '../shared/automations/launch/automation-precheck' -import { formatAutomationSchedule } from '../shared/automations/scheduling/automation-schedules' -import { quoteCliCommandArgument } from './shell-command-quote' +import type { Automation } from '../../shared/automations/automation-definition' +import type { AutomationRun } from '../../shared/automations/history/automation-run' +import type { AutomationListItem } from '../../shared/automations/ownership/automation-list-scope' +import type { AutomationOwnerPrecondition } from '../../shared/automations/ownership/automation-owner-precondition' +import { getAutomationLegacyRepoId } from '../../shared/automations/history/automation-run-identity' +import { formatAutomationPrecheckTimeout } from '../../shared/automations/launch/automation-precheck' +import { formatAutomationSchedule } from '../../shared/automations/scheduling/automation-schedules' +import { quoteCliCommandArgument } from '../shell-command-quote' export type AutomationListPayload = { automations: Automation[] diff --git a/src/cli/handlers/automation-handler-flags.ts b/src/cli/automations/automation-handler-flags.ts similarity index 99% rename from src/cli/handlers/automation-handler-flags.ts rename to src/cli/automations/automation-handler-flags.ts index 8bfea52335f..ed329212abe 100644 --- a/src/cli/handlers/automation-handler-flags.ts +++ b/src/cli/automations/automation-handler-flags.ts @@ -19,7 +19,7 @@ import { getOptionalStringFlag, getRequiredStringFlag } from '../flags' -import { RuntimeClientError } from '../runtime-client' +import { RuntimeClientError } from '../runtime/types' const PRESET_TRIGGERS = new Set(['hourly', 'daily', 'weekdays', 'weekly']) const SCHEDULE_MODIFIER_FLAGS = ['day', 'time'] as const diff --git a/src/cli/handlers/automation-host-support.ts b/src/cli/automations/automation-host-support.ts similarity index 88% rename from src/cli/handlers/automation-host-support.ts rename to src/cli/automations/automation-host-support.ts index ff9463d0d27..b863f6ba3e7 100644 --- a/src/cli/handlers/automation-host-support.ts +++ b/src/cli/automations/automation-host-support.ts @@ -6,9 +6,9 @@ import { EXTRA_AGENT_ARGS_HOST_UPDATE_REQUIRED, hasExtraAgentArgs } from '../../shared/agent-launch/startup/automation-extra-agent-args' -import type { RuntimeStatus } from '../../shared/runtime-types' -import type { RuntimeClient } from '../runtime-client' -import { RuntimeClientError } from '../runtime-client' +import type { RuntimeStatus } from '../../shared/runtime-session-contracts' +import type { RuntimeClient } from '../runtime/client' +import { RuntimeClientError } from '../runtime/types' const SETUP_CHOICE_HOST_UPDATE_REQUIRED = "This host's Orca is too old for --setup on automations. Update Orca on that host, or run the command without --setup." diff --git a/src/cli/automation-owner-conflict-recovery.ts b/src/cli/automations/automation-owner-conflict-recovery.ts similarity index 95% rename from src/cli/automation-owner-conflict-recovery.ts rename to src/cli/automations/automation-owner-conflict-recovery.ts index 9007fe2af4e..0e7d82316b4 100644 --- a/src/cli/automation-owner-conflict-recovery.ts +++ b/src/cli/automations/automation-owner-conflict-recovery.ts @@ -3,7 +3,7 @@ import { AUTOMATION_OWNER_CONFLICT_CODES, isAutomationOwnerConflictCode -} from '../shared/automations/ownership/automation-owner-conflict' +} from '../../shared/automations/ownership/automation-owner-conflict' export type AutomationOwnerConflictRecovery = { nextSteps: readonly string[] } diff --git a/src/cli/automation-runs-paging.ts b/src/cli/automations/automation-runs-paging.ts similarity index 89% rename from src/cli/automation-runs-paging.ts rename to src/cli/automations/automation-runs-paging.ts index d1c2f20b3db..387d8307d64 100644 --- a/src/cli/automation-runs-paging.ts +++ b/src/cli/automations/automation-runs-paging.ts @@ -1,6 +1,7 @@ -import type { AutomationRun } from '../shared/automations/history/automation-run' -import type { RuntimeRpcSuccess } from '../shared/runtime-rpc-envelope' -import { RuntimeClientError, type RuntimeClient } from './runtime-client' +import type { AutomationRun } from '../../shared/automations/history/automation-run' +import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope' +import { RuntimeClientError } from '../runtime/types' +import type { RuntimeClient } from '../runtime/client' // Keep typical snapshot pages below the remote reply limit; retry smaller when needed. export const AUTOMATION_RUNS_PAGE_SIZE = 25 diff --git a/src/cli/handlers/automation-setup-flag.ts b/src/cli/automations/automation-setup-flag.ts similarity index 95% rename from src/cli/handlers/automation-setup-flag.ts rename to src/cli/automations/automation-setup-flag.ts index c5bc9c2e532..32a9c0a8563 100644 --- a/src/cli/handlers/automation-setup-flag.ts +++ b/src/cli/automations/automation-setup-flag.ts @@ -1,4 +1,4 @@ -import { RuntimeClientError } from '../runtime-client' +import { RuntimeClientError } from '../runtime/types' import type { AutomationWorkspaceMode } from '../../shared/automations/automation-definition' export function getAutomationSetupFlag( diff --git a/src/cli/handlers/automations.ts b/src/cli/automations/automations.ts similarity index 98% rename from src/cli/handlers/automations.ts rename to src/cli/automations/automations.ts index b96a1d5b737..9291646cd45 100644 --- a/src/cli/handlers/automations.ts +++ b/src/cli/automations/automations.ts @@ -18,22 +18,22 @@ import { formatAutomationRuns, formatAutomationRunsPage, formatAutomationShow, - printResult, type AutomationShowPayload -} from '../format' +} from './automation-format' +import { printResult } from '../command-result-output' import { getOptionalPositiveIntegerFlag, getOptionalStringFlag, getRequiredStringFlag } from '../flags' -import { resolveAutomationDestination, routeAutomationCreate } from '../automation-destination' +import { resolveAutomationDestination, routeAutomationCreate } from './automation-destination' import { AUTOMATION_RUNS_PAGE_SIZE, automationRunsRpc, readAllAutomationRuns, readAutomationRunsPage -} from '../automation-runs-paging' -import { RuntimeClientError } from '../runtime-client' +} from './automation-runs-paging' +import { RuntimeClientError } from '../runtime/types' import { getOptionalWorktreeSelector, resolveCurrentWorktreeSelector } from '../selectors' import { assertWorkspaceTargetFlagsCompatible, diff --git a/src/cli/browser/browser-capture.ts b/src/cli/browser/browser-capture.ts index bfa0f3e45e3..fbb42e2b209 100644 --- a/src/cli/browser/browser-capture.ts +++ b/src/cli/browser/browser-capture.ts @@ -8,7 +8,7 @@ import type { BrowserNetworkLogResult } from '../../shared/browser/runtime/runtime-browser-contracts' import type { CommandHandler } from '../dispatch' -import { printResult } from '../format' +import { printResult } from '../command-result-output' import { getOptionalPositiveIntegerFlag, getOptionalStringFlag } from '../flags' import { getBrowserCommandTarget } from './browser-command-target' diff --git a/src/cli/browser/browser-cookie.ts b/src/cli/browser/browser-cookie.ts index aab052fc999..e43f53780a6 100644 --- a/src/cli/browser/browser-cookie.ts +++ b/src/cli/browser/browser-cookie.ts @@ -4,7 +4,7 @@ import type { BrowserCookieSetResult } from '../../shared/browser/runtime/runtime-browser-contracts' import type { CommandHandler } from '../dispatch' -import { printResult } from '../format' +import { printResult } from '../command-result-output' import { getOptionalStringFlag, getRequiredStringFlag, diff --git a/src/cli/browser/browser-env.ts b/src/cli/browser/browser-env.ts index 62c93f2c1fb..640a15691a9 100644 --- a/src/cli/browser/browser-env.ts +++ b/src/cli/browser/browser-env.ts @@ -3,7 +3,7 @@ import type { BrowserViewportResult } from '../../shared/browser/runtime/runtime-browser-contracts' import type { CommandHandler } from '../dispatch' -import { printResult } from '../format' +import { printResult } from '../command-result-output' import { getOptionalStringFlag, getRequiredFiniteNumber, diff --git a/src/cli/browser/browser-extension.ts b/src/cli/browser/browser-extension.ts index 471efb88e63..3ea39ad1b05 100644 --- a/src/cli/browser/browser-extension.ts +++ b/src/cli/browser/browser-extension.ts @@ -4,7 +4,7 @@ import type { } from '../../shared/browser/extensions/browser-extension-types' import type { CommandHandler } from '../dispatch' import { getPresentStringFlag } from '../flags' -import { printResult } from '../format' +import { printResult } from '../command-result-output' import { resolveRepoPathArgument } from '../repo-path-arguments' export const BROWSER_EXTENSION_HANDLERS: Record = { diff --git a/src/cli/browser/browser-identity.ts b/src/cli/browser/browser-identity.ts index 04a2fcb4403..1b1936b0d03 100644 --- a/src/cli/browser/browser-identity.ts +++ b/src/cli/browser/browser-identity.ts @@ -7,7 +7,7 @@ import { BROWSER_IDENTITY_RUNTIME_CAPABILITY } from '../../shared/browser/runtim import type { RuntimeStatus } from '../../shared/runtime-session-contracts' import type { CommandHandler, HandlerContext } from '../dispatch' import { getRequiredStringFlag } from '../flags' -import { printResult } from '../format' +import { printResult } from '../command-result-output' import { RuntimeClientError } from '../runtime/types' async function assertBrowserIdentitySupported({ client }: HandlerContext): Promise { diff --git a/src/cli/browser/browser-interact.ts b/src/cli/browser/browser-interact.ts index 34b37ab08df..adb552be8fd 100644 --- a/src/cli/browser/browser-interact.ts +++ b/src/cli/browser/browser-interact.ts @@ -14,7 +14,7 @@ import type { } from '../../shared/browser/runtime/runtime-browser-contracts' import type { CommandHandler } from '../dispatch' import { resolveRepoPathArgument } from '../repo-path-arguments' -import { printResult } from '../format' +import { printResult } from '../command-result-output' import { getOptionalNumberFlag, getOptionalStringFlag, diff --git a/src/cli/browser/browser-nav.ts b/src/cli/browser/browser-nav.ts index 968ef204203..aff3df6d7b7 100644 --- a/src/cli/browser/browser-nav.ts +++ b/src/cli/browser/browser-nav.ts @@ -12,7 +12,7 @@ import type { } from '../../shared/browser/runtime/runtime-browser-contracts' import type { CommandHandler } from '../dispatch' import { formatScreenshot, formatSnapshot, saveBrowserScreenshot } from './browser-format' -import { printResult } from '../format' +import { printResult } from '../command-result-output' import { getOptionalPositiveIntegerFlag, getOptionalStringFlag, diff --git a/src/cli/browser/browser-profile.ts b/src/cli/browser/browser-profile.ts index 5010332c322..38773dbc618 100644 --- a/src/cli/browser/browser-profile.ts +++ b/src/cli/browser/browser-profile.ts @@ -13,7 +13,7 @@ import { formatTabProfileClone, formatTabProfileShow } from './browser-format' -import { printResult } from '../format' +import { printResult } from '../command-result-output' import { RuntimeClientError } from '../runtime/types' import { getBrowserCommandTarget } from './browser-command-target' diff --git a/src/cli/browser/browser-storage.ts b/src/cli/browser/browser-storage.ts index e0d3edd041f..76e98a0883d 100644 --- a/src/cli/browser/browser-storage.ts +++ b/src/cli/browser/browser-storage.ts @@ -1,5 +1,5 @@ import type { CommandHandler } from '../dispatch' -import { printResult } from '../format' +import { printResult } from '../command-result-output' import { getRequiredStringFlag, getRequiredStringFlagAllowingEmpty } from '../flags' import { getBrowserCommandTarget } from './browser-command-target' diff --git a/src/cli/browser/browser-tab.ts b/src/cli/browser/browser-tab.ts index 7ee72d93664..4b8b9f89fb8 100644 --- a/src/cli/browser/browser-tab.ts +++ b/src/cli/browser/browser-tab.ts @@ -12,7 +12,7 @@ import { formatTabListWithProfiles, formatTabShow } from './browser-format' -import { printResult } from '../format' +import { printResult } from '../command-result-output' import { getOptionalNonNegativeIntegerFlag, getOptionalStringFlag, diff --git a/src/cli/cli-error.ts b/src/cli/cli-error.ts index 07a4fe913ea..3ac5d47b31f 100644 --- a/src/cli/cli-error.ts +++ b/src/cli/cli-error.ts @@ -3,7 +3,7 @@ import { matchAutomationOwnerConflict, stripAutomationOwnerConflictCode } from '../shared/automations/ownership/automation-owner-conflict' -import { automationOwnerConflictRecovery } from './automation-owner-conflict-recovery' +import { automationOwnerConflictRecovery } from './automations/automation-owner-conflict-recovery' import { worktreeSelectorRecovery } from './worktree-selector-recovery' import { ambiguousWorkspaceChoices, selectorAmbiguityRecovery } from './selector-ambiguity-recovery' import type { RuntimeRpcFailure } from './runtime-client' diff --git a/src/cli/format.test.ts b/src/cli/command-result-output.test.ts similarity index 96% rename from src/cli/format.test.ts rename to src/cli/command-result-output.test.ts index 1da2db9980e..261c32738e5 100644 --- a/src/cli/format.test.ts +++ b/src/cli/command-result-output.test.ts @@ -3,7 +3,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import { printResult } from './format' +import { printResult } from './command-result-output' let testScreenshotDir: string | null = null diff --git a/src/cli/command-result-output.ts b/src/cli/command-result-output.ts new file mode 100644 index 00000000000..d70a2689c55 --- /dev/null +++ b/src/cli/command-result-output.ts @@ -0,0 +1,15 @@ +import { formatBrowserActionEffects } from './browser/browser-format' +import { prepareComputerCliJsonResult } from './computer/computer-format' +import type { RuntimeRpcSuccess } from '../shared/runtime-rpc-envelope' + +export function printResult( + response: RuntimeRpcSuccess, + json: boolean, + formatter: (value: TResult) => string +): void { + if (json) { + console.log(JSON.stringify(prepareComputerCliJsonResult(response), null, 2)) + return + } + console.log(formatter(response.result) + formatBrowserActionEffects(response.result)) +} diff --git a/src/cli/handlers/computer-action-flag-validation.ts b/src/cli/computer/computer-action-flag-validation.ts similarity index 98% rename from src/cli/handlers/computer-action-flag-validation.ts rename to src/cli/computer/computer-action-flag-validation.ts index eec164018ea..76d54cfd1e2 100644 --- a/src/cli/handlers/computer-action-flag-validation.ts +++ b/src/cli/computer/computer-action-flag-validation.ts @@ -1,4 +1,4 @@ -import { RuntimeClientError } from '../runtime-client' +import { RuntimeClientError } from '../runtime/types' export function validateExclusiveWindowTarget( windowId: number | undefined, diff --git a/src/cli/handlers/computer-action-flags.ts b/src/cli/computer/computer-action-flags.ts similarity index 99% rename from src/cli/handlers/computer-action-flags.ts rename to src/cli/computer/computer-action-flags.ts index b8aa3d49a19..9fb948e40dd 100644 --- a/src/cli/handlers/computer-action-flags.ts +++ b/src/cli/computer/computer-action-flags.ts @@ -11,7 +11,7 @@ import { getRequiredStringFlag, getRequiredStringFlagAllowingEmpty } from '../flags' -import { RuntimeClientError } from '../runtime-client' +import { RuntimeClientError } from '../runtime/types' import { validateDragTarget, validateElementOrCoordinates, diff --git a/src/cli/handlers/computer-action-validation.test.ts b/src/cli/computer/computer-action-validation.test.ts similarity index 63% rename from src/cli/handlers/computer-action-validation.test.ts rename to src/cli/computer/computer-action-validation.test.ts index cc374a1fc1e..06877cd1de3 100644 --- a/src/cli/handlers/computer-action-validation.test.ts +++ b/src/cli/computer/computer-action-validation.test.ts @@ -2,20 +2,16 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' const callMock = vi.fn() -vi.mock('../runtime-client', async () => { +vi.mock('../runtime/client', async () => { class RuntimeClient { call = callMock getCliStatus = vi.fn() openOrca = vi.fn() } - - // Error formatting uses instanceof, so preserve the production error classes. - const { RuntimeClientError, RuntimeRpcFailureError } = await import('../runtime/types.js') - return { RuntimeClient, RuntimeClientError, RuntimeRpcFailureError } + return { RuntimeClient } }) import { main } from '../index' -import { okFixture, queueFixtures } from '../test-fixtures' describe('orca computer action CLI validation', () => { beforeEach(() => { @@ -86,55 +82,6 @@ describe('orca computer action CLI validation', () => { expect(process.exitCode).toBe(1) }) - it('allows literal plus as a press-key key', async () => { - queueFixtures( - callMock, - okFixture('req_press_key', { - snapshot: { - id: 'snap-1', - app: { name: 'Finder', bundleId: 'com.apple.finder', pid: 100 }, - window: { title: 'Finder', id: 1, width: 800, height: 600 }, - coordinateSpace: 'window', - treeText: 'tree', - elementCount: 1, - focusedElementId: null - }, - screenshot: null, - screenshotStatus: { state: 'skipped', reason: 'no_screenshot_flag' }, - action: { - path: 'synthetic', - actionName: 'pressKey', - verification: { state: 'unverified', reason: 'synthetic_input' } - } - }) - ) - - await main( - [ - 'computer', - 'press-key', - '--session', - 'manual', - '--app', - 'Finder', - '--key', - '+', - '--no-screenshot' - ], - '/tmp/repo/src' - ) - - expect(callMock).toHaveBeenCalledWith('computer.pressKey', { - session: 'manual', - app: 'Finder', - key: '+', - noScreenshot: true, - treeDiff: true - }) - expect(vi.mocked(console.error)).not.toHaveBeenCalled() - expect(process.exitCode).toBeUndefined() - }) - it('rejects conflicting get-app-state window target flags before calling the runtime', async () => { await main( [ @@ -199,61 +146,6 @@ describe('orca computer action CLI validation', () => { expect(vi.mocked(console.error).mock.calls[0][0]).toContain('Missing text from stdin') expect(process.exitCode).toBe(1) }) - - it('allows empty stdin for set-value so fields can be cleared', async () => { - queueFixtures( - callMock, - okFixture('req_set_value', { - snapshot: { - id: 'snap-1', - app: { name: 'Finder', bundleId: 'com.apple.finder', pid: 100 }, - window: { title: 'Finder', id: 1, width: 800, height: 600 }, - coordinateSpace: 'window', - treeText: 'tree', - elementCount: 1, - focusedElementId: null - }, - screenshot: null, - screenshotStatus: { state: 'skipped', reason: 'no_screenshot_flag' }, - action: { - path: 'accessibility', - actionName: 'setValue', - verification: { state: 'verified', property: 'value' } - } - }) - ) - const stdin = mockStdin(false, []) - try { - await main( - [ - 'computer', - 'set-value', - '--session', - 'manual', - '--app', - 'Finder', - '--element-index', - '1', - '--value-stdin', - '--no-screenshot' - ], - '/tmp/repo/src' - ) - } finally { - stdin.restore() - } - - expect(callMock).toHaveBeenCalledWith('computer.setValue', { - session: 'manual', - app: 'Finder', - elementIndex: 1, - value: '', - noScreenshot: true, - treeDiff: true - }) - expect(vi.mocked(console.error)).not.toHaveBeenCalled() - expect(process.exitCode).toBeUndefined() - }) }) function mockStdin(isTTY: boolean, chunks: string[]): { restore: () => void } { diff --git a/src/cli/computer-format.ts b/src/cli/computer/computer-format.ts similarity index 96% rename from src/cli/computer-format.ts rename to src/cli/computer/computer-format.ts index a347612d595..05b6dd980ac 100644 --- a/src/cli/computer-format.ts +++ b/src/cli/computer/computer-format.ts @@ -1,14 +1,14 @@ -import { writeCliScreenshotTempFile } from './cli-screenshot-temp-file' -import { formatBase64PayloadByteCount } from './base64-payload-byte-count' -import { quoteCliCommandArgument } from './shell-command-quote' +import { writeCliScreenshotTempFile } from '../cli-screenshot-temp-file' +import { formatBase64PayloadByteCount } from '../base64-payload-byte-count' +import { quoteCliCommandArgument } from '../shell-command-quote' import type { ComputerActionMetadata, ComputerActionResult, ComputerListAppsResult, ComputerListWindowsResult, ComputerSnapshotResult -} from '../shared/runtime-types' -import type { RuntimeRpcSuccess } from './runtime-client' +} from '../../shared/computer-use-runtime-types' +import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope' export function formatGetAppState(result: ComputerSnapshotResult): string { const app = result.snapshot.app diff --git a/src/cli/handlers/computer-state-formatting.test.ts b/src/cli/computer/computer-state-formatting.test.ts similarity index 88% rename from src/cli/handlers/computer-state-formatting.test.ts rename to src/cli/computer/computer-state-formatting.test.ts index c1833fcc33a..881f68fa892 100644 --- a/src/cli/handlers/computer-state-formatting.test.ts +++ b/src/cli/computer/computer-state-formatting.test.ts @@ -5,36 +5,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const callMock = vi.fn() -vi.mock('../runtime-client', () => { +vi.mock('../runtime/client', () => { class RuntimeClient { call = callMock getCliStatus = vi.fn() openOrca = vi.fn() } - class RuntimeClientError extends Error { - readonly code: string - - constructor(code: string, message: string) { - super(message) - this.code = code - } - } - - class RuntimeRpcFailureError extends RuntimeClientError { - readonly response: unknown - - constructor(response: unknown) { - super('runtime_error', 'runtime_error') - this.response = response - } - } - - return { - RuntimeClient, - RuntimeClientError, - RuntimeRpcFailureError - } + return { RuntimeClient } }) import { main } from '../index' diff --git a/src/cli/computer-tree-query.test.ts b/src/cli/computer/computer-tree-query.test.ts similarity index 82% rename from src/cli/computer-tree-query.test.ts rename to src/cli/computer/computer-tree-query.test.ts index a011d7d1306..3a39ac36235 100644 --- a/src/cli/computer-tree-query.test.ts +++ b/src/cli/computer/computer-tree-query.test.ts @@ -30,10 +30,4 @@ describe('queryComputerTreeText', () => { ].join('\n') ) }) - - it('says when nothing matches instead of printing an empty tree', () => { - expect(queryComputerTreeText(TREE, { query: 'underline' })).toContain( - '\n\nNo elements match "underline".\n\nThe focused UI element is' - ) - }) }) diff --git a/src/cli/computer-tree-query.ts b/src/cli/computer/computer-tree-query.ts similarity index 97% rename from src/cli/computer-tree-query.ts rename to src/cli/computer/computer-tree-query.ts index 37ecc7db915..a7971a81f3e 100644 --- a/src/cli/computer-tree-query.ts +++ b/src/cli/computer/computer-tree-query.ts @@ -2,7 +2,7 @@ import { joinComputerTreeText, parseComputerTreeText, type ComputerTreeElement -} from '../shared/computer-use-tree-text' +} from '../../shared/computer-use-tree-text' export type ComputerTreeQuery = { query?: string diff --git a/src/cli/handlers/computer.ts b/src/cli/computer/computer.ts similarity index 97% rename from src/cli/handlers/computer.ts rename to src/cli/computer/computer.ts index 8f7df829357..0240aa65343 100644 --- a/src/cli/handlers/computer.ts +++ b/src/cli/computer/computer.ts @@ -4,22 +4,22 @@ import type { ComputerListWindowsResult, ComputerProviderCapabilities, ComputerSnapshotResult -} from '../../shared/runtime-types' +} from '../../shared/computer-use-runtime-types' import type { CommandHandler } from '../dispatch' import { getOptionalPositiveIntegerFlag, getOptionalStringFlag, getRequiredStringFlag } from '../flags' -import { queryComputerTreeText } from '../computer-tree-query' -import { RuntimeClientError } from '../runtime-client' +import { queryComputerTreeText } from './computer-tree-query' +import { RuntimeClientError } from '../runtime/types' import { formatComputerAction, formatGetAppState, formatListApps, - formatListWindows, - printResult -} from '../format' + formatListWindows +} from './computer-format' +import { printResult } from '../command-result-output' import { getComputerCommandTarget } from '../selectors' import { getComputerActionObserveFlags, diff --git a/src/cli/emulator-logcat-format.ts b/src/cli/emulator/emulator-logcat-format.ts similarity index 100% rename from src/cli/emulator-logcat-format.ts rename to src/cli/emulator/emulator-logcat-format.ts diff --git a/src/cli/emulator-permissions-args.ts b/src/cli/emulator/emulator-permissions-args.ts similarity index 88% rename from src/cli/emulator-permissions-args.ts rename to src/cli/emulator/emulator-permissions-args.ts index 0d6c6916379..0f02c5342ad 100644 --- a/src/cli/emulator-permissions-args.ts +++ b/src/cli/emulator/emulator-permissions-args.ts @@ -1,5 +1,5 @@ -import { getOptionalStringFlag, getRequiredStringFlag } from './flags' -import { RuntimeClientError } from './runtime-client' +import { getOptionalStringFlag, getRequiredStringFlag } from '../flags' +import { RuntimeClientError } from '../runtime/types' export type EmulatorPermissionRequest = { op: 'grant' | 'revoke' | 'reset' diff --git a/src/cli/emulator/emulator.test.ts b/src/cli/emulator/emulator.test.ts new file mode 100644 index 00000000000..5c98543d6a8 --- /dev/null +++ b/src/cli/emulator/emulator.test.ts @@ -0,0 +1,90 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const { callMock, remoteMock } = vi.hoisted(() => ({ + callMock: vi.fn(), + remoteMock: vi.fn(() => false) +})) + +vi.mock('../runtime/client', async () => { + class RuntimeClient { + readonly isRemote: boolean + call = callMock + getCliStatus = vi.fn() + openOrca = vi.fn() + + constructor() { + this.isRemote = remoteMock() + } + } + return { RuntimeClient } +}) + +import { main } from '../index' + +describe('orca emulator CLI handlers', () => { + const originalWorkspaceId = process.env.ORCA_WORKSPACE_ID + const originalWorktreeId = process.env.ORCA_WORKTREE_ID + + beforeEach(() => { + vi.restoreAllMocks() + callMock.mockReset() + remoteMock.mockReturnValue(false) + vi.spyOn(console, 'log').mockImplementation(() => {}) + vi.spyOn(console, 'error').mockImplementation(() => {}) + process.exitCode = undefined + }) + + afterEach(() => { + if (originalWorkspaceId === undefined) { + delete process.env.ORCA_WORKSPACE_ID + } else { + process.env.ORCA_WORKSPACE_ID = originalWorkspaceId + } + if (originalWorktreeId === undefined) { + delete process.env.ORCA_WORKTREE_ID + } else { + process.env.ORCA_WORKTREE_ID = originalWorktreeId + } + }) + + it('rejects relative APK paths for remote runtimes', async () => { + remoteMock.mockReturnValue(true) + + await main( + ['emulator', 'install', 'build/app.apk', '--pairing-code', 'remote', '--worktree', 'all'], + '/repo/project' + ) + + expect(callMock).not.toHaveBeenCalled() + expect(vi.mocked(console.error).mock.calls[0][0]).toContain( + 'Remote emulator install requires --path to be an absolute path on the remote server.' + ) + expect(process.exitCode).toBe(1) + }) + + it('rejects permission reset with package-like arguments', async () => { + await main( + ['emulator', 'permissions', 'reset', 'com.example.app', '--worktree', 'all'], + '/repo/project' + ) + + expect(callMock).not.toHaveBeenCalled() + expect(vi.mocked(console.error).mock.calls[0][0]).toContain( + 'reset does not accept package or permission' + ) + expect(process.exitCode).toBe(1) + }) + + it('rejects grant without a permission before calling the runtime', async () => { + await main( + ['emulator', 'permissions', 'grant', 'com.example.app', '--worktree', 'all'], + '/repo/project' + ) + + expect(callMock).not.toHaveBeenCalled() + expect(vi.mocked(console.error).mock.calls[0][0]).toContain( + ' is required for grant' + ) + expect(process.exitCode).toBe(1) + }) +}) diff --git a/src/cli/handlers/emulator.ts b/src/cli/emulator/emulator.ts similarity index 97% rename from src/cli/handlers/emulator.ts rename to src/cli/emulator/emulator.ts index d1a549102ef..e6613644921 100644 --- a/src/cli/handlers/emulator.ts +++ b/src/cli/emulator/emulator.ts @@ -1,7 +1,7 @@ import type { CommandHandler } from '../dispatch' -import { formatLogcat } from '../emulator-logcat-format' -import { parseEmulatorPermissionRequest } from '../emulator-permissions-args' -import { printResult } from '../format' +import { formatLogcat } from './emulator-logcat-format' +import { parseEmulatorPermissionRequest } from './emulator-permissions-args' +import { printResult } from '../command-result-output' import { resolveRepoPathArgument } from '../repo-path-arguments' import { getOptionalPositiveIntegerFlag, @@ -10,7 +10,7 @@ import { getRequiredStringFlag } from '../flags' import { getEmulatorCommandTarget } from '../selectors' -import { RuntimeClientError } from '../runtime-client' +import { RuntimeClientError } from '../runtime/types' import { EMULATOR_ATTACH_RPC_TIMEOUT_MS } from '../../shared/emulator-attach-timeouts' type EmulatorAttachResult = { diff --git a/src/cli/handlers/file-absolute-paths.test.ts b/src/cli/files/file-absolute-paths.test.ts similarity index 80% rename from src/cli/handlers/file-absolute-paths.test.ts rename to src/cli/files/file-absolute-paths.test.ts index f4215077ccc..c39dcf9a8be 100644 --- a/src/cli/handlers/file-absolute-paths.test.ts +++ b/src/cli/files/file-absolute-paths.test.ts @@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const callMock = vi.fn() -vi.mock('../runtime-client', () => { +vi.mock('../runtime/client', () => { class RuntimeClient { readonly isRemote = false call = callMock @@ -10,25 +10,7 @@ vi.mock('../runtime-client', () => { openOrca = vi.fn() } - class RuntimeClientError extends Error { - readonly code: string - - constructor(code: string, message: string) { - super(message) - this.code = code - } - } - - class RuntimeRpcFailureError extends RuntimeClientError { - readonly response: unknown - - constructor(response: unknown) { - super('runtime_error', 'runtime_error') - this.response = response - } - } - - return { RuntimeClient, RuntimeClientError, RuntimeRpcFailureError } + return { RuntimeClient } }) import { main } from '../index' diff --git a/src/cli/handlers/file-open-call.ts b/src/cli/files/file-open-call.ts similarity index 90% rename from src/cli/handlers/file-open-call.ts rename to src/cli/files/file-open-call.ts index 7eca5572777..e50028a7b48 100644 --- a/src/cli/handlers/file-open-call.ts +++ b/src/cli/files/file-open-call.ts @@ -1,6 +1,7 @@ import type { RuntimeFileOpenResult } from '../../shared/file-access/runtime-editor-file-open' import type { HandlerContext } from '../dispatch' -import { RuntimeClientError, type RuntimeRpcSuccess } from '../runtime-client' +import { RuntimeClientError } from '../runtime/types' +import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope' const NO_APP_WINDOW_MESSAGE = 'This Orca server has no app window, so it cannot open files as tabs. Nothing was opened.' diff --git a/src/cli/handlers/file-open-position.ts b/src/cli/files/file-open-position.ts similarity index 95% rename from src/cli/handlers/file-open-position.ts rename to src/cli/files/file-open-position.ts index 9edc09a0717..0975d8ea4f4 100644 --- a/src/cli/handlers/file-open-position.ts +++ b/src/cli/files/file-open-position.ts @@ -1,6 +1,6 @@ import type { RuntimeFileOpenPosition } from '../../shared/file-access/runtime-editor-file-open' import { getOptionalPositiveIntegerFlag } from '../flags' -import { RuntimeClientError } from '../runtime-client' +import { RuntimeClientError } from '../runtime/types' export function getFileOpenPosition( flags: Map diff --git a/src/cli/handlers/file.test.ts b/src/cli/files/file.test.ts similarity index 84% rename from src/cli/handlers/file.test.ts rename to src/cli/files/file.test.ts index 0aa4927170f..4f5f1a4ed0a 100644 --- a/src/cli/handlers/file.test.ts +++ b/src/cli/files/file.test.ts @@ -2,7 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' const callMock = vi.fn() -vi.mock('../runtime-client', () => { +vi.mock('../runtime/client', () => { class RuntimeClient { readonly isRemote: boolean call = callMock @@ -19,29 +19,7 @@ vi.mock('../runtime-client', () => { } } - class RuntimeClientError extends Error { - readonly code: string - - constructor(code: string, message: string) { - super(message) - this.code = code - } - } - - class RuntimeRpcFailureError extends RuntimeClientError { - readonly response: unknown - - constructor(response: unknown) { - super('runtime_error', 'runtime_error') - this.response = response - } - } - - return { - RuntimeClient, - RuntimeClientError, - RuntimeRpcFailureError - } + return { RuntimeClient } }) import { main } from '../index' diff --git a/src/cli/handlers/file.ts b/src/cli/files/file.ts similarity index 98% rename from src/cli/handlers/file.ts rename to src/cli/files/file.ts index 68aef649b48..a3c77a52438 100644 --- a/src/cli/handlers/file.ts +++ b/src/cli/files/file.ts @@ -1,14 +1,14 @@ import { getFileOpenPosition } from './file-open-position' import type { GitStatusEntry, GitStatusResult } from '../../shared/git/status/git-status-types' import type { RuntimeFileOpenResult } from '../../shared/file-access/runtime-editor-file-open' -import type { RuntimeWorktreeRecord } from '../../shared/runtime-types' +import type { RuntimeWorktreeRecord } from '../../shared/runtime-worktree-contracts' import type { RuntimeNavigationTarget } from '../../shared/runtime-navigation' import { isRuntimePathAbsolute, relativePathInsideRoot } from '../../shared/cross-platform-path' import { isWslUncPath, parseWslUncPath, toWindowsWslPath } from '../../shared/wsl-paths' import type { CommandHandler, HandlerContext } from '../dispatch' import { getOptionalStringFlag, getRequiredStringFlag } from '../flags' -import { printResult } from '../format' -import { RuntimeClientError } from '../runtime-client' +import { printResult } from '../command-result-output' +import { RuntimeClientError } from '../runtime/types' import { callFileOpen } from './file-open-call' import { getOptionalWorktreeSelector, resolveCurrentWorktreeSelector } from '../selectors' diff --git a/src/cli/format.ts b/src/cli/format.ts deleted file mode 100644 index 27f39e160da..00000000000 --- a/src/cli/format.ts +++ /dev/null @@ -1,146 +0,0 @@ -import type { CliStatusCaller } from '../shared/orchestration/orchestration-caller-status' -import type { CliStatusResult } from '../shared/runtime-types' -import { formatBrowserActionEffects } from './browser/browser-format' -import { prepareComputerCliJsonResult } from './computer-format' -import type { RuntimeRpcSuccess } from './runtime-client' - -export { formatCliError, reportCliError, type CliErrorContext } from './cli-error' - -export { - formatComputerAction, - formatGetAppState, - formatListApps, - formatListWindows -} from './computer-format' -export type { ComputerActionFollowUpTarget } from './computer-format' -export { - formatProjectHostSetupCreateResult, - formatProjectHostSetupDeleteResult, - formatProjectHostSetupList, - formatProjectHostSetupResult, - formatProjectHostSetupUpdateResult, - formatProjectList -} from './project-format' -export { - formatTerminalClose, - formatTerminalCreate, - formatTerminalFocus, - formatTerminalList, - formatTerminalRead, - formatTerminalRename, - formatTerminalSetPaneTitle, - formatTerminalSend, - formatTerminalShow, - formatTerminalSplit, - formatTerminalWait, - terminalSendWarnings -} from './terminal-format' -export { - formatAutomationList, - formatAutomationRemoved, - formatAutomationRun, - formatAutomationRuns, - formatAutomationRunsPage, - formatAutomationShow -} from './automation-format' -export type { AutomationListPayload, AutomationShowPayload } from './automation-format' -export { - formatEnvironment, - formatEnvironmentList, - formatMemorySnapshot, - formatRepoList, - formatRepoRefs, - formatRepoShow, - formatWorktreeList, - formatWorktreePs, - formatWorktreeShow -} from './workspace-format' - -export function printResult( - response: RuntimeRpcSuccess, - json: boolean, - formatter: (value: TResult) => string -): void { - if (json) { - console.log(JSON.stringify(prepareComputerCliJsonResult(response), null, 2)) - return - } - console.log(formatter(response.result) + formatBrowserActionEffects(response.result)) -} - -export type HostListEntry = { - kind: 'local' | 'ssh' | 'environment' - name: string - id: string - selector: string - platform?: string - machineName?: string - connected?: boolean - connectionStatus?: string -} - -// Explicit host selectors prevent callers from using a display name on the wrong host scope. -export function formatHostList(result: { hosts: HostListEntry[] }): string { - const kindLabel: Record = { - local: 'local', - ssh: 'ssh target', - environment: 'orca server' - } - return result.hosts - .map( - (host) => - `${kindLabel[host.kind].padEnd(11)} ${host.name}${host.machineName ? ` (${host.machineName})` : ''} ${host.platform ?? 'platform unknown'} ${formatHostConnection(host)} -> ${host.selector}` - ) - .join('\n') -} - -/** What one runtime calls itself; `machineName` is absent when the runtime predates the field. */ -export type HostNameResult = { - machineName?: string - platform?: string -} - -export function formatHostName(result: HostNameResult): string { - return `${result.machineName ?? 'unknown'}${result.platform ? ` (${result.platform})` : ''}` -} - -function formatHostConnection(host: HostListEntry): string { - if (host.kind !== 'ssh') { - return '' - } - if (host.connected === undefined) { - return `connection unknown${host.connectionStatus ? ` (${host.connectionStatus})` : ''}` - } - return host.connected - ? `connected${host.connectionStatus ? ` (${host.connectionStatus})` : ''}` - : `not connected${host.connectionStatus ? ` (${host.connectionStatus})` : ''}` -} - -export function formatCliStatus(status: CliStatusResult): string { - return [ - ...(status.target && status.target.kind === 'environment' - ? [`target: environment ${status.target.environment}`] - : []), - `appRunning: ${status.app.running}`, - `pid: ${status.app.pid ?? 'none'}`, - `desktopWindowStatus: ${status.app.desktopWindowStatus ?? 'unknown'}`, - `runtimeState: ${status.runtime.state}`, - `runtimeReachable: ${status.runtime.reachable}`, - `runtimeConnectionState: ${status.runtime.connectionState ?? 'unknown'}`, - `runtimeId: ${status.runtime.runtimeId ?? 'none'}`, - `graphState: ${status.graph.state}`, - ...(status.runtime.degradations ?? []).map((degradation) => `degraded: ${degradation.message}`), - ...(status.caller === undefined ? [] : [`orcaSessionId: ${formatStatusCaller(status.caller)}`]) - ].join('\n') -} - -function formatStatusCaller(caller: CliStatusCaller): string { - if ('refusal' in caller) { - return `none (refused: ${caller.refusal.code})` - } - return `${caller.orcaSessionId}${caller.live ? '' : ' (not live)'}` -} - -export function formatStatus(status: CliStatusResult): string { - return formatCliStatus(status) -} diff --git a/src/cli/handler-group-manifest.ts b/src/cli/handler-group-manifest.ts index 23266e2d1bf..27a788fc857 100644 --- a/src/cli/handler-group-manifest.ts +++ b/src/cli/handler-group-manifest.ts @@ -1,7 +1,7 @@ import type { CommandHandler } from './dispatch' import { BROWSER_HANDLER_GROUPS } from './browser/browser-handler-groups' -import { JIRA_HANDLER_GROUP } from './jira-handler-group' -import { LINEAR_HANDLER_GROUP } from './linear-handler-group' +import { JIRA_HANDLER_GROUP } from './jira/jira-handler-group' +import { LINEAR_HANDLER_GROUP } from './linear/linear-handler-group' import { REFERENCE_HANDLER_GROUP } from './reference-handler-group' import { SERVE_PAIRING_HANDLER_GROUPS } from './serve-pairing-handler-groups' import { PLUGIN_HANDLER_GROUPS } from './plugin-handler-groups' @@ -39,7 +39,7 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [ { name: 'account', keys: ['account add', 'account list', 'account select', 'account rm'], - load: async () => (await import('./handlers/account.js')).ACCOUNT_HANDLERS + load: async () => (await import('./accounts/account.js')).ACCOUNT_HANDLERS }, { name: 'artifacts', @@ -50,7 +50,7 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [ 'artifacts unshare', 'artifacts delete' ], - load: async () => (await import('./handlers/artifacts.js')).ARTIFACT_HANDLERS + load: async () => (await import('./artifacts/artifacts.js')).ARTIFACT_HANDLERS }, { name: 'automations', @@ -63,7 +63,7 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [ 'automations run', 'automations runs' ], - load: async () => (await import('./handlers/automations.js')).AUTOMATION_HANDLERS + load: async () => (await import('./automations/automations.js')).AUTOMATION_HANDLERS }, { name: 'project', @@ -94,7 +94,7 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [ { name: 'file', keys: ['file open', 'file diff', 'file open-changed'], - load: async () => (await import('./handlers/file.js')).FILE_HANDLERS + load: async () => (await import('./files/file.js')).FILE_HANDLERS }, { name: 'terminal', @@ -174,7 +174,7 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [ 'emulator ax', 'emulator logcat' ], - load: async () => (await import('./handlers/emulator.js')).EMULATOR_HANDLERS + load: async () => (await import('./emulator/emulator.js')).EMULATOR_HANDLERS }, { name: 'computer', @@ -194,22 +194,22 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [ 'computer paste-text', 'computer set-value' ], - load: async () => (await import('./handlers/computer.js')).COMPUTER_HANDLERS + load: async () => (await import('./computer/computer.js')).COMPUTER_HANDLERS }, { name: 'agent-hooks', keys: ['agent hooks prepare-codex', 'agent hooks status', 'agent hooks off', 'agent hooks on'], - load: async () => (await import('./handlers/agent-hooks.js')).AGENT_HOOK_HANDLERS + load: async () => (await import('./agents/agent-hooks.js')).AGENT_HOOK_HANDLERS }, { name: 'agent-launch', keys: ['agent launch'], - load: async () => (await import('./handlers/agent-launch.js')).AGENT_LAUNCH_HANDLERS + load: async () => (await import('./agents/agent-launch.js')).AGENT_LAUNCH_HANDLERS }, { name: 'chat', keys: ['chat rename'], - load: async () => (await import('./handlers/chat.js')).CHAT_HANDLERS + load: async () => (await import('./agents/chat.js')).CHAT_HANDLERS }, { name: 'connector', @@ -259,11 +259,11 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [ { name: 'search', keys: ['search'], - load: async () => (await import('./handlers/search.js')).SEARCH_HANDLERS + load: async () => (await import('./session-search/search.js')).SEARCH_HANDLERS }, { name: 'ports', keys: ['ports'], - load: async () => (await import('./handlers/ports.js')).PORTS_HANDLERS + load: async () => (await import('./workspace-ports/ports.js')).PORTS_HANDLERS } ] diff --git a/src/cli/handlers/automation-owner-fencing.test.ts b/src/cli/handlers/automation-owner-fencing.test.ts deleted file mode 100644 index e5b4b6ed0da..00000000000 --- a/src/cli/handlers/automation-owner-fencing.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { AUTOMATION_HANDLERS } from './automations' - -const owner = { selector: { kind: 'ssh', targetId: 'box', targetGeneration: 4 } } - -function ok(result: unknown): unknown { - return { id: 'request-1', ok: true, result, _meta: { runtimeId: 'runtime-1' } } -} - -function clientAnsweringShow(owner: unknown): { call: ReturnType } { - const call = vi.fn(async (method: string) => - method === 'automation.show' - ? ok(owner === undefined ? { automation: { id: 'a1' } } : { automation: { id: 'a1' }, owner }) - : ok({ automation: { id: 'a1' }, removed: true, id: 'a1', run: { id: 'r1' }, runs: [] }) - ) - return { call } -} - -afterEach(() => vi.restoreAllMocks()) - -// Generation-bearing SSH records reject mutations that omit the owner precondition. -describe('CLI automation mutations carry the owner they read', () => { - it.each([ - ['automations remove', 'automation.delete'], - ['automations run', 'automation.runNow'] - ])('%s sends the owner from automation.show to %s', async (command, method) => { - const { call } = clientAnsweringShow(owner) - vi.spyOn(console, 'log').mockImplementation(() => undefined) - - await AUTOMATION_HANDLERS[command]!({ - client: { call } as never, - cwd: '/tmp', - flags: new Map([['id', 'a1']]), - json: true - }) - - expect(call).toHaveBeenNthCalledWith(1, 'automation.show', { id: 'a1' }) - expect(call).toHaveBeenNthCalledWith(2, method, { id: 'a1', expectedOwner: owner }) - }) - - it('edit sends the owner alongside the update payload', async () => { - const { call } = clientAnsweringShow(owner) - vi.spyOn(console, 'log').mockImplementation(() => undefined) - - await AUTOMATION_HANDLERS['automations edit']!({ - client: { call } as never, - cwd: '/tmp', - flags: new Map([ - ['id', 'a1'], - ['name', 'renamed'] - ]), - json: true - }) - - expect(call).toHaveBeenNthCalledWith( - 2, - 'automation.update', - expect.objectContaining({ id: 'a1', expectedOwner: owner }) - ) - }) - - // Older hosts supply no owner and require no precondition. - it('omits the precondition when the host reports no owner', async () => { - const { call } = clientAnsweringShow(undefined) - vi.spyOn(console, 'log').mockImplementation(() => undefined) - - await AUTOMATION_HANDLERS['automations run']!({ - client: { call } as never, - cwd: '/tmp', - flags: new Map([['id', 'a1']]), - json: true - }) - - expect(call).toHaveBeenNthCalledWith(2, 'automation.runNow', { id: 'a1' }) - }) -}) diff --git a/src/cli/handlers/connector.ts b/src/cli/handlers/connector.ts index 5f392f11444..9ae2109977c 100644 --- a/src/cli/handlers/connector.ts +++ b/src/cli/handlers/connector.ts @@ -7,7 +7,7 @@ import { getOptionalStringFlag, getRequiredStringFlag } from '../flags' -import { printResult } from '../format' +import { printResult } from '../command-result-output' import { RuntimeClientError } from '../runtime-client' import { getRequiredWorktreeSelector } from '../selectors' diff --git a/src/cli/handlers/core.ts b/src/cli/handlers/core.ts index 7f320e3394e..4eba110c8c2 100644 --- a/src/cli/handlers/core.ts +++ b/src/cli/handlers/core.ts @@ -1,7 +1,8 @@ import { spawn } from 'node:child_process' import { resolve } from 'node:path' import type { CommandHandler } from '../dispatch' -import { formatCliStatus, formatStatus, printResult } from '../format' +import { formatCliStatus, formatCliStatus as formatStatus } from '../runtime/cli-status-format' +import { printResult } from '../command-result-output' import { RuntimeClientError, serveOrcaApp } from '../runtime-client' import { getOptionalServeBind } from '../runtime/serve-bind-flag' import { stripElectronRunAsNode } from '../runtime/orca-app-executable' diff --git a/src/cli/handlers/diagnostics.ts b/src/cli/handlers/diagnostics.ts index eb894b73696..8bb9841442f 100644 --- a/src/cli/handlers/diagnostics.ts +++ b/src/cli/handlers/diagnostics.ts @@ -1,6 +1,7 @@ import type { MemorySnapshot } from '../../shared/process-stats-types' import type { CommandHandler } from '../dispatch' -import { formatMemorySnapshot, printResult } from '../format' +import { formatMemorySnapshot } from '../workspace-format' +import { printResult } from '../command-result-output' import { TERMINAL_DAEMON_HANDLERS } from './terminal-daemon' export const DIAGNOSTICS_HANDLERS: Record = { diff --git a/src/cli/handlers/emulator.test.ts b/src/cli/handlers/emulator.test.ts deleted file mode 100644 index e13f06c7952..00000000000 --- a/src/cli/handlers/emulator.test.ts +++ /dev/null @@ -1,185 +0,0 @@ -import path from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { callMock, remoteMock } = vi.hoisted(() => ({ - callMock: vi.fn(), - remoteMock: vi.fn(() => false) -})) - -vi.mock('../runtime-client', async () => { - class RuntimeClient { - readonly isRemote: boolean - call = callMock - getCliStatus = vi.fn() - openOrca = vi.fn() - - constructor() { - this.isRemote = remoteMock() - } - } - - // Error formatting uses instanceof, so preserve the production error classes. - const { RuntimeClientError, RuntimeRpcFailureError } = await import('../runtime/types.js') - return { RuntimeClient, RuntimeClientError, RuntimeRpcFailureError } -}) - -import { main } from '../index' -import { okFixture, queueFixtures } from '../test-fixtures' - -describe('orca emulator CLI handlers', () => { - const originalWorkspaceId = process.env.ORCA_WORKSPACE_ID - const originalWorktreeId = process.env.ORCA_WORKTREE_ID - - beforeEach(() => { - vi.restoreAllMocks() - callMock.mockReset() - remoteMock.mockReturnValue(false) - vi.spyOn(console, 'log').mockImplementation(() => {}) - vi.spyOn(console, 'error').mockImplementation(() => {}) - process.exitCode = undefined - }) - - afterEach(() => { - if (originalWorkspaceId === undefined) { - delete process.env.ORCA_WORKSPACE_ID - } else { - process.env.ORCA_WORKSPACE_ID = originalWorkspaceId - } - if (originalWorktreeId === undefined) { - delete process.env.ORCA_WORKTREE_ID - } else { - process.env.ORCA_WORKTREE_ID = originalWorktreeId - } - }) - - it('resolves relative APK paths before calling the runtime', async () => { - queueFixtures(callMock, okFixture('req_install', { ok: true })) - - await main( - ['emulator', 'install', 'build/app.apk', '--reinstall', '--worktree', 'all'], - '/repo/project' - ) - - expect(callMock).toHaveBeenCalledWith('emulator.install', { - path: path.resolve('/repo/project', 'build/app.apk'), - reinstall: true, - device: undefined, - emulator: undefined, - worktree: undefined - }) - }) - - it('uses the folder workspace exported by the current Orca terminal', async () => { - process.env.ORCA_WORKSPACE_ID = 'folder:folder-1' - delete process.env.ORCA_WORKTREE_ID - callMock.mockResolvedValue( - okFixture('req_attach', { - attached: true, - info: { deviceUdid: 'device-1', streamUrl: 'scrcpy://device-1' } - }) - ) - - await main(['emulator', 'attach', 'device-1'], '/folder/project') - - expect(callMock).toHaveBeenCalledOnce() - expect(callMock).toHaveBeenCalledWith( - 'emulator.attach', - { device: 'device-1', worktree: 'folder:folder-1', focus: false }, - { timeoutMs: 240_000 } - ) - }) - - it('uses the current git worktree exported by the Orca terminal', async () => { - process.env.ORCA_WORKSPACE_ID = 'folder:stale-parent' - process.env.ORCA_WORKTREE_ID = 'repo-1::/repo/project ' - callMock.mockResolvedValue( - okFixture('req_attach', { - attached: true, - info: { deviceUdid: 'device-1', streamUrl: 'scrcpy://device-1' } - }) - ) - - await main(['emulator', 'attach', 'device-1'], '/repo/project') - - expect(callMock).toHaveBeenCalledOnce() - expect(callMock).toHaveBeenCalledWith( - 'emulator.attach', - { device: 'device-1', worktree: 'repo-1::/repo/project ', focus: false }, - { timeoutMs: 240_000 } - ) - }) - - it('rejects relative APK paths for remote runtimes', async () => { - remoteMock.mockReturnValue(true) - - await main( - ['emulator', 'install', 'build/app.apk', '--pairing-code', 'remote', '--worktree', 'all'], - '/repo/project' - ) - - expect(callMock).not.toHaveBeenCalled() - expect(vi.mocked(console.error).mock.calls[0][0]).toContain( - 'Remote emulator install requires --path to be an absolute path on the remote server.' - ) - expect(process.exitCode).toBe(1) - }) - - it('preserves absolute server APK paths for remote runtimes', async () => { - remoteMock.mockReturnValue(true) - queueFixtures(callMock, okFixture('req_install', { ok: true })) - - await main( - ['emulator', 'install', 'C:\\tmp\\app.apk', '--pairing-code', 'remote', '--worktree', 'all'], - '/repo/project' - ) - - expect(callMock).toHaveBeenCalledWith('emulator.install', { - path: 'C:\\tmp\\app.apk', - reinstall: false, - device: undefined, - emulator: undefined, - worktree: undefined - }) - }) - - it('allows device-wide permission reset without package or permission', async () => { - queueFixtures(callMock, okFixture('req_permissions', { ok: true })) - - await main(['emulator', 'permissions', 'reset', '--worktree', 'all'], '/repo/project') - - expect(callMock).toHaveBeenCalledWith('emulator.permissions', { - op: 'reset', - package: undefined, - permission: undefined, - device: undefined, - emulator: undefined, - worktree: undefined - }) - }) - - it('rejects permission reset with package-like arguments', async () => { - await main( - ['emulator', 'permissions', 'reset', 'com.example.app', '--worktree', 'all'], - '/repo/project' - ) - - expect(callMock).not.toHaveBeenCalled() - expect(vi.mocked(console.error).mock.calls[0][0]).toContain( - 'reset does not accept package or permission' - ) - expect(process.exitCode).toBe(1) - }) - - it('rejects grant without a permission before calling the runtime', async () => { - await main( - ['emulator', 'permissions', 'grant', 'com.example.app', '--worktree', 'all'], - '/repo/project' - ) - - expect(callMock).not.toHaveBeenCalled() - expect(vi.mocked(console.error).mock.calls[0][0]).toContain( - ' is required for grant' - ) - expect(process.exitCode).toBe(1) - }) -}) diff --git a/src/cli/handlers/environment.ts b/src/cli/handlers/environment.ts index cea32095c3b..cc426c0c060 100644 --- a/src/cli/handlers/environment.ts +++ b/src/cli/handlers/environment.ts @@ -1,12 +1,7 @@ import type { CommandHandler } from '../dispatch' -import { - formatEnvironment, - formatEnvironmentList, - formatHostList, - formatHostName, - printResult, - type HostNameResult -} from '../format' +import { formatEnvironment, formatEnvironmentList } from '../workspace-format' +import { formatHostList, formatHostName, type HostNameResult } from '../hosts/host-format' +import { printResult } from '../command-result-output' import { parseHostFlag } from '../execution-host-flag' import { fetchSshTargetSummaries, diff --git a/src/cli/handlers/folder-workspace-mutations.ts b/src/cli/handlers/folder-workspace-mutations.ts index 1438b220232..4fac8469f47 100644 --- a/src/cli/handlers/folder-workspace-mutations.ts +++ b/src/cli/handlers/folder-workspace-mutations.ts @@ -7,7 +7,8 @@ import type { import type { FolderWorkspace } from '../../shared/folder-workspaces/folder-workspace-types' import { FOLDER_WORKSPACE_UNIQUE_ID_MUTATION_RUNTIME_CAPABILITY } from '../../shared/worktree-runtime-capabilities' import { folderIdOfSelector, folderWorkspaceKey } from '../../shared/workspace-scope' -import { formatWorktreeShow, printResult } from '../format' +import { formatWorktreeShow } from '../workspace-format' +import { printResult } from '../command-result-output' import { getOptionalStringFlag, getOptionalStringFlagAllowingEmpty } from '../flags' import { RuntimeClientError, type RuntimeClient, type RuntimeRpcSuccess } from '../runtime-client' import { getWorktreeReadFlags } from './worktree-unread-flag' diff --git a/src/cli/handlers/interactive-login-interruption.test.ts b/src/cli/handlers/interactive-login-interruption.test.ts deleted file mode 100644 index 1404480dd3e..00000000000 --- a/src/cli/handlers/interactive-login-interruption.test.ts +++ /dev/null @@ -1,136 +0,0 @@ -import { EventEmitter } from 'node:events' -import type { ChildProcess } from 'node:child_process' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { - terminateInteractiveLoginProcess, - terminateWindowsLoginProcessTree -} from './interactive-login-interruption' - -function loginChild(pid = 4321): ChildProcess & EventEmitter { - return Object.assign(new EventEmitter(), { - kill: vi.fn(), - pid - }) as unknown as ChildProcess & EventEmitter -} - -afterEach(() => { - vi.useRealTimers() -}) - -describe('terminateInteractiveLoginProcess', () => { - it('runs bounded taskkill /T /F without a shell', async () => { - const execFileImpl = vi.fn( - ( - _command: string, - _args: readonly string[], - _options: { timeout?: number; windowsHide?: boolean }, - callback: (error: Error | null) => void - ) => callback(null) - ) - - await terminateWindowsLoginProcessTree(4321, execFileImpl as never) - - expect(execFileImpl).toHaveBeenCalledWith( - 'taskkill', - ['/pid', '4321', '/T', '/F'], - { timeout: 5_000, windowsHide: true }, - expect.any(Function) - ) - }) - - it('waits for both Windows tree termination and physical wrapper close', async () => { - const child = loginChild() - let finishTreeKill: (() => void) | undefined - const killWindowsTree = vi.fn( - () => - new Promise((resolve) => { - finishTreeKill = resolve - }) - ) - let terminated = false - - const pending = terminateInteractiveLoginProcess(child, 'SIGTERM', { - platform: 'win32', - killWindowsTree - }).then(() => { - terminated = true - }) - - expect(killWindowsTree).toHaveBeenCalledWith(4321) - child.emit('close', 1) - await Promise.resolve() - expect(terminated).toBe(false) - - finishTreeKill?.() - await pending - expect(child.kill).not.toHaveBeenCalled() - }) - - it('bounds Windows close waits and falls back to the direct wrapper', async () => { - vi.useFakeTimers() - const child = loginChild() - - let terminated = false - const pending = terminateInteractiveLoginProcess(child, 'SIGINT', { - platform: 'win32', - killWindowsTree: vi.fn().mockResolvedValue(undefined) - }).then(() => { - terminated = true - }) - await vi.advanceTimersByTimeAsync(999) - expect(child.kill).not.toHaveBeenCalled() - expect(terminated).toBe(false) - await vi.advanceTimersByTimeAsync(1) - expect(child.kill).toHaveBeenCalledOnce() - expect(child.kill).toHaveBeenCalledWith(undefined) - - await vi.advanceTimersByTimeAsync(999) - expect(terminated).toBe(false) - await vi.advanceTimersByTimeAsync(1) - await pending - expect(terminated).toBe(true) - }) - - it('forwards the interrupt signal to a direct POSIX child and awaits close', async () => { - const child = loginChild() - let terminated = false - - const pending = terminateInteractiveLoginProcess(child, 'SIGHUP', { - platform: 'linux' - }).then(() => { - terminated = true - }) - - expect(child.kill).toHaveBeenCalledWith('SIGHUP') - await Promise.resolve() - expect(terminated).toBe(false) - - child.emit('close', 1) - await pending - expect(child.kill).toHaveBeenCalledOnce() - }) - - it('force-kills an unresponsive POSIX child before the final bounded wait', async () => { - vi.useFakeTimers() - const child = loginChild() - - let terminated = false - const pending = terminateInteractiveLoginProcess(child, 'SIGINT', { - platform: 'darwin' - }).then(() => { - terminated = true - }) - await vi.advanceTimersByTimeAsync(4_999) - expect(child.kill).toHaveBeenCalledExactlyOnceWith('SIGINT') - expect(terminated).toBe(false) - await vi.advanceTimersByTimeAsync(1) - expect(child.kill).toHaveBeenNthCalledWith(1, 'SIGINT') - expect(child.kill).toHaveBeenNthCalledWith(2, 'SIGKILL') - - await vi.advanceTimersByTimeAsync(999) - expect(terminated).toBe(false) - await vi.advanceTimersByTimeAsync(1) - await pending - expect(terminated).toBe(true) - }) -}) diff --git a/src/cli/handlers/linear.test.ts b/src/cli/handlers/linear.test.ts deleted file mode 100644 index e1cd6cc9324..00000000000 --- a/src/cli/handlers/linear.test.ts +++ /dev/null @@ -1,557 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const callMock = vi.fn() - -vi.mock('../runtime-client', async () => { - class RuntimeClient { - readonly isRemote: boolean - call = callMock - getCliStatus = vi.fn() - openOrca = vi.fn() - - constructor( - _userDataPath?: string, - _requestTimeoutMs?: number, - remotePairingCode = process.env.ORCA_PAIRING_CODE ?? null, - environmentSelector = process.env.ORCA_ENVIRONMENT ?? null - ) { - this.isRemote = Boolean(remotePairingCode || environmentSelector) - } - } - - // Error formatting uses instanceof, so preserve the production error classes. - const { RuntimeClientError, RuntimeRpcFailureError } = await import('../runtime/types.js') - - return { - RuntimeClient, - RuntimeClientError, - RuntimeRpcFailureError - } -}) - -import { main } from '../index' -import { okFixture, queueFixtures } from '../test-fixtures' - -describe('orca linear CLI handlers', () => { - const originalEnv = { ...process.env } - - beforeEach(() => { - vi.restoreAllMocks() - callMock.mockReset() - process.env = { ...originalEnv } - // Clear real terminal/worktree/pairing hints inherited from the test runner. - delete process.env.ORCA_WORKTREE_ID - delete process.env.ORCA_TERMINAL_HANDLE - delete process.env.ORCA_PAIRING_CODE - delete process.env.ORCA_ENVIRONMENT - process.exitCode = undefined - vi.spyOn(console, 'log').mockImplementation(() => {}) - vi.spyOn(console, 'error').mockImplementation(() => {}) - }) - - it('maps --full issue reads to read-only issueContext RPC', async () => { - queueFixtures(callMock, okFixture('req_linear', issueResult())) - - await main(['linear', 'issue', 'ENG-123', '--full', '--json'], '/tmp/repo') - - expect(callMock).toHaveBeenCalledWith( - 'linear.issueContext', - { - input: 'ENG-123', - current: false, - workspaceId: undefined, - include: { - comments: true, - children: true, - attachments: true, - relations: true, - activity: true - }, - depth: 2, - context: { - remote: false, - cwd: '/tmp/repo' - } - }, - { timeoutMs: 120_000 } - ) - }) - - it.each([ - { flags: [], depth: 0, children: false }, - { flags: ['--children'], depth: 2, children: true }, - { flags: ['--children', '--depth', '0'], depth: 0, children: true } - ])('routes child depth from CLI flags: $flags', async ({ flags, depth, children }) => { - queueFixtures(callMock, okFixture('req_linear', issueResult())) - await main(['linear', 'issue', 'ENG-123', ...flags, '--json'], '/tmp/repo') - expect(callMock).toHaveBeenCalledWith( - 'linear.issueContext', - expect.objectContaining({ depth, include: expect.objectContaining({ children }) }), - { timeoutMs: undefined } - ) - expect(JSON.parse(String(vi.mocked(console.log).mock.calls[0][0])).result).toEqual( - issueResult() - ) - }) - - it('prints truncation on human stdout and in JSON without using stderr for JSON', async () => { - const listResult = { - issues: [ - { - id: 'issue-1', - identifier: 'ENG-1', - title: 'Fix auth', - url: 'https://linear.app/acme/issue/ENG-1', - labels: [], - workspace: { id: 'workspace-1', name: 'Acme' } - } - ], - truncated: true, - meta: { - limit: 1, - returned: 1, - hasMore: true, - nextCursor: 'next-page', - orderBy: 'updatedAt', - workspaceId: 'workspace-1', - partial: false, - workspaceErrors: [] - } - } - queueFixtures(callMock, okFixture('req_list', listResult)) - await main(['linear', 'list-issues', '--limit', '1'], '/tmp/repo') - expect(vi.mocked(console.log).mock.calls[0][0]).toContain('truncated: showing 1') - expect( - vi.mocked(console.error).mock.calls.some((call) => String(call[0]).includes('more results')) - ).toBe(true) - - vi.mocked(console.log).mockClear() - vi.mocked(console.error).mockClear() - queueFixtures(callMock, okFixture('req_list_json', listResult)) - await main(['linear', 'list-issues', '--limit', '1', '--json'], '/tmp/repo') - const jsonOut = String(vi.mocked(console.log).mock.calls[0][0]) - expect(jsonOut).toContain('"truncated": true') - expect(vi.mocked(console.error)).not.toHaveBeenCalled() - }) - - it('passes verified current-context hints without resolving cwd for remote runtimes', async () => { - process.env.ORCA_TERMINAL_HANDLE = 'term_123' - process.env.ORCA_WORKTREE_ID = 'repo::/srv/app' - process.env.ORCA_PAIRING_CODE = 'orca://pair?payload=bad' - queueFixtures(callMock, okFixture('req_linear', issueResult())) - - await main(['linear', 'issue', '--current', '--comments', '--json'], '/client/repo') - - expect(callMock).toHaveBeenCalledWith( - 'linear.issueContext', - expect.objectContaining({ - input: undefined, - current: true, - include: expect.objectContaining({ comments: true }), - context: { - remote: true, - worktreeId: 'repo::/srv/app', - terminalHandle: 'term_123' - } - }), - { timeoutMs: undefined } - ) - }) - - it('rejects --depth unless children are requested', async () => { - await main(['linear', 'issue', 'ENG-123', '--depth', '3'], '/tmp/repo') - - expect(callMock).not.toHaveBeenCalled() - expect(vi.mocked(console.error).mock.calls[0][0]).toContain( - '--depth requires --children or --full' - ) - expect(process.exitCode).toBe(1) - }) - - it('maps search to agent search RPC with capped limit', async () => { - queueFixtures( - callMock, - okFixture('req_search', { - issues: [], - meta: { query: 'auth', workspaceId: 'all', limit: 50, returned: 0, limitReached: false } - }) - ) - - await main(['linear', 'search', 'auth', '--workspace', 'all', '--limit', '500'], '/tmp/repo') - - expect(callMock).toHaveBeenCalledWith('linear.agentSearchIssues', { - query: 'auth', - limit: 50, - workspaceId: 'all' - }) - }) - - it('maps relation writes to the current-issue perspective', async () => { - queueFixtures(callMock, okFixture('req_relation', relationWriteResult())) - - await main( - [ - 'linear', - 'relation', - 'add', - 'ENG-123', - '--related', - 'ENG-456', - '--type', - 'blocked-by', - '--json' - ], - '/tmp/repo' - ) - - expect(callMock).toHaveBeenCalledWith( - 'linear.issueRelationWrite', - { - input: 'ENG-123', - current: false, - workspaceId: undefined, - relatedInput: 'ENG-456', - relationship: 'blockedBy', - operation: 'add', - context: { remote: false, cwd: '/tmp/repo' } - }, - { timeoutMs: 75_000 } - ) - }) - - it('rejects impossible due dates before dispatch', async () => { - await main(['linear', 'due-date', 'set', 'ENG-123', '--to', '2026-02-30'], '/tmp/repo') - - expect(callMock).not.toHaveBeenCalled() - expect(vi.mocked(console.error).mock.calls[0][0]).toContain('real calendar date') - }) - - it('preserves repeated labels for label updates', async () => { - queueFixtures(callMock, okFixture('req_label', taskUpdateResult('labels'))) - - await main( - ['linear', 'label', 'add', 'ENG-123', '--label', 'Bug', '--label', 'Regression', '--json'], - '/tmp/repo' - ) - - expect(callMock).toHaveBeenCalledWith( - 'linear.issueUpdateTask', - expect.objectContaining({ - input: 'ENG-123', - operation: 'labels', - labelMode: 'add', - labels: ['Bug', 'Regression'] - }), - { timeoutMs: 75_000 } - ) - }) - - it('requires exact write targets for issue writes', async () => { - await main(['linear', 'comment', 'add', '--body', 'done'], '/tmp/repo') - - expect(callMock).not.toHaveBeenCalled() - expect(vi.mocked(console.error).mock.calls[0][0]).toContain( - 'Pass a Linear issue id or --current' - ) - expect(process.exitCode).toBe(1) - }) - - it('rejects --workspace all for writes before dispatch', async () => { - await main( - [ - 'linear', - 'attach', - 'ENG-123', - '--url', - 'https://example.com/review/123', - '--workspace', - 'all' - ], - '/tmp/repo' - ) - - expect(callMock).not.toHaveBeenCalled() - expect(vi.mocked(console.error).mock.calls[0][0]).toContain( - '--workspace all is not valid for Linear writes' - ) - expect(process.exitCode).toBe(1) - }) - - it('reads comment bodies from stdin and passes retry write ids through', async () => { - const stdin = mockStdin(false, ['line one\n', 'line two']) - queueFixtures(callMock, okFixture('req_comment', commentAddResult())) - - try { - await main( - [ - 'linear', - 'comment', - 'add', - '--current', - '--body-file', - '-', - '--reply-to', - 'comment-parent', - '--write-id', - '123e4567-e89b-12d3-a456-426614174000', - '--json' - ], - '/tmp/repo' - ) - } finally { - stdin.restore() - } - - expect(callMock).toHaveBeenCalledWith( - 'linear.issueAddComment', - { - input: undefined, - current: true, - workspaceId: undefined, - body: 'line one\nline two', - replyTo: 'comment-parent', - writeId: '123e4567-e89b-12d3-a456-426614174000', - context: { - remote: false, - cwd: '/tmp/repo' - } - }, - { timeoutMs: 75_000 } - ) - }) - - it('edits a comment from stdin and deletes one through the rm alias', async () => { - const commentId = '9f3c2a10-1111-4222-8333-444455556666' - const stdin = mockStdin(false, ['fixed body']) - queueFixtures( - callMock, - okFixture('req_edit', commentAddResult()), - okFixture('req_delete', commentAddResult()) - ) - - try { - await main(['linear', 'comment', 'edit', commentId, '--body-file', '-'], '/tmp/repo') - } finally { - stdin.restore() - } - await main(['linear', 'comment', 'rm', commentId, '--workspace', 'w', '--json'], '/tmp/repo') - - expect(callMock).toHaveBeenNthCalledWith( - 1, - 'linear.commentEdit', - { commentId, body: 'fixed body', workspaceId: undefined }, - { timeoutMs: 75_000 } - ) - expect(callMock).toHaveBeenNthCalledWith( - 2, - 'linear.commentDelete', - { commentId, workspaceId: 'w' }, - { timeoutMs: 75_000 } - ) - expect(vi.mocked(console.log).mock.calls[0][0]).toBe('Edited comment comment-id on ENG-123.') - }) - - it('rejects malformed write ids before dispatch', async () => { - await main( - [ - 'linear', - 'attach', - 'ENG-123', - '--url', - 'https://example.com/review/123', - '--write-id', - 'not-a-uuid', - '--json' - ], - '/tmp/repo' - ) - - expect(callMock).not.toHaveBeenCalled() - const payload = JSON.parse(String(vi.mocked(console.log).mock.calls[0][0])) as { - error: { code: string } - } - expect(payload.error.code).toBe('linear_invalid_write_id') - }) - - it('maps MCP-style save-issue updates and explicit clears', async () => { - queueFixtures(callMock, okFixture('req_save', createResult())) - - await main( - [ - 'linear', - 'save-issue', - 'ENG-123', - '--title', - 'Updated title', - '--assignee', - 'null', - '--estimate', - 'null', - '--due-date', - 'null', - '--project', - 'null', - '--label', - 'Bug', - '--json' - ], - '/tmp/repo' - ) - - expect(callMock).toHaveBeenCalledWith( - 'linear.saveIssue', - expect.objectContaining({ - input: 'ENG-123', - title: 'Updated title', - assignee: null, - estimate: null, - dueDate: null, - project: null, - labels: ['Bug'] - }), - { timeoutMs: 75_000 } - ) - }) - - it('rejects duplicate body inputs before dispatch', async () => { - await main( - ['linear', 'create', '--title', 'Bug', '--body', 'one', '--body-file', 'body.md'], - '/tmp/repo' - ) - - expect(callMock).not.toHaveBeenCalled() - expect(vi.mocked(console.error).mock.calls[0][0]).toContain('Use either --body or --body-file') - }) -}) - -function issueResult(): unknown { - return { - issue: { - id: 'issue-id', - identifier: 'ENG-123', - title: 'Fix auth', - url: 'https://linear.app/acme/issue/ENG-123', - state: { name: 'Todo' }, - team: { name: 'Engineering' }, - labels: [] - }, - meta: { - requested: { - current: false, - include: { - comments: false, - children: false, - attachments: false, - relations: false, - activity: false - }, - depth: 2 - }, - resolved: { - id: 'issue-id', - identifier: 'ENG-123', - workspaceId: 'workspace-1', - workspaceName: 'Acme' - }, - partial: false, - includeErrors: [], - sections: {} - } - } -} - -function commentAddResult(): unknown { - return { - comment: { id: 'comment-id', url: null, parentId: 'comment-parent' }, - issue: { id: 'issue-id', identifier: 'ENG-123', url: 'https://linear.app/acme/issue/ENG-123' }, - meta: { - workspaceId: 'workspace-1', - bodyChars: 17, - writeId: '123e4567-e89b-12d3-a456-426614174000', - deduplicated: false - } - } -} - -function createResult(): unknown { - return { - issue: { - id: 'issue-child', - identifier: 'ENG-456', - title: 'Follow-up bug', - url: 'https://linear.app/acme/issue/ENG-456', - team: { id: 'team-eng', key: 'ENG', name: 'Engineering' }, - state: { id: 'state-triage', name: 'Triage' }, - parent: { id: 'issue-id', identifier: 'ENG-123' } - }, - meta: { - workspaceId: 'workspace-1', - writeId: '123e4567-e89b-12d3-a456-426614174000', - deduplicated: false - } - } -} - -function taskUpdateResult(operation: string): unknown { - return { - issue: { id: 'issue-id', identifier: 'ENG-123', url: 'https://linear.app/acme/issue/ENG-123' }, - operation, - previous: {}, - current: {}, - meta: { workspaceId: 'workspace-1', alreadySet: false } - } -} - -function relationWriteResult(): unknown { - return { - issue: { - id: 'issue-id', - identifier: 'ENG-123', - title: 'Current', - url: 'https://linear.app/acme/issue/ENG-123' - }, - relatedIssue: { - id: 'related-id', - identifier: 'ENG-456', - title: 'Related', - url: 'https://linear.app/acme/issue/ENG-456' - }, - relation: { - id: 'relation-id', - type: 'blocks', - direction: 'inbound', - relationship: 'blockedBy' - }, - operation: 'add', - meta: { workspaceId: 'workspace-1', alreadySet: false } - } -} - -function mockStdin(isTTY: boolean, chunks: string[]): { restore: () => void } { - const stdin = process.stdin - const previousIsTTY = stdin.isTTY - const previousAsyncIterator = stdin[Symbol.asyncIterator] - Object.defineProperty(stdin, 'isTTY', { - configurable: true, - value: isTTY - }) - ;(stdin as unknown as Record)[Symbol.asyncIterator] = async function* () { - for (const chunk of chunks) { - yield chunk - } - return undefined - } - return { - restore: () => { - Object.defineProperty(stdin, 'isTTY', { - configurable: true, - value: previousIsTTY - }) - if (previousAsyncIterator) { - ;(stdin as unknown as Record)[Symbol.asyncIterator] = previousAsyncIterator - } else { - Reflect.deleteProperty(stdin, Symbol.asyncIterator) - } - } - } -} diff --git a/src/cli/handlers/managed-server-reconnect.ts b/src/cli/handlers/managed-server-reconnect.ts index 94ae2565130..4007783aa3d 100644 --- a/src/cli/handlers/managed-server-reconnect.ts +++ b/src/cli/handlers/managed-server-reconnect.ts @@ -1,7 +1,7 @@ // Updates can close this connection mid-call; report the outcome from status after the runtime returns. import type { OrcadManagedRuntimeStatus } from '../../shared/orcad-managed-runtime' import type { HandlerContext } from '../dispatch' -import { printResult } from '../format' +import { printResult } from '../command-result-output' import { RuntimeClientError, type RuntimeRpcSuccess } from '../runtime-client' const STATUS_ATTEMPTS = 15 diff --git a/src/cli/handlers/managed-server.ts b/src/cli/handlers/managed-server.ts index 579239d02ea..9be9aea327a 100644 --- a/src/cli/handlers/managed-server.ts +++ b/src/cli/handlers/managed-server.ts @@ -12,7 +12,7 @@ import { MANAGED_SERVER_RUNTIME_CAPABILITY } from '../../shared/protocol-version import type { RuntimeStatus } from '../../shared/runtime-session-contracts' import type { CommandHandler, HandlerContext } from '../dispatch' import { getRequiredStringFlag } from '../flags' -import { printResult } from '../format' +import { printResult } from '../command-result-output' import { RuntimeClientError, type RuntimeRpcSuccess } from '../runtime-client' import { formatManagedServerStatus } from './managed-server-format' import { reportAfterClosedConnection } from './managed-server-reconnect' diff --git a/src/cli/handlers/orchestration-caller-identity-cli.test.ts b/src/cli/handlers/orchestration-caller-identity-cli.test.ts index 03202f7d6af..776204c17bf 100644 --- a/src/cli/handlers/orchestration-caller-identity-cli.test.ts +++ b/src/cli/handlers/orchestration-caller-identity-cli.test.ts @@ -4,24 +4,17 @@ const callMock = vi.fn() const getTerminalHandleMock = vi.hoisted(() => vi.fn()) const originalTerminalHandle = process.env.ORCA_TERMINAL_HANDLE const originalPaneKey = process.env.ORCA_PANE_KEY -vi.mock('../format', () => ({ printResult: vi.fn() })) +vi.mock('../command-result-output', () => ({ printResult: vi.fn() })) vi.mock('../selectors', () => ({ getTerminalHandle: getTerminalHandleMock })) import { ORCHESTRATION_HANDLERS } from './orchestration' import { RuntimeClientError } from '../runtime-client' -import { printResult } from '../format' +import { printResult } from '../command-result-output' function staleHandleError(): RuntimeClientError { return new RuntimeClientError('terminal_handle_stale', 'terminal_handle_stale') } -function stubStaleHandleRemint(liveHandle: string, downstream: unknown): void { - callMock - .mockResolvedValueOnce(notLiveIdentity()) - .mockResolvedValueOnce({ result: { terminal: { handle: liveHandle } } }) - .mockResolvedValueOnce(downstream) -} - function stubStaleHandleRemintFailure(error: RuntimeClientError): void { callMock.mockResolvedValueOnce(notLiveIdentity()).mockRejectedValueOnce(error) } @@ -30,10 +23,6 @@ function notLiveIdentity(): { result: { identity: { live: false } } } { return { result: { identity: { live: false } } } } -function liveIdentity(handle: string): { result: { identity: { handle: string; live: true } } } { - return { result: { identity: { handle, live: true } } } -} - afterEach(() => { getTerminalHandleMock.mockReset() if (originalTerminalHandle === undefined) { @@ -66,15 +55,6 @@ describe('orchestration dispatch coordinator handle', () => { json } as never) - const invokeDispatchShow = (flags: Map, json = true) => - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This handler uses only client.call, supplied by the fixture; no RuntimeClient lifecycle methods are accessed. - ORCHESTRATION_HANDLERS['orchestration dispatch-show']({ - flags, - client: { call: callMock }, - cwd: '/tmp/repo', - json - } as never) - const invokeRun = (flags: Map) => ORCHESTRATION_HANDLERS['orchestration coordinator-start']({ flags, @@ -83,92 +63,6 @@ describe('orchestration dispatch coordinator handle', () => { json: true } as never) - it('allows a dry run without a recipient and returns only its preamble', async () => { - callMock.mockResolvedValue({ - result: { dispatch: null, dryRun: true, preamble: 'preview preamble' } - }) - - await invokeDispatch( - new Map([ - ['task', 'task_1'], - ['from', 'terminal_coordinator'], - ['dry-run', true], - ['return-preamble', true], - ['full', true] - ]), - false - ) - - expect(callMock).toHaveBeenCalledWith('orchestration.dispatch', { - task: 'task_1', - run: undefined, - to: undefined, - from: 'terminal_coordinator', - inject: undefined, - dryRun: true, - returnPreamble: true, - devMode: false - }) - expect(renderedValue({ dispatch: null, dryRun: true, preamble: 'preview preamble' })).toBe( - 'preview preamble' - ) - }) - - it('does not resolve coordinator identity for a non-preamble dispatch lookup', async () => { - callMock.mockResolvedValue({ result: { dispatch: null } }) - - await invokeDispatchShow( - new Map([ - ['task', 'task_1'], - ['full', true] - ]), - false - ) - - expect(callMock).toHaveBeenCalledWith('orchestration.dispatchShow', { - task: 'task_1', - preamble: undefined, - from: undefined, - devMode: false - }) - expect(getTerminalHandleMock).not.toHaveBeenCalled() - expect(renderedValue({ dispatch: null })).toBe('No dispatch context found.') - }) - - it('remints a stale coordinator env handle from the caller pane key', async () => { - process.env.ORCA_TERMINAL_HANDLE = 'term_stale_coord' - process.env.ORCA_PANE_KEY = 'tab_coord:leaf_coord' - stubStaleHandleRemint('term_live_coord', { - result: { dispatch: { id: 'ctx_1', task_id: 'task_1', status: 'dispatched' } } - }) - getTerminalHandleMock.mockRejectedValue(new Error('active terminal fallback is unsafe')) - - await invokeDispatch( - new Map([ - ['task', 'task_1'], - ['to', 'term_worker'], - ['inject', true] - ]) - ) - - expect(callMock).toHaveBeenNthCalledWith(1, 'terminal.resolveIdentity', { - terminal: 'term_stale_coord' - }) - expect(callMock).toHaveBeenNthCalledWith(2, 'terminal.resolvePane', { - paneKey: 'tab_coord:leaf_coord' - }) - expect(getTerminalHandleMock).not.toHaveBeenCalled() - expect(callMock).toHaveBeenNthCalledWith(3, 'orchestration.dispatch', { - task: 'task_1', - to: 'term_worker', - from: 'term_live_coord', - inject: true, - dryRun: undefined, - returnPreamble: undefined, - devMode: false - }) - }) - it('rejects stale coordinator env handles when the caller pane cannot be proven', async () => { process.env.ORCA_TERMINAL_HANDLE = 'term_stale_coord' callMock.mockRejectedValueOnce(staleHandleError()) @@ -218,35 +112,6 @@ describe('orchestration dispatch coordinator handle', () => { expect(getTerminalHandleMock).not.toHaveBeenCalled() }) - it('uses a live coordinator handle for dispatch-show preamble previews', async () => { - process.env.ORCA_TERMINAL_HANDLE = 'term_stale_coord' - process.env.ORCA_PANE_KEY = 'tab_coord:leaf_coord' - stubStaleHandleRemint('term_live_coord', { - result: { dispatch: null, preamble: 'preamble' } - }) - getTerminalHandleMock.mockRejectedValue(new Error('active terminal fallback is unsafe')) - - await invokeDispatchShow( - new Map([ - ['task', 'task_1'], - ['preamble', true] - ]) - ) - - expect(callMock).toHaveBeenNthCalledWith(1, 'terminal.resolveIdentity', { - terminal: 'term_stale_coord' - }) - expect(callMock).toHaveBeenNthCalledWith(2, 'terminal.resolvePane', { - paneKey: 'tab_coord:leaf_coord' - }) - expect(callMock).toHaveBeenNthCalledWith(3, 'orchestration.dispatchShow', { - task: 'task_1', - preamble: true, - from: 'term_live_coord', - devMode: false - }) - }) - it('retires the legacy coordinator command without runtime effects', async () => { await expect( invokeRun(new Map([['spec', 'run the plan']])) @@ -278,28 +143,6 @@ describe('orchestration task-create caller handle', () => { json: true } as never) - it('records a live env terminal handle as task creator', async () => { - process.env.ORCA_TERMINAL_HANDLE = 'term_creator' - callMock - .mockResolvedValueOnce(liveIdentity('term_creator')) - .mockResolvedValueOnce({ result: { task: { id: 'task_1', status: 'ready' } } }) - - await invokeTaskCreate(new Map([['spec', 'do work']])) - - expect(callMock).toHaveBeenNthCalledWith(1, 'terminal.resolveIdentity', { - terminal: 'term_creator' - }) - expect(callMock).toHaveBeenNthCalledWith(2, 'orchestration.taskCreate', { - spec: 'do work', - taskTitle: undefined, - displayName: undefined, - deps: undefined, - parent: undefined, - run: undefined, - callerTerminalHandle: 'term_creator' - }) - }) - it('fails closed when a stale task creator handle cannot be reminted', async () => { process.env.ORCA_TERMINAL_HANDLE = 'term_stale' callMock.mockRejectedValueOnce(staleHandleError()) @@ -315,40 +158,4 @@ describe('orchestration task-create caller handle', () => { expect(getTerminalHandleMock).not.toHaveBeenCalled() expect(callMock).toHaveBeenCalledTimes(1) }) - - it('remints a stale task creator env handle from the caller pane key', async () => { - process.env.ORCA_TERMINAL_HANDLE = 'term_stale' - process.env.ORCA_PANE_KEY = 'tab_creator:leaf_creator' - stubStaleHandleRemint('term_live', { - result: { task: { id: 'task_1', status: 'ready' } } - }) - getTerminalHandleMock.mockRejectedValue(new Error('active terminal fallback is unsafe')) - - await invokeTaskCreate(new Map([['spec', 'do work']])) - - expect(callMock).toHaveBeenNthCalledWith(1, 'terminal.resolveIdentity', { - terminal: 'term_stale' - }) - expect(callMock).toHaveBeenNthCalledWith(2, 'terminal.resolvePane', { - paneKey: 'tab_creator:leaf_creator' - }) - expect(getTerminalHandleMock).not.toHaveBeenCalled() - expect(callMock).toHaveBeenNthCalledWith(3, 'orchestration.taskCreate', { - spec: 'do work', - taskTitle: undefined, - displayName: undefined, - deps: undefined, - parent: undefined, - run: undefined, - callerTerminalHandle: 'term_live' - }) - }) }) - -function renderedValue(value: unknown): string { - const formatter = vi.mocked(printResult).mock.calls[0]?.[2] - if (!formatter) { - throw new Error('Expected a plain output formatter') - } - return formatter(value) -} diff --git a/src/cli/handlers/orchestration-check-identity.test.ts b/src/cli/handlers/orchestration-check-identity.test.ts index f2b806ec4f9..11ffec64684 100644 --- a/src/cli/handlers/orchestration-check-identity.test.ts +++ b/src/cli/handlers/orchestration-check-identity.test.ts @@ -6,7 +6,7 @@ const originalTerminalHandle = process.env.ORCA_TERMINAL_HANDLE const originalPaneKey = process.env.ORCA_PANE_KEY const printResultMock = vi.hoisted(() => vi.fn()) -vi.mock('../format', () => ({ printResult: printResultMock })) +vi.mock('../command-result-output', () => ({ printResult: printResultMock })) vi.mock('../selectors', () => ({ getTerminalHandle: getTerminalHandleMock })) import { ORCHESTRATION_HANDLERS } from './orchestration' @@ -41,24 +41,6 @@ describe('orchestration check identity', () => { json } as never) - it('carries the caller pane key when the environment handle may be stale', async () => { - process.env.ORCA_TERMINAL_HANDLE = 'term_stale_coord' - process.env.ORCA_PANE_KEY = 'tab_coord:leaf_coord' - getTerminalHandleMock.mockRejectedValue(new Error('active terminal fallback is unsafe')) - - await invokeCheck(new Map([['wait', true]])) - - expect(getTerminalHandleMock).not.toHaveBeenCalled() - expect(callMock).toHaveBeenCalledWith( - 'orchestration.check', - expect.objectContaining({ - terminal: 'term_stale_coord', - terminalPaneKey: 'tab_coord:leaf_coord', - wait: true - }) - ) - }) - it('rejects an empty --terminal instead of consuming the ambient mailbox', async () => { process.env.ORCA_TERMINAL_HANDLE = 'term_coord' @@ -67,19 +49,4 @@ describe('orchestration check identity', () => { ).rejects.toMatchObject({ code: 'invalid_argument' }) expect(callMock).not.toHaveBeenCalled() }) - - it('keeps an explicit legacy terminal handle scoped to that handle', async () => { - process.env.ORCA_TERMINAL_HANDLE = 'term_stale_env' - - await invokeCheck(new Map([['terminal', 'term_legacy_worker']])) - - expect(callMock).toHaveBeenCalledTimes(1) - expect(callMock).toHaveBeenCalledWith( - 'orchestration.check', - expect.objectContaining({ - terminal: 'term_legacy_worker', - terminalPaneKey: undefined - }) - ) - }) }) diff --git a/src/cli/handlers/orchestration-federated-legacy-settlement.test.ts b/src/cli/handlers/orchestration-federated-legacy-settlement.test.ts index 5697da608eb..ec1360d2e17 100644 --- a/src/cli/handlers/orchestration-federated-legacy-settlement.test.ts +++ b/src/cli/handlers/orchestration-federated-legacy-settlement.test.ts @@ -2,7 +2,7 @@ import { afterEach, expect, it, vi } from 'vitest' const callMock = vi.fn() const printResultMock = vi.hoisted(() => vi.fn()) -vi.mock('../format', () => ({ printResult: printResultMock })) +vi.mock('../command-result-output', () => ({ printResult: printResultMock })) vi.mock('../selectors', () => ({ getTerminalHandle: vi.fn() })) import { ORCHESTRATION_HANDLERS } from './orchestration' @@ -13,57 +13,6 @@ afterEach(() => { printResultMock.mockReset() }) -it('accepts an explicitly attested legacy worker-server settlement', async () => { - const result = { - relay: { - messageId: 'relay_legacy_done', - sequence: 1, - dispatchId: 'ctx_legacy', - destination: 'run_home', - accepted: true - }, - lifecycle: { - action: 'completed', - authority: 'worker_server_legacy' - } - } - callMock.mockResolvedValueOnce({ result }) - - await ORCHESTRATION_HANDLERS['orchestration send']( - orchestrationTestContext( - callMock, - new Map([ - ['full', true], - ['from', 'term_worker'], - ['subject', 'done'], - ['type', 'worker_done'], - ['task-id', 'task_legacy'], - ['dispatch-id', 'ctx_legacy'], - ['outcome', 'succeeded'] - ]), - true - ) - ) - - expect(callMock).toHaveBeenCalledOnce() - expect(callMock).toHaveBeenCalledWith( - 'orchestration.send', - expect.objectContaining({ - from: 'term_worker', - subject: 'done', - type: 'worker_done', - payload: JSON.stringify({ - taskId: 'task_legacy', - dispatchId: 'ctx_legacy', - outcome: 'succeeded' - }), - waitForLifecycleSettlement: true - }), - { orchestrationRequestId: expect.any(String) } - ) - expect(printResultMock).toHaveBeenCalledWith({ result }, true, expect.any(Function)) -}) - it('rejects an unattested relay settlement', async () => { callMock.mockResolvedValueOnce({ result: { diff --git a/src/cli/handlers/orchestration-legacy-read-only.test.ts b/src/cli/handlers/orchestration-legacy-read-only.test.ts index a6537fb1542..fc9738bea40 100644 --- a/src/cli/handlers/orchestration-legacy-read-only.test.ts +++ b/src/cli/handlers/orchestration-legacy-read-only.test.ts @@ -2,10 +2,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' const callMock = vi.fn() -vi.mock('../format', () => ({ printResult: vi.fn() })) +vi.mock('../command-result-output', () => ({ printResult: vi.fn() })) vi.mock('../selectors', () => ({ getTerminalHandle: vi.fn() })) -import { printResult } from '../format' +import { printResult } from '../command-result-output' import { ORCHESTRATION_HANDLERS } from './orchestration' import { orchestrationTestContext } from './orchestration-handler-test-context' @@ -161,35 +161,4 @@ describe('legacy orchestration CLI inspection', () => { ).toEqual(['[Reply: orca orchestration reply --id msg_current --body "..."]']) expect(response.result.formatted).not.toContain('--from run:run_current') }) - - it('labels legacy rows in full inbox output without hiding their body', async () => { - const result = { - messages: [ - { - id: 'msg_legacy', - run_id: 'run_legacy_local', - from_handle: 'term_worker', - to_handle: 'term_coord', - subject: 'progress', - body: 'Tests are running.' - } - ], - count: 1 - } - callMock.mockResolvedValue({ result }) - - await ORCHESTRATION_HANDLERS['orchestration inbox']( - orchestrationTestContext( - callMock, - new Map([['full', true]]), - false, - '/repo' - ) - ) - - const formatter = vi.mocked(printResult).mock.calls[0]?.[2] - const output = formatter?.(result) - expect(output).toContain('msg_legacy [legacy, read-only]') - expect(output).toContain('Tests are running.') - }) }) diff --git a/src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts b/src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts index a7b1766437e..ba0452a890b 100644 --- a/src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts +++ b/src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts @@ -1,5 +1,5 @@ import { afterEach, expect, it, vi } from 'vitest' -import { reportCliError } from '../format' +import { reportCliError } from '../cli-error' import { ORCHESTRATION_HANDLERS } from './orchestration' afterEach(() => { diff --git a/src/cli/handlers/orchestration-lifecycle-rejection.test.ts b/src/cli/handlers/orchestration-lifecycle-rejection.test.ts index a18d2abd157..6efb7d2cc50 100644 --- a/src/cli/handlers/orchestration-lifecycle-rejection.test.ts +++ b/src/cli/handlers/orchestration-lifecycle-rejection.test.ts @@ -2,10 +2,10 @@ import { afterEach, expect, it, vi } from 'vitest' const callMock = vi.fn() const originalExitCode = process.exitCode -vi.mock('../format', () => ({ printResult: vi.fn() })) +vi.mock('../command-result-output', () => ({ printResult: vi.fn() })) vi.mock('../selectors', () => ({ getTerminalHandle: vi.fn() })) -import { printResult } from '../format' +import { printResult } from '../command-result-output' import { ORCHESTRATION_HANDLERS } from './orchestration' afterEach(() => { @@ -84,28 +84,6 @@ it('raises a Run-home relay rejection for the CLI error boundary', async () => { expect(printResult).not.toHaveBeenCalled() }) -it('accepts an explicit current settlement without a compatibility read', async () => { - callMock.mockResolvedValueOnce({ - result: { message: { id: 'msg_done' }, lifecycle: { action: 'completed' } } - }) - - await ORCHESTRATION_HANDLERS['orchestration send']({ - flags: new Map([ - ['from', 'term_worker'], - ['subject', 'done'], - ['type', 'worker_done'], - ['task-id', 'task_1'], - ['dispatch-id', 'ctx_1'], - ['outcome', 'succeeded'] - ]), - client: { call: callMock }, - cwd: '/tmp/repo', - json: true - } as never) - - expect(callMock).toHaveBeenCalledOnce() -}) - it('fails closed when an older runtime leaves worker_done dispatched without a verdict', async () => { callMock .mockResolvedValueOnce({ @@ -200,129 +178,6 @@ it('preserves the worker_done mutation identity when post-verification fails', a }) }) -it('accepts a legacy response only after the authoritative dispatch is terminal', async () => { - callMock - .mockResolvedValueOnce({ - result: { message: { id: 'msg_legacy_completed', run_id: 'run_1' } } - }) - .mockResolvedValueOnce({ - result: { dispatch: { id: 'ctx_1', status: 'completed' } } - }) - .mockResolvedValueOnce({ - result: { - tasks: [ - { - id: 'task_1', - status: 'completed', - result: JSON.stringify({ - provenance: 'worker_report', - messageId: 'msg_legacy_completed', - outcome: 'succeeded' - }) - } - ] - } - }) - - await ORCHESTRATION_HANDLERS['orchestration send']({ - flags: new Map([ - ['from', 'term_worker'], - ['subject', 'done'], - ['type', 'worker_done'], - ['task-id', 'task_1'], - ['dispatch-id', 'ctx_1'], - ['outcome', 'succeeded'] - ]), - client: { call: callMock }, - cwd: '/tmp/repo', - json: true - } as never) - - expect(callMock).toHaveBeenCalledTimes(3) - expect(callMock).toHaveBeenNthCalledWith(2, 'orchestration.dispatchShow', { task: 'task_1' }) -}) - -it('accepts a legacy failed report only after the authoritative dispatch failed', async () => { - callMock - .mockResolvedValueOnce({ - result: { message: { id: 'msg_legacy_failed', run_id: 'run_1' } } - }) - .mockResolvedValueOnce({ result: { dispatch: { id: 'ctx_1', status: 'failed' } } }) - .mockResolvedValueOnce({ - result: { - tasks: [ - { - id: 'task_1', - status: 'failed', - result: JSON.stringify({ - provenance: 'worker_report', - messageId: 'msg_legacy_failed', - outcome: 'failed' - }) - } - ] - } - }) - - await ORCHESTRATION_HANDLERS['orchestration send']({ - flags: new Map([ - ['from', 'term_worker'], - ['subject', 'failed'], - ['type', 'worker_done'], - ['task-id', 'task_1'], - ['dispatch-id', 'ctx_1'], - ['outcome', 'failed'] - ]), - client: { call: callMock }, - cwd: '/tmp/repo', - json: true - } as never) - - expect(callMock).toHaveBeenCalledTimes(3) -}) - -it('accepts an idempotent retry whose first report already settled', async () => { - callMock - .mockResolvedValueOnce({ - result: { - message: { id: 'msg_retry', run_id: 'run_1', from_handle: 'term_worker' } - } - }) - .mockResolvedValueOnce({ result: { dispatch: { id: 'ctx_1', status: 'completed' } } }) - .mockResolvedValueOnce({ - result: { - tasks: [ - { - id: 'task_1', - status: 'completed', - result: JSON.stringify({ - provenance: 'worker_report', - messageId: 'msg_first', - reportedBy: 'term_worker', - outcome: 'succeeded' - }) - } - ] - } - }) - - await ORCHESTRATION_HANDLERS['orchestration send']({ - flags: new Map([ - ['from', 'term_worker'], - ['subject', 'done'], - ['type', 'worker_done'], - ['task-id', 'task_1'], - ['dispatch-id', 'ctx_1'], - ['outcome', 'succeeded'] - ]), - client: { call: callMock }, - cwd: '/tmp/repo', - json: true - } as never) - - expect(callMock).toHaveBeenCalledTimes(3) -}) - it('rejects an unrelated failed Dispatch that left its Task blocked', async () => { callMock .mockResolvedValueOnce({ diff --git a/src/cli/handlers/orchestration-task-list-brief.test.ts b/src/cli/handlers/orchestration-task-list-brief.test.ts index 4aee06fab3a..e727e250588 100644 --- a/src/cli/handlers/orchestration-task-list-brief.test.ts +++ b/src/cli/handlers/orchestration-task-list-brief.test.ts @@ -2,10 +2,10 @@ import { afterEach, describe, expect, it, vi } from 'vitest' const callMock = vi.fn() -vi.mock('../format', () => ({ printResult: vi.fn() })) +vi.mock('../command-result-output', () => ({ printResult: vi.fn() })) import { ORCHESTRATION_HANDLERS } from './orchestration' -import { printResult } from '../format' +import { printResult } from '../command-result-output' import { okFixture } from '../test-fixtures' import { RuntimeClient } from '../runtime-client' @@ -57,17 +57,4 @@ describe('orchestration task-list brief output', () => { expect(response).toHaveProperty('result.tasks.0.spec', `First line ${'detail '.repeat(21)}d…`) expect(response).toHaveProperty('result.tasks.0.spec_truncated', true) }) - - it('passes server-abbreviated rows through untouched', async () => { - const serverTasks = [ - { id: 'task_1', spec: 'already brief…', status: 'ready', spec_truncated: true } - ] - const serverResponse = okFixture('req_tasks', { tasks: serverTasks, count: 1 }) - callMock.mockReset().mockResolvedValue(serverResponse) - - const response = await runTaskListBrief() - - // Re-abbreviating would reset spec_truncated because the already-truncated text fits the cap. - expect(response).toHaveProperty('result.tasks', serverTasks) - }) }) diff --git a/src/cli/handlers/orchestration-worker-cli.test.ts b/src/cli/handlers/orchestration-worker-cli.test.ts index acaef5fb0bf..b39b4d5985f 100644 --- a/src/cli/handlers/orchestration-worker-cli.test.ts +++ b/src/cli/handlers/orchestration-worker-cli.test.ts @@ -2,14 +2,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const callMock = vi.fn() const originalExitCode = process.exitCode -vi.mock('../format', async (importOriginal) => { +vi.mock('../command-result-output', async (importOriginal) => { const original = await importOriginal<{ printResult: typeof printResult }>() return { printResult: vi.fn(original.printResult) } }) vi.mock('../selectors', () => ({ getTerminalHandle: vi.fn() })) import { ORCHESTRATION_HANDLERS } from './orchestration' -import { printResult } from '../format' +import { printResult } from '../command-result-output' import { RuntimeClient } from '../runtime-client' diff --git a/src/cli/handlers/orchestration.test.ts b/src/cli/handlers/orchestration.test.ts index a22e1916003..4f95228896f 100644 --- a/src/cli/handlers/orchestration.test.ts +++ b/src/cli/handlers/orchestration.test.ts @@ -4,12 +4,12 @@ const callMock = vi.fn() const getTerminalHandleMock = vi.hoisted(() => vi.fn()) const originalExitCode = process.exitCode -vi.mock('../format', () => ({ printResult: vi.fn() })) +vi.mock('../command-result-output', () => ({ printResult: vi.fn() })) vi.mock('../selectors', () => ({ getTerminalHandle: getTerminalHandleMock })) import { ORCHESTRATION_HANDLERS } from './orchestration' -import { printResult } from '../format' +import { printResult } from '../command-result-output' import { okFixture } from '../test-fixtures' beforeEach(() => { diff --git a/src/cli/handlers/orchestration/agent-view.ts b/src/cli/handlers/orchestration/agent-view.ts index d8535c9c2ec..aeef0db4a3f 100644 --- a/src/cli/handlers/orchestration/agent-view.ts +++ b/src/cli/handlers/orchestration/agent-view.ts @@ -1,5 +1,5 @@ import type { HandlerContext } from '../../dispatch' -import { printResult } from '../../format' +import { printResult } from '../../command-result-output' import { formatOrchestrationErrorLine } from '../../cli-error' import { renderCommand } from '../../orchestration-mutation-recovery' import { resolveOrchestrationCliExecutable } from '../../runtime/orchestration-recovery-command' diff --git a/src/cli/handlers/orchestration/gate-handlers.ts b/src/cli/handlers/orchestration/gate-handlers.ts index 9d264c2b804..2745e7a2e55 100644 --- a/src/cli/handlers/orchestration/gate-handlers.ts +++ b/src/cli/handlers/orchestration/gate-handlers.ts @@ -1,5 +1,5 @@ import type { CommandHandler } from '../../dispatch' -import { printResult } from '../../format' +import { printResult } from '../../command-result-output' import { printOrchestrationResult } from './agent-view' import { getOptionalJsonFlag, getOptionalStringFlag, getRequiredStringFlag } from '../../flags' import { callOrchestrationMutation } from './mutation-request' diff --git a/src/cli/handlers/orchestration/message-check-handler.ts b/src/cli/handlers/orchestration/message-check-handler.ts index aa3869fa383..f46543bfea5 100644 --- a/src/cli/handlers/orchestration/message-check-handler.ts +++ b/src/cli/handlers/orchestration/message-check-handler.ts @@ -1,6 +1,6 @@ import type { CommandHandler } from '../../dispatch' import { refuseAgentServerRoute } from './agent-server-route' -import { printResult } from '../../format' +import { printResult } from '../../command-result-output' import { withReceiptNext } from './receipt-next-text' import { printOrchestrationResult } from './agent-view' import { checkView } from './message-agent-views' diff --git a/src/cli/handlers/orchestration/message-inbox-handlers.ts b/src/cli/handlers/orchestration/message-inbox-handlers.ts index 66ba2a23a13..69b29a47a8c 100644 --- a/src/cli/handlers/orchestration/message-inbox-handlers.ts +++ b/src/cli/handlers/orchestration/message-inbox-handlers.ts @@ -1,5 +1,5 @@ import type { CommandHandler } from '../../dispatch' -import { printResult } from '../../format' +import { printResult } from '../../command-result-output' import { getOptionalPositiveIntegerFlag, getOptionalStringFlag, diff --git a/src/cli/handlers/orchestration/message-send-handler.ts b/src/cli/handlers/orchestration/message-send-handler.ts index 3fb76f51562..08d6129be96 100644 --- a/src/cli/handlers/orchestration/message-send-handler.ts +++ b/src/cli/handlers/orchestration/message-send-handler.ts @@ -1,5 +1,5 @@ import type { CommandHandler } from '../../dispatch' -import { printResult } from '../../format' +import { printResult } from '../../command-result-output' import { printOrchestrationResult } from './agent-view' import { withReceiptNext } from './receipt-next-text' import { formatWorkerStart } from './worker-output' diff --git a/src/cli/handlers/orchestration/question-handler.ts b/src/cli/handlers/orchestration/question-handler.ts index c54aa32f7da..3c7e92f98bb 100644 --- a/src/cli/handlers/orchestration/question-handler.ts +++ b/src/cli/handlers/orchestration/question-handler.ts @@ -1,6 +1,6 @@ import type { CommandHandler } from '../../dispatch' import { getOptionalStringFlag } from '../../flags' -import { printResult } from '../../format' +import { printResult } from '../../command-result-output' import { renderCommand } from '../../orchestration-mutation-recovery' import { RuntimeClientError, type RuntimeClient } from '../../runtime-client' import type { RuntimeStatus } from '../../../shared/runtime-types' diff --git a/src/cli/handlers/orchestration/run-handlers.ts b/src/cli/handlers/orchestration/run-handlers.ts index f2a1e14961f..0f39760b493 100644 --- a/src/cli/handlers/orchestration/run-handlers.ts +++ b/src/cli/handlers/orchestration/run-handlers.ts @@ -1,6 +1,6 @@ import { abbreviateOrchestrationText } from '../../../shared/orchestration/orchestration-task-summary' import type { CommandHandler } from '../../dispatch' -import { printResult } from '../../format' +import { printResult } from '../../command-result-output' import { printOrchestrationResult } from './agent-view' import { getOptionalPositiveIntegerFlag, diff --git a/src/cli/handlers/orchestration/task-handlers.ts b/src/cli/handlers/orchestration/task-handlers.ts index 17b9cbf81cd..708d0ce6da1 100644 --- a/src/cli/handlers/orchestration/task-handlers.ts +++ b/src/cli/handlers/orchestration/task-handlers.ts @@ -1,5 +1,5 @@ import type { CommandHandler } from '../../dispatch' -import { printResult } from '../../format' +import { printResult } from '../../command-result-output' import { printOrchestrationResult } from './agent-view' import { TASK_LIST_VIEW, TASK_RECEIPT_VIEW, type TaskListResult } from './task-agent-views' import { getOptionalStringFlag, getRequiredStringFlag } from '../../flags' diff --git a/src/cli/handlers/orchestration/worker-launch-handler.ts b/src/cli/handlers/orchestration/worker-launch-handler.ts index d26ab6a669a..f81c1bbdf63 100644 --- a/src/cli/handlers/orchestration/worker-launch-handler.ts +++ b/src/cli/handlers/orchestration/worker-launch-handler.ts @@ -1,5 +1,5 @@ import type { CommandHandler } from '../../dispatch' -import { printResult } from '../../format' +import { printResult } from '../../command-result-output' import { withReceiptNext } from './receipt-next-text' import { getOptionalStringFlag, getPresentStringFlag } from '../../flags' import { RuntimeClientError, type RuntimeClient } from '../../runtime-client' diff --git a/src/cli/handlers/orchestration/worker-observation-handlers.ts b/src/cli/handlers/orchestration/worker-observation-handlers.ts index 51c802e6496..e2a5c40c8a0 100644 --- a/src/cli/handlers/orchestration/worker-observation-handlers.ts +++ b/src/cli/handlers/orchestration/worker-observation-handlers.ts @@ -1,5 +1,5 @@ import type { CommandHandler } from '../../dispatch' -import { printResult } from '../../format' +import { printResult } from '../../command-result-output' import { printOrchestrationReceipt, printOrchestrationResult } from './agent-view' import { WORKER_SHOW_VIEW, type WorkerShowResult } from './worker-agent-views' import { diff --git a/src/cli/handlers/orchestration/worker-terminal-handlers.ts b/src/cli/handlers/orchestration/worker-terminal-handlers.ts index 45e2c76d5bc..6f0101e88eb 100644 --- a/src/cli/handlers/orchestration/worker-terminal-handlers.ts +++ b/src/cli/handlers/orchestration/worker-terminal-handlers.ts @@ -1,5 +1,5 @@ import type { CommandHandler } from '../../dispatch' -import { printResult } from '../../format' +import { printResult } from '../../command-result-output' import { printOrchestrationResult } from './agent-view' import { remoteHost, WORKER_LIST_VIEW, type WorkerListResult } from './worker-agent-views' import { diff --git a/src/cli/handlers/pair.ts b/src/cli/handlers/pair.ts index c3296818b8b..e29590af09f 100644 --- a/src/cli/handlers/pair.ts +++ b/src/cli/handlers/pair.ts @@ -1,6 +1,6 @@ import type { CommandHandler } from '../dispatch' import { getOptionalStringFlag } from '../flags' -import { printResult } from '../format' +import { printResult } from '../command-result-output' import { RuntimeClientError } from '../runtime/types' import { PAIRING_CREATE_OFFER_METHOD, diff --git a/src/cli/handlers/profile-state.ts b/src/cli/handlers/profile-state.ts index 2661a39e27d..59281ae4dbd 100644 --- a/src/cli/handlers/profile-state.ts +++ b/src/cli/handlers/profile-state.ts @@ -1,6 +1,6 @@ import { z } from 'zod' import type { CommandHandler } from '../dispatch' -import { printResult } from '../format' +import { printResult } from '../command-result-output' import { rejectRemoteSelectionFlags } from '../remote-selection-flag-rejection' import { getDefaultUserDataPath, diff --git a/src/cli/handlers/project.ts b/src/cli/handlers/project.ts index 798eaa8bdb6..151e085047b 100644 --- a/src/cli/handlers/project.ts +++ b/src/cli/handlers/project.ts @@ -20,9 +20,9 @@ import { formatProjectHostSetupList, formatProjectHostSetupResult, formatProjectHostSetupUpdateResult, - formatProjectList, - printResult -} from '../format' + formatProjectList +} from '../project-format' +import { printResult } from '../command-result-output' import { hostFilterMatchesHostId, parseHostFlag, diff --git a/src/cli/handlers/reference.ts b/src/cli/handlers/reference.ts index 22e66511d15..675c4c996a7 100644 --- a/src/cli/handlers/reference.ts +++ b/src/cli/handlers/reference.ts @@ -15,7 +15,7 @@ import { getRepeatedStringFlag, getRequiredStringFlag } from '../flags' -import { printResult } from '../format' +import { printResult } from '../command-result-output' import { assertReferenceWritesSupported, parseReferenceInputs, diff --git a/src/cli/handlers/repo.ts b/src/cli/handlers/repo.ts index 85926e3ddf3..8d4dff111af 100644 --- a/src/cli/handlers/repo.ts +++ b/src/cli/handlers/repo.ts @@ -1,6 +1,7 @@ import type { RuntimeRepoList, RuntimeRepoSearchRefs } from '../../shared/runtime-types' import type { CommandHandler } from '../dispatch' -import { formatRepoList, formatRepoRefs, formatRepoShow, printResult } from '../format' +import { formatRepoList, formatRepoRefs, formatRepoShow } from '../workspace-format' +import { printResult } from '../command-result-output' import { getOptionalPositiveIntegerFlag, getOptionalRepoKind, diff --git a/src/cli/handlers/serve-restore.ts b/src/cli/handlers/serve-restore.ts index 2a52e93ffba..a0e16775d37 100644 --- a/src/cli/handlers/serve-restore.ts +++ b/src/cli/handlers/serve-restore.ts @@ -1,5 +1,5 @@ import type { CommandHandler } from '../dispatch' -import { printResult } from '../format' +import { printResult } from '../command-result-output' import type { AutomaticWorkMode, AutomaticWorkResumeResult, diff --git a/src/cli/handlers/skill-sharing.ts b/src/cli/handlers/skill-sharing.ts index 8d4cd883fd3..c122e4aa4ba 100644 --- a/src/cli/handlers/skill-sharing.ts +++ b/src/cli/handlers/skill-sharing.ts @@ -12,7 +12,7 @@ import type { SkillCloudOperation } from '../../shared/skill-cloud-contract' import type { SkillDiscoveryResult } from '../../shared/skills' import type { CommandHandler, HandlerContext } from '../dispatch' import { getRepeatedStringFlag } from '../flags' -import { printResult } from '../format' +import { printResult } from '../command-result-output' import { RuntimeClientError, RuntimeRpcFailureError, diff --git a/src/cli/handlers/speech.ts b/src/cli/handlers/speech.ts index c7ca57652b7..d0d7717c06e 100644 --- a/src/cli/handlers/speech.ts +++ b/src/cli/handlers/speech.ts @@ -1,5 +1,5 @@ import type { CommandHandler, HandlerContext } from '../dispatch' -import { printResult } from '../format' +import { printResult } from '../command-result-output' import { RuntimeClientError, type RuntimeRpcSuccess } from '../runtime-client' import { OPENAI_SPEECH_KEY_MAX_LENGTH } from '../../shared/rpc-contract/speech-params' diff --git a/src/cli/handlers/terminal-close.ts b/src/cli/handlers/terminal-close.ts index d11b4e17da8..bb4c005b926 100644 --- a/src/cli/handlers/terminal-close.ts +++ b/src/cli/handlers/terminal-close.ts @@ -3,7 +3,9 @@ import type { RuntimeWorktreeTerminalCloseResult } from '../../shared/runtime-types' import type { CommandHandler } from '../dispatch' -import { formatTerminalClose, reportCliError, printResult } from '../format' +import { formatTerminalClose } from '../terminal-format' +import { reportCliError } from '../cli-error' +import { printResult } from '../command-result-output' import { RuntimeClientError } from '../runtime-client' import { getRequiredWorktreeSelector, getTerminalHandle } from '../selectors' import { describeUnconfirmedCloseStop } from '../../shared/terminal/pty/lifecycle/pty-liveness-verdict' diff --git a/src/cli/handlers/terminal-daemon.ts b/src/cli/handlers/terminal-daemon.ts index 58bb5824fdc..b3f367b1db1 100644 --- a/src/cli/handlers/terminal-daemon.ts +++ b/src/cli/handlers/terminal-daemon.ts @@ -3,7 +3,7 @@ import { describePtyProcessCeiling, type PtyProcessCeilingState } from '../../shared/terminal/pty/native-process/pty-process-ceiling-state' -import { printResult } from '../format' +import { printResult } from '../command-result-output' import { RuntimeClientError } from '../runtime-client' type SeveredDaemonStatus = { diff --git a/src/cli/handlers/terminal-send.ts b/src/cli/handlers/terminal-send.ts index e9d03856b31..36f0db3739d 100644 --- a/src/cli/handlers/terminal-send.ts +++ b/src/cli/handlers/terminal-send.ts @@ -2,7 +2,8 @@ import type { RuntimeTerminalSend } from '../../shared/runtime-types' import '../../shared/protocol-version' import { TERMINAL_PROMPT_DELIVERY_RUNTIME_CAPABILITY } from '../../shared/terminal/runtime-policy/terminal-runtime-capabilities' import type { CommandHandler } from '../dispatch' -import { formatTerminalSend, printResult, terminalSendWarnings } from '../format' +import { formatTerminalSend, terminalSendWarnings } from '../terminal-format' +import { printResult } from '../command-result-output' import { getOptionalPositiveIntegerFlag, getOptionalStringFlag } from '../flags' import { readRetryRequestFlag } from '../retry-request-flag' import { RuntimeClientError } from '../runtime-client' diff --git a/src/cli/handlers/terminal.ts b/src/cli/handlers/terminal.ts index 9dbfafd6312..80c84fb75ac 100644 --- a/src/cli/handlers/terminal.ts +++ b/src/cli/handlers/terminal.ts @@ -20,9 +20,9 @@ import { formatTerminalSetPaneTitle, formatTerminalShow, formatTerminalSplit, - formatTerminalWait, - printResult -} from '../format' + formatTerminalWait +} from '../terminal-format' +import { printResult } from '../command-result-output' import { getOptionalPositiveIntegerFlag, getOptionalStringFlag, diff --git a/src/cli/handlers/worktree-activate.ts b/src/cli/handlers/worktree-activate.ts index b459a2ce613..de2c5eeb211 100644 --- a/src/cli/handlers/worktree-activate.ts +++ b/src/cli/handlers/worktree-activate.ts @@ -1,5 +1,5 @@ import type { CommandHandler } from '../dispatch' -import { printResult } from '../format' +import { printResult } from '../command-result-output' import { getRequiredWorktreeSelector } from '../selectors' import { folderIdOfSelector } from '../../shared/workspace-scope' import { refuseFolderWorkspaceActivation } from './folder-workspace-mutations' diff --git a/src/cli/handlers/worktree-create-agent-launch.ts b/src/cli/handlers/worktree-create-agent-launch.ts index 494ee350859..60118c47a71 100644 --- a/src/cli/handlers/worktree-create-agent-launch.ts +++ b/src/cli/handlers/worktree-create-agent-launch.ts @@ -17,13 +17,14 @@ import { getAgentLaunchCapabilities, type CliAgentLaunch, SURFACE_UNSUPPORTED_MESSAGE -} from '../agent-launch-request' -import { formatWorktreeShow, printResult } from '../format' +} from '../agents/agent-launch-request' +import { formatWorktreeShow } from '../workspace-format' +import { printResult } from '../command-result-output' import { RuntimeClientError, type RuntimeClient } from '../runtime-client' import { printLineageSummary } from './worktree-lineage-summary' import { printHookWarning } from './worktree-removal-warnings' import { withSetupDecisionRecovery } from './worktree-setup-decision-recovery' -import { withCliAgentLaunchRecovery } from '../agent-launch-recovery' +import { withCliAgentLaunchRecovery } from '../agents/agent-launch-recovery' type WorktreeAgentLaunchResult = Pick< RuntimeWorktreeCreateResult, diff --git a/src/cli/handlers/worktree.ts b/src/cli/handlers/worktree.ts index 5f4acb7f34b..dffc06352ec 100644 --- a/src/cli/handlers/worktree.ts +++ b/src/cli/handlers/worktree.ts @@ -11,7 +11,8 @@ import type { CommandHandler } from '../dispatch' import { printHookWarning, printPreservedBranchWarning } from './worktree-removal-warnings' import { requestWorktreeRemoval } from './worktree-removal-request' import { removeIfFolderWorkspace, setIfFolderWorkspace } from './folder-workspace-mutations' -import { formatWorktreeList, formatWorktreePs, formatWorktreeShow, printResult } from '../format' +import { formatWorktreeList, formatWorktreePs, formatWorktreeShow } from '../workspace-format' +import { printResult } from '../command-result-output' import { annotateOmittedHostScope, type WithAnnotatedHostScope @@ -30,7 +31,7 @@ import { resolveCurrentWorktreeSelector } from '../selectors' import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent' -import { parseCliAgent, readCliAgentLaunch } from '../agent-launch-request' +import { parseCliAgent, readCliAgentLaunch } from '../agents/agent-launch-request' import { createWorktreeWithAgent } from './worktree-create-agent-launch' import { printLineageSummary, printSetParentLine } from './worktree-lineage-summary' import { resolveCreateParentFields, resolveSetParentFields } from './worktree-parent-fields' diff --git a/src/cli/hosts/host-format.ts b/src/cli/hosts/host-format.ts new file mode 100644 index 00000000000..e256ba37583 --- /dev/null +++ b/src/cli/hosts/host-format.ts @@ -0,0 +1,47 @@ +export type HostListEntry = { + kind: 'local' | 'ssh' | 'environment' + name: string + id: string + selector: string + platform?: string + machineName?: string + connected?: boolean + connectionStatus?: string +} + +// Explicit host selectors prevent callers from using a display name on the wrong host scope. +export function formatHostList(result: { hosts: HostListEntry[] }): string { + const kindLabel: Record = { + local: 'local', + ssh: 'ssh target', + environment: 'orca server' + } + return result.hosts + .map( + (host) => + `${kindLabel[host.kind].padEnd(11)} ${host.name}${host.machineName ? ` (${host.machineName})` : ''} ${host.platform ?? 'platform unknown'} ${formatHostConnection(host)} -> ${host.selector}` + ) + .join('\n') +} + +/** What one runtime calls itself; `machineName` is absent when the runtime predates the field. */ +export type HostNameResult = { + machineName?: string + platform?: string +} + +export function formatHostName(result: HostNameResult): string { + return `${result.machineName ?? 'unknown'}${result.platform ? ` (${result.platform})` : ''}` +} + +function formatHostConnection(host: HostListEntry): string { + if (host.kind !== 'ssh') { + return '' + } + if (host.connected === undefined) { + return `connection unknown${host.connectionStatus ? ` (${host.connectionStatus})` : ''}` + } + return host.connected + ? `connected${host.connectionStatus ? ` (${host.connectionStatus})` : ''}` + : `not connected${host.connectionStatus ? ` (${host.connectionStatus})` : ''}` +} diff --git a/src/cli/index-agent-launch.test.ts b/src/cli/index-agent-launch.test.ts index 9b320a13096..f60e8a2ff23 100644 --- a/src/cli/index-agent-launch.test.ts +++ b/src/cli/index-agent-launch.test.ts @@ -47,7 +47,7 @@ import { main } from './index' import { RuntimeClientError, RuntimeRpcFailureError } from './runtime-client' import { queueFixtures } from './test-fixtures' import { useWorktreeAwarenessEnvironment } from './index-test-harness' -import { agentLaunchHostFixture } from './agent-launch-test-fixtures' +import { agentLaunchHostFixture } from './agents/agent-launch-test-fixtures' const WORKTREE_ID = 'repo-1::/tmp/repo' const ORIGINAL_EXIT_CODE = process.exitCode diff --git a/src/cli/jira-format.ts b/src/cli/jira/jira-format.ts similarity index 98% rename from src/cli/jira-format.ts rename to src/cli/jira/jira-format.ts index c4d056e159d..ac9f424257d 100644 --- a/src/cli/jira-format.ts +++ b/src/cli/jira/jira-format.ts @@ -7,7 +7,7 @@ import type { JiraIssueType, JiraTransition, JiraUser -} from '../shared/jira/jira-types' +} from '../../shared/jira/jira-types' function issueHeadline(issue: JiraIssue): string { return `${issue.key} ${issue.title}` diff --git a/src/cli/jira-handler-group.ts b/src/cli/jira/jira-handler-group.ts similarity index 81% rename from src/cli/jira-handler-group.ts rename to src/cli/jira/jira-handler-group.ts index 086f74e45b6..be17fbf0c25 100644 --- a/src/cli/jira-handler-group.ts +++ b/src/cli/jira/jira-handler-group.ts @@ -1,4 +1,4 @@ -import type { HandlerGroup } from './handler-group-manifest' +import type { HandlerGroup } from '../handler-group-manifest' export const JIRA_HANDLER_GROUP: HandlerGroup = { name: 'jira', @@ -25,5 +25,5 @@ export const JIRA_HANDLER_GROUP: HandlerGroup = { 'jira label rm', 'jira label set' ], - load: async () => (await import('./handlers/jira.js')).JIRA_HANDLERS + load: async () => (await import('./jira.js')).JIRA_HANDLERS } diff --git a/src/cli/jira-target.ts b/src/cli/jira/jira-target.ts similarity index 84% rename from src/cli/jira-target.ts rename to src/cli/jira/jira-target.ts index 5266393d213..444e62eee80 100644 --- a/src/cli/jira-target.ts +++ b/src/cli/jira/jira-target.ts @@ -1,14 +1,14 @@ -import type { JiraConnectionStatus, JiraSite } from '../shared/jira/jira-types' -import type { RuntimeStatus } from '../shared/runtime-types' -import { JIRA_AGENT_ACCESS_RUNTIME_CAPABILITY } from '../shared/jira/jira-agent-capability' +import type { JiraConnectionStatus, JiraSite } from '../../shared/jira/jira-types' +import type { RuntimeStatus } from '../../shared/runtime-session-contracts' +import { JIRA_AGENT_ACCESS_RUNTIME_CAPABILITY } from '../../shared/jira/jira-agent-capability' import { getMatchingJiraSites, JIRA_ISSUE_KEY_PATTERN, parseJiraIssueUrl -} from '../shared/jira/jira-issue-url' -import type { HandlerContext } from './dispatch' -import { getOptionalStringFlag } from './flags' -import { RuntimeClientError } from './runtime-client' +} from '../../shared/jira/jira-issue-url' +import type { HandlerContext } from '../dispatch' +import { getOptionalStringFlag } from '../flags' +import { RuntimeClientError } from '../runtime/types' export function resolveJiraTarget( context: HandlerContext, diff --git a/src/cli/handlers/jira-write.test.ts b/src/cli/jira/jira-write.test.ts similarity index 97% rename from src/cli/handlers/jira-write.test.ts rename to src/cli/jira/jira-write.test.ts index a9306a20d29..1e4810800a6 100644 --- a/src/cli/handlers/jira-write.test.ts +++ b/src/cli/jira/jira-write.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest' import { JIRA_AGENT_ACCESS_RUNTIME_CAPABILITY } from '../../shared/jira/jira-agent-capability' -import { RuntimeClientError } from '../runtime-client' +import { RuntimeClientError } from '../runtime/types' import { JIRA_WRITE_HANDLERS } from './jira-write' function clientFailingWrite(failure: Error) { diff --git a/src/cli/handlers/jira-write.ts b/src/cli/jira/jira-write.ts similarity index 96% rename from src/cli/handlers/jira-write.ts rename to src/cli/jira/jira-write.ts index 37b99c9781a..5cabb2de15b 100644 --- a/src/cli/handlers/jira-write.ts +++ b/src/cli/jira/jira-write.ts @@ -14,10 +14,11 @@ import { getRepeatedStringFlag, getRequiredStringFlag } from '../flags' -import { printResult } from '../format' -import { formatJiraCreate } from '../jira-format' -import { resolveJiraTarget } from '../jira-target' -import { RuntimeClientError, type RuntimeRpcSuccess } from '../runtime-client' +import { printResult } from '../command-result-output' +import { formatJiraCreate } from './jira-format' +import { resolveJiraTarget } from './jira-target' +import { RuntimeClientError } from '../runtime/types' +import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope' async function callJiraWrite( context: HandlerContext, diff --git a/src/cli/handlers/jira.ts b/src/cli/jira/jira.ts similarity index 97% rename from src/cli/handlers/jira.ts rename to src/cli/jira/jira.ts index 48fab64afe6..a15bfbf3e1f 100644 --- a/src/cli/handlers/jira.ts +++ b/src/cli/jira/jira.ts @@ -17,7 +17,7 @@ import { getOptionalStringFlag, getRequiredStringFlag } from '../flags' -import { printResult } from '../format' +import { printResult } from '../command-result-output' import { formatJiraCommentList, formatJiraIssue, @@ -27,9 +27,9 @@ import { formatJiraProjectList, formatJiraTransitionList, formatJiraUserList -} from '../jira-format' -import { resolveJiraTarget } from '../jira-target' -import { RuntimeClientError } from '../runtime-client' +} from './jira-format' +import { resolveJiraTarget } from './jira-target' +import { RuntimeClientError } from '../runtime/types' import { JIRA_WRITE_HANDLERS } from './jira-write' function issueTarget(context: HandlerContext) { diff --git a/src/cli/handlers/linear-comment-write.ts b/src/cli/linear/linear-comment-write.ts similarity index 91% rename from src/cli/handlers/linear-comment-write.ts rename to src/cli/linear/linear-comment-write.ts index b7112d95311..e92e6ba1b4a 100644 --- a/src/cli/handlers/linear-comment-write.ts +++ b/src/cli/linear/linear-comment-write.ts @@ -1,25 +1,25 @@ import type { LinearCommentAddRequest, - LinearCommentAddResult, LinearCommentDeleteRequest, LinearCommentDeleteResult, LinearCommentEditRequest, LinearCommentEditResult } from '../../shared/linear/agent-access' +import type { LinearCommentAddResult } from '../../shared/linear/agent-result-types' import type { CommandHandler } from '../dispatch' import { getOptionalStringFlag, getRequiredStringFlag } from '../flags' -import { printResult } from '../format' +import { printResult } from '../command-result-output' import { formatLinearCommentAdd, formatLinearCommentDelete, formatLinearCommentEdit -} from '../linear-format' +} from './linear-format' import { buildWriteTargetRequest, getOptionalWriteId, readLinearBody, rejectAllWorkspaceForWrite -} from '../linear-request-builders' +} from './linear-request-builders' const LINEAR_WRITE_TIMEOUT_MS = 75_000 diff --git a/src/cli/linear-format.ts b/src/cli/linear/linear-format.ts similarity index 93% rename from src/cli/linear-format.ts rename to src/cli/linear/linear-format.ts index 5a632ad1450..350bca9dd28 100644 --- a/src/cli/linear-format.ts +++ b/src/cli/linear/linear-format.ts @@ -1,14 +1,10 @@ import type { LinearAttachResult, LinearCommentAddResult, - LinearCommentDeleteResult, - LinearCommentEditResult, LinearCreateResult, LinearIssueListResult, - LinearMcpIssueListResult, LinearIssueContextResult, LinearIssueTaskUpdateResult, - LinearIssueRelationWriteResult, LinearSaveIssueResult, LinearProjectListResult, LinearSearchIssueSummary, @@ -18,15 +14,21 @@ import type { LinearTeamMembersResult, LinearTeamStatesResult, LinearStatusSetResult -} from '../shared/linear/agent-access' -import { appendLinearListTruncation } from '../shared/linear/list-truncation-format' -import { linearPriorityLabel } from '../shared/linear/priority-label' +} from '../../shared/linear/agent-result-types' +import type { + LinearCommentDeleteResult, + LinearCommentEditResult +} from '../../shared/linear/agent-access' +import type { LinearMcpIssueListResult } from '../../shared/linear/mcp-issue-list' +import type { LinearIssueRelationWriteResult } from '../../shared/linear/issue-relation-write' +import { appendLinearListTruncation } from '../../shared/linear/list-truncation-format' +import { linearPriorityLabel } from '../../shared/linear/priority-label' import { formatLinearProjectListRows, linearProjectListWarningLines -} from '../shared/linear/project-list-format' -import { padEndToTerminalWidth } from '../shared/terminal/display-width/terminal-display-width' -import { terminalSafeLine as safe } from '../shared/terminal/output/terminal-safe-text' +} from '../../shared/linear/project-list-format' +import { padEndToTerminalWidth } from '../../shared/terminal/display-width/terminal-display-width' +import { terminalSafeLine as safe } from '../../shared/terminal/output/terminal-safe-text' export function formatLinearIssue(result: LinearIssueContextResult): string { const issue = result.issue diff --git a/src/cli/linear-handler-group.ts b/src/cli/linear/linear-handler-group.ts similarity index 85% rename from src/cli/linear-handler-group.ts rename to src/cli/linear/linear-handler-group.ts index d59d1184886..9e84a81dbf2 100644 --- a/src/cli/linear-handler-group.ts +++ b/src/cli/linear/linear-handler-group.ts @@ -1,4 +1,4 @@ -import type { HandlerGroup } from './handler-group-manifest' +import type { HandlerGroup } from '../handler-group-manifest' export const LINEAR_HANDLER_GROUP: HandlerGroup = { name: 'linear', @@ -33,5 +33,5 @@ export const LINEAR_HANDLER_GROUP: HandlerGroup = { 'linear attach', 'linear create' ], - load: async () => (await import('./handlers/linear.js')).LINEAR_HANDLERS + load: async () => (await import('./linear.js')).LINEAR_HANDLERS } diff --git a/src/cli/handlers/linear-list-issues.ts b/src/cli/linear/linear-list-issues.ts similarity index 92% rename from src/cli/handlers/linear-list-issues.ts rename to src/cli/linear/linear-list-issues.ts index 51efa1b711e..d4ec8666afd 100644 --- a/src/cli/handlers/linear-list-issues.ts +++ b/src/cli/linear/linear-list-issues.ts @@ -1,16 +1,16 @@ import type { LinearMcpIssueListRequest, LinearMcpIssueListResult -} from '../../shared/linear/agent-access' +} from '../../shared/linear/mcp-issue-list' import type { CommandHandler } from '../dispatch' import { getOptionalNonNegativeIntegerFlag, getOptionalPositiveIntegerFlag, getOptionalStringFlag } from '../flags' -import { printResult } from '../format' -import { formatLinearMcpIssueList, printLinearMcpIssueListWarnings } from '../linear-format' -import { RuntimeClientError } from '../runtime-client' +import { printResult } from '../command-result-output' +import { formatLinearMcpIssueList, printLinearMcpIssueListWarnings } from './linear-format' +import { RuntimeClientError } from '../runtime/types' export const runLinearListIssues: CommandHandler = async ({ flags, client, json }) => { const priority = getOptionalNonNegativeIntegerFlag(flags, 'priority') diff --git a/src/cli/handlers/linear-relation-write.ts b/src/cli/linear/linear-relation-write.ts similarity index 82% rename from src/cli/handlers/linear-relation-write.ts rename to src/cli/linear/linear-relation-write.ts index 2a718442df7..c11cdefc4e1 100644 --- a/src/cli/handlers/linear-relation-write.ts +++ b/src/cli/linear/linear-relation-write.ts @@ -2,13 +2,13 @@ import type { LinearIssueRelationship, LinearIssueRelationWriteRequest, LinearIssueRelationWriteResult -} from '../../shared/linear/agent-access' +} from '../../shared/linear/issue-relation-write' import type { CommandHandler } from '../dispatch' import { getRequiredStringFlag } from '../flags' -import { printResult } from '../format' -import { formatLinearRelationWrite } from '../linear-format' -import { buildWriteTargetRequest } from '../linear-request-builders' -import { RuntimeClientError } from '../runtime-client' +import { printResult } from '../command-result-output' +import { formatLinearRelationWrite } from './linear-format' +import { buildWriteTargetRequest } from './linear-request-builders' +import { RuntimeClientError } from '../runtime/types' const LINEAR_WRITE_TIMEOUT_MS = 75_000 diff --git a/src/cli/linear-request-builders.ts b/src/cli/linear/linear-request-builders.ts similarity index 96% rename from src/cli/linear-request-builders.ts rename to src/cli/linear/linear-request-builders.ts index 97704f90110..f3f434da18f 100644 --- a/src/cli/linear-request-builders.ts +++ b/src/cli/linear/linear-request-builders.ts @@ -1,24 +1,24 @@ -import { readCommandBody } from './command-body-input' +import { readCommandBody } from '../command-body-input' import type { LinearIssueInclude, LinearIssueListRequest, LinearIssueRequest, LinearIssueTaskUpdateRequest, LinearWriteTargetRequest -} from '../shared/linear/agent-access' +} from '../../shared/linear/agent-access' import { LINEAR_CHILDREN_MAX_DEPTH, LINEAR_WRITE_BODY_CAP, clampLinearIssueDepth -} from '../shared/linear/agent-access' -import { isLinearUuid } from '../shared/linear/uuid' +} from '../../shared/linear/agent-access' +import { isLinearUuid } from '../../shared/linear/uuid' import { getOptionalNonNegativeIntegerFlag, getOptionalStringFlag, getRepeatedStringFlag, getRequiredStringFlag -} from './flags' -import { RuntimeClientError } from './runtime-client' +} from '../flags' +import { RuntimeClientError } from '../runtime/types' const LINEAR_PRIORITY_VALUES = new Map([ ['none', 0], diff --git a/src/cli/linear-save-issue-request.ts b/src/cli/linear/linear-save-issue-request.ts similarity index 93% rename from src/cli/linear-save-issue-request.ts rename to src/cli/linear/linear-save-issue-request.ts index 95111463cc8..1c2033506ae 100644 --- a/src/cli/linear-save-issue-request.ts +++ b/src/cli/linear/linear-save-issue-request.ts @@ -1,9 +1,9 @@ -import type { LinearSaveIssueRequest } from '../shared/linear/agent-access' +import type { LinearSaveIssueRequest } from '../../shared/linear/agent-access' import { getOptionalNullableNumberFlag, getOptionalStringFlag, getRepeatedStringFlag -} from './flags' +} from '../flags' import { buildLinearCurrentContext, getDueDateFlag, @@ -12,7 +12,7 @@ import { readLinearBody, rejectAllWorkspaceForWrite } from './linear-request-builders' -import { RuntimeClientError } from './runtime-client' +import { RuntimeClientError } from '../runtime/types' export async function buildSaveIssueRequest( flags: Map, diff --git a/src/cli/handlers/linear-save-issue.ts b/src/cli/linear/linear-save-issue.ts similarity index 57% rename from src/cli/handlers/linear-save-issue.ts rename to src/cli/linear/linear-save-issue.ts index c946e0d15c9..2fb6418f2b3 100644 --- a/src/cli/handlers/linear-save-issue.ts +++ b/src/cli/linear/linear-save-issue.ts @@ -1,11 +1,9 @@ -import type { - LinearSaveIssueRequest, - LinearSaveIssueResult -} from '../../shared/linear/agent-access' +import type { LinearSaveIssueRequest } from '../../shared/linear/agent-access' +import type { LinearSaveIssueResult } from '../../shared/linear/agent-result-types' import type { CommandHandler } from '../dispatch' -import { printResult } from '../format' -import { formatLinearSaveIssue } from '../linear-format' -import { buildSaveIssueRequest } from '../linear-save-issue-request' +import { printResult } from '../command-result-output' +import { formatLinearSaveIssue } from './linear-format' +import { buildSaveIssueRequest } from './linear-save-issue-request' const LINEAR_WRITE_TIMEOUT_MS = 75_000 diff --git a/src/cli/linear/linear.test.ts b/src/cli/linear/linear.test.ts new file mode 100644 index 00000000000..8bbfcf71efd --- /dev/null +++ b/src/cli/linear/linear.test.ts @@ -0,0 +1,164 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const callMock = vi.fn() + +vi.mock('../runtime/client', async () => { + class RuntimeClient { + readonly isRemote: boolean + call = callMock + getCliStatus = vi.fn() + openOrca = vi.fn() + + constructor( + _userDataPath?: string, + _requestTimeoutMs?: number, + remotePairingCode = process.env.ORCA_PAIRING_CODE ?? null, + environmentSelector = process.env.ORCA_ENVIRONMENT ?? null + ) { + this.isRemote = Boolean(remotePairingCode || environmentSelector) + } + } + + return { RuntimeClient } +}) + +import { main } from '../index' +import { okFixture, queueFixtures } from '../test-fixtures' + +describe('orca linear CLI handlers', () => { + const originalEnv = { ...process.env } + + beforeEach(() => { + vi.restoreAllMocks() + callMock.mockReset() + process.env = { ...originalEnv } + // Clear real terminal/worktree/pairing hints inherited from the test runner. + delete process.env.ORCA_WORKTREE_ID + delete process.env.ORCA_TERMINAL_HANDLE + delete process.env.ORCA_PAIRING_CODE + delete process.env.ORCA_ENVIRONMENT + process.exitCode = undefined + vi.spyOn(console, 'log').mockImplementation(() => {}) + vi.spyOn(console, 'error').mockImplementation(() => {}) + }) + + it('prints truncation on human stdout and in JSON without using stderr for JSON', async () => { + const listResult = { + issues: [ + { + id: 'issue-1', + identifier: 'ENG-1', + title: 'Fix auth', + url: 'https://linear.app/acme/issue/ENG-1', + labels: [], + workspace: { id: 'workspace-1', name: 'Acme' } + } + ], + truncated: true, + meta: { + limit: 1, + returned: 1, + hasMore: true, + nextCursor: 'next-page', + orderBy: 'updatedAt', + workspaceId: 'workspace-1', + partial: false, + workspaceErrors: [] + } + } + queueFixtures(callMock, okFixture('req_list', listResult)) + await main(['linear', 'list-issues', '--limit', '1'], '/tmp/repo') + expect(vi.mocked(console.log).mock.calls[0][0]).toContain('truncated: showing 1') + expect( + vi.mocked(console.error).mock.calls.some((call) => String(call[0]).includes('more results')) + ).toBe(true) + + vi.mocked(console.log).mockClear() + vi.mocked(console.error).mockClear() + queueFixtures(callMock, okFixture('req_list_json', listResult)) + await main(['linear', 'list-issues', '--limit', '1', '--json'], '/tmp/repo') + const jsonOut = String(vi.mocked(console.log).mock.calls[0][0]) + expect(jsonOut).toContain('"truncated": true') + expect(vi.mocked(console.error)).not.toHaveBeenCalled() + }) + + it('rejects --depth unless children are requested', async () => { + await main(['linear', 'issue', 'ENG-123', '--depth', '3'], '/tmp/repo') + + expect(callMock).not.toHaveBeenCalled() + expect(vi.mocked(console.error).mock.calls[0][0]).toContain( + '--depth requires --children or --full' + ) + expect(process.exitCode).toBe(1) + }) + + it('rejects impossible due dates before dispatch', async () => { + await main(['linear', 'due-date', 'set', 'ENG-123', '--to', '2026-02-30'], '/tmp/repo') + + expect(callMock).not.toHaveBeenCalled() + expect(vi.mocked(console.error).mock.calls[0][0]).toContain('real calendar date') + }) + + it('requires exact write targets for issue writes', async () => { + await main(['linear', 'comment', 'add', '--body', 'done'], '/tmp/repo') + + expect(callMock).not.toHaveBeenCalled() + expect(vi.mocked(console.error).mock.calls[0][0]).toContain( + 'Pass a Linear issue id or --current' + ) + expect(process.exitCode).toBe(1) + }) + + it('rejects --workspace all for writes before dispatch', async () => { + await main( + [ + 'linear', + 'attach', + 'ENG-123', + '--url', + 'https://example.com/review/123', + '--workspace', + 'all' + ], + '/tmp/repo' + ) + + expect(callMock).not.toHaveBeenCalled() + expect(vi.mocked(console.error).mock.calls[0][0]).toContain( + '--workspace all is not valid for Linear writes' + ) + expect(process.exitCode).toBe(1) + }) + + it('rejects malformed write ids before dispatch', async () => { + await main( + [ + 'linear', + 'attach', + 'ENG-123', + '--url', + 'https://example.com/review/123', + '--write-id', + 'not-a-uuid', + '--json' + ], + '/tmp/repo' + ) + + expect(callMock).not.toHaveBeenCalled() + const payload = JSON.parse(String(vi.mocked(console.log).mock.calls[0][0])) as { + error: { code: string } + } + expect(payload.error.code).toBe('linear_invalid_write_id') + }) + + it('rejects duplicate body inputs before dispatch', async () => { + await main( + ['linear', 'create', '--title', 'Bug', '--body', 'one', '--body-file', 'body.md'], + '/tmp/repo' + ) + + expect(callMock).not.toHaveBeenCalled() + expect(vi.mocked(console.error).mock.calls[0][0]).toContain('Use either --body or --body-file') + }) +}) diff --git a/src/cli/handlers/linear.ts b/src/cli/linear/linear.ts similarity index 97% rename from src/cli/handlers/linear.ts rename to src/cli/linear/linear.ts index 75952170a10..aa82959b272 100644 --- a/src/cli/handlers/linear.ts +++ b/src/cli/linear/linear.ts @@ -1,27 +1,29 @@ import type { LinearAttachRequest, - LinearAttachResult, LinearCreateRequest, - LinearCreateResult, LinearIssueListRequest, + LinearProjectListRequest, + LinearIssueTaskUpdateRequest, + LinearStatusSetRequest +} from '../../shared/linear/agent-access' +import type { + LinearAttachResult, + LinearCreateResult, LinearIssueListResult, LinearIssueContextResult, - LinearProjectListRequest, LinearProjectListResult, - LinearIssueTaskUpdateRequest, LinearIssueTaskUpdateResult, LinearSearchResult, - LinearStatusSetRequest, LinearStatusSetResult, LinearTeamLabelsResult, LinearTeamListResult, LinearTeamMembersResult, LinearTeamStatesResult -} from '../../shared/linear/agent-access' +} from '../../shared/linear/agent-result-types' import { clampLinearSearchLimit } from '../../shared/linear/agent-access' import type { CommandHandler } from '../dispatch' -import { printResult } from '../format' -import { RuntimeClientError } from '../runtime-client' +import { printResult } from '../command-result-output' +import { RuntimeClientError } from '../runtime/types' import { getOptionalPositiveIntegerFlag, getOptionalStringFlag, @@ -42,7 +44,7 @@ import { getRequiredRepeatedStringFlag, readLinearBody, rejectAllWorkspaceForWrite -} from '../linear-request-builders' +} from './linear-request-builders' import { formatLinearAttach, formatLinearCreate, @@ -60,7 +62,7 @@ import { printLinearListWarnings, printLinearProjectListWarnings, printLinearSearchWarnings -} from '../linear-format' +} from './linear-format' import { LINEAR_COMMENT_WRITE_HANDLERS } from './linear-comment-write' import { runLinearListIssues } from './linear-list-issues' import { linearRelationWriteHandler } from './linear-relation-write' diff --git a/src/cli/orchestration-session-caller-cli.test.ts b/src/cli/orchestration-session-caller-cli.test.ts index 0f7742dcfa7..49372109b01 100644 --- a/src/cli/orchestration-session-caller-cli.test.ts +++ b/src/cli/orchestration-session-caller-cli.test.ts @@ -5,7 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const callMock = vi.hoisted(() => vi.fn()) const getTerminalHandleMock = vi.hoisted(() => vi.fn()) -vi.mock('./format', () => ({ printResult: vi.fn() })) +vi.mock('./command-result-output', () => ({ printResult: vi.fn() })) vi.mock('./selectors', () => ({ getTerminalHandle: getTerminalHandleMock })) import { ORCHESTRATION_HANDLERS } from './handlers/orchestration' @@ -13,13 +13,11 @@ import { findCommandSpec } from './args' import { COMMAND_SPECS } from './specs' import { refuseConflictingSessionCallerFlags } from './session-caller-flags' import { createOrchestrationCompatibilityEnvelope } from './runtime/orchestration-compatibility-envelope' -import { getDefaultUserDataPath } from './runtime/metadata' -import { formatCliError, reportCliError } from './cli-error' + +import { formatCliError } from './cli-error' import { RuntimeRpcFailureError } from './runtime/types' const SESSION = 'f7a1c0de-1111-4222-8333-444455556666' -/** SESSION continues ROOT after /clear, retaining ROOT's orchestration address. */ -const ROOT = '0b5e2d7c-9a41-4c3e-8f62-7d1a3e5b9c08' const IDENTITY_ENV = [ 'ORCA_AGENT_SESSION_ID', 'ORCA_TERMINAL_HANDLE', @@ -249,20 +247,6 @@ afterEach(() => { describe.each(CALLER_VERBS)('orchestration $command run as an agent session', (verb) => { beforeEach(asSessionWithInheritedPane) - it('acts as the session: no terminal is resolved, guessed or sent', async () => { - await invoke(verb.command, flagMap(verb.flags)) - - const [params] = callsTo(verb.method) - expect(params, 'the verb reached its method').toBeDefined() - expect(params?.[verb.callerParam]).toBeUndefined() - expect(params?.terminalPaneKey).toBeUndefined() - expect(params?.senderPaneKey).toBeUndefined() - expect(getTerminalHandleMock).not.toHaveBeenCalled() - expect(callMock.mock.calls.map(([name]) => name)).not.toEqual( - expect.arrayContaining([expect.stringMatching(/^terminal\./)]) - ) - }) - it.runIf(verb.callerFlag !== undefined)( 'refuses a caller flag naming another caller, before any request', async () => { @@ -286,40 +270,8 @@ describe.each(CALLER_VERBS)('orchestration $command run as an agent session', (v expect(callMock).not.toHaveBeenCalled() } ) - - it.runIf(verb.callerFlag !== undefined).each([`orca_session_id:${SESSION}`, SESSION])( - 'accepts a caller flag that restates the session (%s)', - async (restated) => { - await invoke(verb.command, flagMap({ ...verb.flags, [verb.callerFlag ?? 'from']: restated })) - - const [params] = callsTo(verb.method) - expect(params, 'the verb reached its method').toBeDefined() - expect(params?.[verb.callerParam]).toBeUndefined() - } - ) }) -describe.each(CALLER_VERBS.filter((verb) => verb.callerFlag !== undefined))( - 'orchestration $command run by a /clear-ed chat', - (verb) => { - beforeEach(asSessionWithInheritedPane) - - it('sends the address it had before the clear for the host to place, instead of refusing it', async () => { - const flags = flagMap({ - ...verb.flags, - [verb.callerFlag ?? 'from']: `orca_session_id:${ROOT}` - }) - await invoke(verb.command, flags) - - const [params] = callsTo(verb.method) - expect(params?.[verb.callerParam]).toBe(`orca_session_id:${ROOT}`) - expect(params?.terminalPaneKey).toBeUndefined() - expect(params?.senderPaneKey).toBeUndefined() - expect(getTerminalHandleMock).not.toHaveBeenCalled() - }) - } -) - describe.each([ { command: 'gate-list', method: 'gateList', callerParam: 'from' }, { command: 'task-list', method: 'taskList', callerParam: 'callerTerminalHandle' } @@ -337,20 +289,6 @@ describe.each([ ).rejects.toMatchObject({ code: 'consumer_fenced' }) expect(callMock).not.toHaveBeenCalled() }) - - it('accepts a --from that restates the session', async () => { - await invoke(command, flagMap({ run: 'run_1', from: `orca_session_id:${SESSION}` })) - expect(callsTo(method)[0]?.[callerParam]).toBeUndefined() - }) - - it.each([`orca_session_id:${ROOT}`, 'orca_session_id:9d4c1b2a-3e5f-4a6b-8c7d-0e1f2a3b4c5d'])( - 'sends a session address it cannot place (%s) for the host to check, never dropping it', - async (declared) => { - // Forward session addresses for host lineage checks; dropping them would bypass caller fencing. - await invoke(command, flagMap({ run: 'run_1', from: declared })) - expect(callsTo(method)[0]).toMatchObject({ run: 'run_1', [callerParam]: declared }) - } - ) }) describe('the identity a session presents', () => { @@ -367,27 +305,6 @@ describe('the identity a session presents', () => { expect(callMock).not.toHaveBeenCalled() }) - it("sends a structured worker's lifecycle report as the session, not refused as identity-less", async () => { - setEnv({ ORCA_AGENT_SESSION_ID: SESSION }) - - await invoke( - 'send', - flagMap({ to: 'run:run_1', subject: 'done', type: 'worker_done', outcome: 'succeeded' }) - ) - - expect(callsTo('send')[0]).toMatchObject({ type: 'worker_done' }) - expect(callsTo('send')[0]?.from).toBeUndefined() - }) - - it('never treats a session that has an id as identity-less, even beside the old marker', async () => { - setEnv({ ORCA_AGENT_SESSION_ID: SESSION, ORCA_STRUCTURED_SESSION: '1' }) - - await invoke('check', flagMap({})) - - expect(callsTo('check')).toHaveLength(1) - expect(getTerminalHandleMock).not.toHaveBeenCalled() - }) - it('keeps the identity-less refusal, without --from advice, for a child that has no id', async () => { setEnv({ ORCA_STRUCTURED_SESSION: '1' }) @@ -398,48 +315,6 @@ describe('the identity a session presents', () => { expect(getTerminalHandleMock).not.toHaveBeenCalled() expect(callMock).not.toHaveBeenCalled() }) - - it('leaves a terminal agent exactly as it was: its own handle is the caller', async () => { - setEnv({ ORCA_TERMINAL_HANDLE: 'term_pty', ORCA_PANE_KEY: 'tab_pty:1:2' }) - callMock.mockImplementation(async (name: string) => - name === 'terminal.resolveIdentity' ? { result: { identity: { live: true } } } : RESULT - ) - - await invoke('run-create', flagMap({ objective: 'o' })) - await invoke('check', flagMap({})) - - expect(callsTo('runCreate')[0]?.from).toBe('term_pty') - expect(callsTo('check')[0]).toMatchObject({ - terminal: 'term_pty', - terminalPaneKey: 'tab_pty:1:2' - }) - }) - - it('previews a dispatch with the coordinator address the real dispatch would write', async () => { - const preview = async (flags: Record) => { - callMock.mockClear() - await invoke('dispatch-show', flagMap({ task: 'task_1', preamble: true, ...flags })) - return callsTo('dispatchShow')[0]?.from - } - asSessionWithInheritedPane() - expect(await preview({})).toBe(`orca_session_id:${SESSION}`) - expect(await preview({ from: 'term_sibling' })).toBe('term_sibling') - setEnv({ ORCA_AGENT_SESSION_ID: SESSION, ORCA_TERMINAL_HANDLE: 'structworker_self' }) - expect(await preview({})).toBe('structworker_self') - expect(getTerminalHandleMock).not.toHaveBeenCalled() - }) - - it('resumes a timed-out ask as the session, without naming a terminal', async () => { - asSessionWithInheritedPane() - callMock.mockResolvedValue({ result: { ...RESULT.result, answer: null, timedOut: true } }) - const logs = vi.mocked(console.log) - - await invoke('ask', flagMap({ to: 'term_worker', question: 'q' }), false) - - const advice = logs.mock.calls.map(([line]) => String(line)).join('\n') - expect(advice).toContain('--resume msg_1') - expect(advice).not.toContain('--from') - }) }) describe('a host refusal of the session', () => { @@ -465,30 +340,6 @@ describe('a host refusal of the session', () => { expect(formatCliError(WORKER_GONE)).toBe(WORKER_GONE.message) } ) - - it('keeps the Orca id a provider-id refusal names, for a JSON reader to branch on', () => { - const providerId = new RuntimeRpcFailureError({ - id: 'rpc_1', - ok: false, - error: { - code: 'session_caller_provider_id', - message: 'provider id', - data: { effectsApplied: false, orcaSessionId: SESSION } - }, - _meta: { runtimeId: 'runtime_1' } - }) - const printed: string[] = [] - vi.mocked(console.log).mockImplementation((line: string) => { - printed.push(line) - }) - - reportCliError(providerId, true) - - expect(JSON.parse(printed.join('\n'))).toMatchObject({ - ok: false, - error: { code: 'session_caller_provider_id', data: { orcaSessionId: SESSION } } - }) - }) }) describe('the orchestration envelope', () => { @@ -504,58 +355,17 @@ describe('the orchestration envelope', () => { }) }) - it('binds whichever current Orca CLI the agent reached, not only the one the session names', () => { - // Another CLI install may rewrite ORCA_CLI_COMMAND; the envelope must still pin the session instance. - vi.stubEnv('ORCA_USER_DATA_PATH', '/data/session-orca') - try { - const envelope = createOrchestrationCompatibilityEnvelope({ - ORCA_AGENT_SESSION_ID: SESSION, - ORCA_CLI_COMMAND: 'orca', - ORCA_WINDOWS_PACKAGED_CLI_LAUNCHER: '1', - ORCA_USER_DATA_PATH: '/data/session-orca' - }) - - expect(envelope.orchestrationCompatibilityEvidence).toEqual({ agentSessionId: SESSION }) - expect(getDefaultUserDataPath('linux', '/home/u')).toBe('/data/session-orca') - } finally { - vi.unstubAllEnvs() - } - }) - it('claims no session without an injected id', () => { expect( createOrchestrationCompatibilityEnvelope({ ORCA_AGENT_SESSION_ID: ' ' }) .orchestrationCompatibilityEvidence ).toBeUndefined() }) - - it('keeps a WSL stamp beside the id, so the host can refuse the cross-host claim', () => { - const envelope = createOrchestrationCompatibilityEnvelope({ - ORCA_AGENT_SESSION_ID: SESSION, - ORCA_ORCHESTRATION_COMPATIBILITY_HOST_KIND: 'wsl', - ORCA_ORCHESTRATION_COMPATIBILITY_HOST_ID: 'local', - ORCA_ORCHESTRATION_COMPATIBILITY_HOST_INCARNATION: 'Ubuntu' - }) - - expect(envelope.orchestrationCompatibilityEvidence).toEqual({ - agentSessionId: SESSION, - host: { kind: 'wsl', hostId: 'local', distro: 'Ubuntu' } - }) - }) }) describe('which flag names the caller, declared on every spec', () => { const ORCHESTRATION_SPECS = COMMAND_SPECS.filter((spec) => spec.path[0] === 'orchestration') - it('classifies every --from and --terminal an orchestration verb accepts', () => { - const unclassified = ORCHESTRATION_SPECS.flatMap((spec) => - (['from', 'terminal'] as const) - .filter((flag) => spec.allowedFlags.includes(flag) && !spec.identityFlagRoles?.[flag]) - .map((flag) => `${spec.path.join(' ')} --${flag}`) - ) - expect(unclassified).toEqual([]) - }) - const callerFlagVerbs = ORCHESTRATION_SPECS.flatMap((spec) => (['from', 'terminal'] as const) .filter((flag) => spec.identityFlagRoles?.[flag] === 'caller') @@ -573,18 +383,4 @@ describe('which flag names the caller, declared on every spec', () => { expect(getTerminalHandleMock).not.toHaveBeenCalled() } ) - - it.each( - ORCHESTRATION_SPECS.flatMap((spec) => - (['from', 'terminal'] as const) - .filter((flag) => spec.identityFlagRoles?.[flag] === 'target') - .map((flag) => ({ command: spec.path[1] ?? '', flag })) - ) - )('$command passes a --$flag target through unfenced', async ({ command, flag }) => { - asSessionWithInheritedPane() - await invoke(command, flagMap({ ...EVERY_REQUIRED_FLAG, [flag]: 'term_sibling' })) - expect(callMock.mock.calls.flatMap(([, params]) => Object.values(params ?? {}))).toContain( - 'term_sibling' - ) - }) }) diff --git a/src/cli/orchestration-structured-session-no-identity.test.ts b/src/cli/orchestration-structured-session-no-identity.test.ts index 566dd31e6ab..cc0235f0e32 100644 --- a/src/cli/orchestration-structured-session-no-identity.test.ts +++ b/src/cli/orchestration-structured-session-no-identity.test.ts @@ -4,7 +4,7 @@ import { ORCA_STRUCTURED_SESSION_ENV } from '../shared/structured-session-marker const callMock = vi.hoisted(() => vi.fn()) const getTerminalHandleMock = vi.hoisted(() => vi.fn()) -vi.mock('./format', () => ({ printResult: vi.fn() })) +vi.mock('./command-result-output', () => ({ printResult: vi.fn() })) vi.mock('./selectors', () => ({ getTerminalHandle: getTerminalHandleMock })) import { ORCHESTRATION_HANDLERS } from './handlers/orchestration' @@ -66,13 +66,4 @@ describe('a structured chat session with no orchestration identity', () => { ).rejects.toMatchObject({ message: expect.stringContaining('--from') }) expect(callMock).not.toHaveBeenCalled() }) - - it('still accepts an explicit --terminal, which is the actionable escape', async () => { - callMock.mockResolvedValue({ result: { messages: [], count: 0 } }) - await invoke('orchestration check', new Map([['terminal', 'structworker_self']])) - expect(callMock).toHaveBeenCalledWith( - 'orchestration.check', - expect.objectContaining({ terminal: 'structworker_self' }) - ) - }) }) diff --git a/src/cli/reference-input.ts b/src/cli/reference-input.ts index d60bc1049c1..94a7d823c13 100644 --- a/src/cli/reference-input.ts +++ b/src/cli/reference-input.ts @@ -15,7 +15,7 @@ import { import type { HandlerContext } from './dispatch' import { type RuntimeClient, RuntimeClientError } from './runtime-client' import { getOptionalStringFlag, getRepeatedStringFlag } from './flags' -import { resolveJiraTarget } from './jira-target' +import { resolveJiraTarget } from './jira/jira-target' type ReferenceInput = { key: string } | { item: WorkspaceAttachment } diff --git a/src/cli/runtime/cli-status-format.ts b/src/cli/runtime/cli-status-format.ts new file mode 100644 index 00000000000..850689f8921 --- /dev/null +++ b/src/cli/runtime/cli-status-format.ts @@ -0,0 +1,27 @@ +import type { CliStatusCaller } from '../../shared/orchestration/orchestration-caller-status' +import type { CliStatusResult } from '../../shared/runtime-types' + +export function formatCliStatus(status: CliStatusResult): string { + return [ + ...(status.target && status.target.kind === 'environment' + ? [`target: environment ${status.target.environment}`] + : []), + `appRunning: ${status.app.running}`, + `pid: ${status.app.pid ?? 'none'}`, + `desktopWindowStatus: ${status.app.desktopWindowStatus ?? 'unknown'}`, + `runtimeState: ${status.runtime.state}`, + `runtimeReachable: ${status.runtime.reachable}`, + `runtimeConnectionState: ${status.runtime.connectionState ?? 'unknown'}`, + `runtimeId: ${status.runtime.runtimeId ?? 'none'}`, + `graphState: ${status.graph.state}`, + ...(status.runtime.degradations ?? []).map((degradation) => `degraded: ${degradation.message}`), + ...(status.caller === undefined ? [] : [`orcaSessionId: ${formatStatusCaller(status.caller)}`]) + ].join('\n') +} + +function formatStatusCaller(caller: CliStatusCaller): string { + if ('refusal' in caller) { + return `none (refused: ${caller.refusal.code})` + } + return `${caller.orcaSessionId}${caller.live ? '' : ' (not live)'}` +} diff --git a/src/cli/runtime/client-recovery.test.ts b/src/cli/runtime/client-recovery.test.ts index 17bd6f32ced..f285a2a04e6 100644 --- a/src/cli/runtime/client-recovery.test.ts +++ b/src/cli/runtime/client-recovery.test.ts @@ -5,7 +5,7 @@ import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' import '../../shared/protocol-version' import '../orchestration-mutation-recovery' -import { reportCliError } from '../format' +import { reportCliError } from '../cli-error' import { RuntimeClient, RuntimeClientError, RuntimeRpcFailureError } from '../runtime-client' const servers = new Set() diff --git a/src/cli/agent-session-search-format.ts b/src/cli/session-search/agent-session-search-format.ts similarity index 95% rename from src/cli/agent-session-search-format.ts rename to src/cli/session-search/agent-session-search-format.ts index d14c96b0dbd..cd1ba790762 100644 --- a/src/cli/agent-session-search-format.ts +++ b/src/cli/session-search/agent-session-search-format.ts @@ -1,10 +1,10 @@ -import { aiVaultAgentLabel } from '../shared/ai-vault/contracts/ai-vault-types' +import { aiVaultAgentLabel } from '../../shared/ai-vault/contracts/ai-vault-types' import type { AiVaultSearchHit, AiVaultSearchResponse, AiVaultSearchStatus -} from '../shared/ai-vault/search/ai-vault-search-types' -import { terminalSafeLine } from '../shared/terminal/output/terminal-safe-text' +} from '../../shared/ai-vault/search/ai-vault-search-types' +import { terminalSafeLine } from '../../shared/terminal/output/terminal-safe-text' type SessionSearchResults = Extract /** Malformed cursors are a caller mistake and leave through the CLI error channel. */ diff --git a/src/cli/search-command-arguments.test.ts b/src/cli/session-search/search-command-arguments.test.ts similarity index 95% rename from src/cli/search-command-arguments.test.ts rename to src/cli/session-search/search-command-arguments.test.ts index aa8a2da5f70..35891978eea 100644 --- a/src/cli/search-command-arguments.test.ts +++ b/src/cli/session-search/search-command-arguments.test.ts @@ -2,12 +2,12 @@ import { describe, expect, it } from 'vitest' import { normalizeCommandPositionals, parseArgs, - specPaths, validateCommandAndFlags, type ParsedArgs -} from './args' +} from '../args' +import { specPaths } from '../command-spec' import { parseSearchCommand } from './search-command-arguments' -import { COMMAND_SPECS } from './specs' +import { COMMAND_SPECS } from '../specs/index' const COMMAND_PATHS = COMMAND_SPECS.flatMap((spec) => specPaths(spec)) diff --git a/src/cli/search-command-arguments.ts b/src/cli/session-search/search-command-arguments.ts similarity index 93% rename from src/cli/search-command-arguments.ts rename to src/cli/session-search/search-command-arguments.ts index 39096a081be..085c6d8474c 100644 --- a/src/cli/search-command-arguments.ts +++ b/src/cli/session-search/search-command-arguments.ts @@ -2,15 +2,15 @@ import { AI_VAULT_AGENTS, AI_VAULT_SCOPE_PATHS_MAX_COUNT, type AiVaultAgent -} from '../shared/ai-vault/contracts/ai-vault-types' -import { AiVaultSearchFiltersSchema } from '../shared/ai-vault/search/ai-vault-search-contract' -import type { AiVaultSearchRequest } from '../shared/ai-vault/search/ai-vault-search-types' +} from '../../shared/ai-vault/contracts/ai-vault-types' +import { AiVaultSearchFiltersSchema } from '../../shared/ai-vault/search/ai-vault-search-contract' +import type { AiVaultSearchRequest } from '../../shared/ai-vault/search/ai-vault-search-types' import { getOptionalPositiveIntegerFlag, getOptionalStringFlag, getRepeatedStringFlag -} from './flags' -import { RuntimeClientError } from './runtime/types' +} from '../flags' +import { RuntimeClientError } from '../runtime/types' export type SearchCommand = | { kind: 'index-status' } diff --git a/src/cli/handlers/search.ts b/src/cli/session-search/search.ts similarity index 90% rename from src/cli/handlers/search.ts rename to src/cli/session-search/search.ts index 3f87c4eb61c..ea87784486e 100644 --- a/src/cli/handlers/search.ts +++ b/src/cli/session-search/search.ts @@ -3,12 +3,12 @@ import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope' import { formatSessionSearchResponse, formatSessionSearchStatus -} from '../agent-session-search-format' +} from './agent-session-search-format' import type { CommandHandler } from '../dispatch' -import { printResult } from '../format' -import type { RuntimeClient } from '../runtime-client' +import { printResult } from '../command-result-output' +import type { RuntimeClient } from '../runtime/client' import { RuntimeClientError } from '../runtime/types' -import { parseSearchCommand } from '../search-command-arguments' +import { parseSearchCommand } from './search-command-arguments' export const MALFORMED_CURSOR_MESSAGE = 'The host did not recognise that --cursor value. Cursors belong to one query on one host; re-run the search without --cursor.' diff --git a/src/cli/ports-format.ts b/src/cli/workspace-ports/ports-format.ts similarity index 98% rename from src/cli/ports-format.ts rename to src/cli/workspace-ports/ports-format.ts index ef25d083838..31b63438274 100644 --- a/src/cli/ports-format.ts +++ b/src/cli/workspace-ports/ports-format.ts @@ -2,7 +2,7 @@ import type { WorkspacePort, WorkspacePortHostScanResult, WorkspacePortOwner -} from '../shared/workspace-ports' +} from '../../shared/workspace-ports' function ownerName(owner: WorkspacePortOwner): string { return owner.displayName || owner.worktreeId diff --git a/src/cli/handlers/ports.ts b/src/cli/workspace-ports/ports.ts similarity index 94% rename from src/cli/handlers/ports.ts rename to src/cli/workspace-ports/ports.ts index ba6e9f30c4a..cda0773fa69 100644 --- a/src/cli/handlers/ports.ts +++ b/src/cli/workspace-ports/ports.ts @@ -1,18 +1,16 @@ import { normalizeRuntimePathForComparison } from '../../shared/cross-platform-path' import type { FolderWorkspace } from '../../shared/folder-workspaces/folder-workspace-types' -import type { RuntimeStatus, RuntimeWorktreeRecord } from '../../shared/runtime-types' +import type { RuntimeStatus } from '../../shared/runtime-session-contracts' +import type { RuntimeWorktreeRecord } from '../../shared/runtime-worktree-contracts' import { WORKSPACE_SELECTOR_FOLDER_MATCH_RUNTIME_CAPABILITY } from '../../shared/worktree-runtime-capabilities' import type { WorkspacePortHostScanResult } from '../../shared/workspace-ports' import { parseWorkspaceKey } from '../../shared/workspace-scope' import type { CommandHandler, HandlerContext } from '../dispatch' import { getOptionalStringFlag } from '../flags' -import { printResult } from '../format' -import { formatPortsScan } from '../ports-format' -import { - RuntimeClientError, - RuntimeRpcFailureError, - type RuntimeRpcSuccess -} from '../runtime-client' +import { printResult } from '../command-result-output' +import { formatPortsScan } from './ports-format' +import { RuntimeClientError, RuntimeRpcFailureError } from '../runtime/types' +import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope' import { normalizeWorktreeSelectorForCaller, resolveCurrentWorktreeSelector } from '../selectors' type PortsTarget = { selector: string; worktreePath: string | null } diff --git a/src/main/runtime/rpc/methods/orchestration/cli-runtime-boundary.test.ts b/src/main/runtime/rpc/methods/orchestration/cli-runtime-boundary.test.ts index 1b37b5c220f..13af55d4888 100644 --- a/src/main/runtime/rpc/methods/orchestration/cli-runtime-boundary.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/cli-runtime-boundary.test.ts @@ -26,7 +26,7 @@ describe('orchestration CLI/runtime boundary', () => { afterEach(() => { h.cleanup() restoreTerminalHandle() - vi.doUnmock('../../../../../cli/format') + vi.doUnmock('../../../../../cli/command-result-output') vi.doUnmock('../../../../../cli/runtime-client') vi.unstubAllEnvs() vi.restoreAllMocks() @@ -104,7 +104,7 @@ describe('orchestration CLI/runtime boundary', () => { /** Imports orchestration handlers after mocking output so the test observes state, not stdout. */ async function loadOrchestrationHandlers(): Promise> { - vi.doMock('../../../../../cli/format', () => ({ printResult: vi.fn() })) + vi.doMock('../../../../../cli/command-result-output', () => ({ printResult: vi.fn() })) const cliModulePath = '../../../../../cli/handlers/orchestration' const module = (await import(cliModulePath)) as { ORCHESTRATION_HANDLERS: Record diff --git a/tests/e2e/agent-launch-cli.unit.test.ts b/tests/e2e/agent-launch-cli.unit.test.ts index 2a74aacde39..eb346bd9904 100644 --- a/tests/e2e/agent-launch-cli.unit.test.ts +++ b/tests/e2e/agent-launch-cli.unit.test.ts @@ -7,9 +7,9 @@ import type { StructuredAgentSessionFirstMessage } from '../../src/shared/agent- import { openTestAgentSessionRecordStore } from '../../src/main/runtime/agent-session/records/agent-session-record-store-test-harness' import { closeTestJournalHostDatabase } from '../../src/main/native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' import { RuntimeClient, RuntimeClientError } from '../../src/cli/runtime-client' -import { callAgentLaunch, readCliAgentLaunch } from '../../src/cli/agent-launch-request' +import { callAgentLaunch, readCliAgentLaunch } from '../../src/cli/agents/agent-launch-request' import { parseArgs } from '../../src/cli/args' -import { AGENT_LAUNCH_HANDLERS } from '../../src/cli/handlers/agent-launch' +import { AGENT_LAUNCH_HANDLERS } from '../../src/cli/agents/agent-launch' import { createWorktreeWithAgent } from '../../src/cli/handlers/worktree-create-agent-launch' import { methodNamed, @@ -299,47 +299,6 @@ describe('CLI launch through host surface creation and replay admission', () => expect(call).toHaveBeenCalledTimes(2) }) - it.each([undefined, 'current'])( - 'uses the innermost enclosing folder workspace for %s', - async (selector) => { - const client = hostClient(runtimeStub()) - vi.spyOn(console, 'log').mockImplementation(() => {}) - const call = vi.mocked(client.call) - call.mockResolvedValueOnce({ - id: 'list', - ok: true, - result: { worktrees: [], totalCount: 0, truncated: false }, - _meta: { runtimeId: 'runtime-1' } - }) - call.mockResolvedValueOnce({ - id: 'folders', - ok: true, - result: { - folderWorkspaces: [ - { id: 'outer', folderPath: '/tmp/repo' }, - { id: 'remote', folderPath: '/tmp/repo/nested/deeper', connectionId: 'ssh-1' }, - { id: 'nested', folderPath: '/tmp/repo/nested' } - ] - }, - _meta: { runtimeId: 'runtime-1' } - }) - const flags = new Map([['agent', 'codex']]) - if (selector) { - flags.set('worktree', selector) - } - await AGENT_LAUNCH_HANDLERS['agent launch']({ - flags, - client, - cwd: '/tmp/repo/nested/deeper', - json: true - }) - expect(call).toHaveBeenCalledWith( - 'agent.launchReplay', - expect.objectContaining({ target: { kind: 'existing', worktree: 'folder:nested' } }) - ) - } - ) - it('refuses remote cwd inference for current', async () => { const client = hostClient(runtimeStub()) vi.spyOn(client, 'isRemote', 'get').mockReturnValue(true)