From 560a22e00f4867398ecd73aaaeb01a5f9414d5ef Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Thu, 12 Nov 2026 08:12:55 -0800 Subject: [PATCH] refactor(cli): organize command dispatch and orchestration owners (#41562) * refactor(cli): organize command dispatch and orchestration owners * test(orchestration): retire superseded unbound mail refusal case --- .github/workflows/computer-e2e.yml | 2 +- config/flaky-test-pattern-baseline.txt | 4 +- .../process-host-direct-import-baseline.txt | 2 +- config/recurring-timer-baseline.txt | 2 +- config/reliability-gates.jsonc | 32 +- .../source-routing/pr-e2e-source-routing.mjs | 2 +- src/cli/accounts/account-selection.ts | 4 +- src/cli/accounts/account.test.ts | 4 +- src/cli/accounts/account.ts | 6 +- src/cli/accounts/data-account-commands.ts | 6 +- src/cli/agents/agent-hooks.ts | 8 +- src/cli/agents/agent-launch-recovery.ts | 2 +- src/cli/agents/agent-launch-request.ts | 2 +- src/cli/agents/agent-launch-test-fixtures.ts | 2 +- src/cli/agents/agent-launch.ts | 6 +- src/cli/agents/chat.ts | 6 +- .../args-repeatable-flags.test.ts | 26 +- src/cli/{ => arguments}/args.test.ts | 22 +- src/cli/{ => arguments}/args.ts | 15 +- src/cli/{ => arguments}/command-body-input.ts | 2 +- src/cli/{ => arguments}/flags.ts | 4 +- .../quote-stripped-json-flag.ts | 0 .../{ => arguments}/shell-command-quote.ts | 2 +- src/cli/artifacts/artifacts.ts | 6 +- src/cli/automations/automation-format.ts | 2 +- .../automations/automation-handler-flags.ts | 2 +- src/cli/automations/automations.ts | 6 +- src/cli/browser/browser-capture.ts | 6 +- src/cli/browser/browser-command-target.ts | 4 +- src/cli/browser/browser-cookie.ts | 6 +- src/cli/browser/browser-empty-values.test.ts | 151 +------ src/cli/browser/browser-env.ts | 6 +- src/cli/browser/browser-expect-url.test.ts | 82 +--- src/cli/browser/browser-extension.ts | 6 +- src/cli/browser/browser-format.ts | 2 +- src/cli/browser/browser-handler-groups.ts | 2 +- src/cli/browser/browser-identity.ts | 6 +- src/cli/browser/browser-interact.ts | 6 +- src/cli/browser/browser-nav.ts | 6 +- src/cli/browser/browser-profile.ts | 6 +- src/cli/browser/browser-storage.ts | 6 +- src/cli/browser/browser-tab.ts | 6 +- src/cli/computer/computer-action-flags.ts | 2 +- src/cli/computer/computer-command-target.ts | 2 +- src/cli/computer/computer-format.ts | 6 +- .../computer-state-formatting.test.ts | 2 +- src/cli/computer/computer.ts | 6 +- src/cli/{handlers => connectors}/connector.ts | 8 +- .../{handlers => diagnostics}/diagnostics.ts | 6 +- .../agent-context-handlers.ts} | 6 +- src/cli/{ => discovery}/agent-context.ts | 4 +- .../command-scoped-flag-help.ts | 0 src/cli/{ => discovery}/command-spec.ts | 0 .../command-suggestion-budget.test.ts | 25 +- ...nd-suggestion-destructive-families.test.ts | 4 +- .../command-suggestion.test.ts | 2 +- src/cli/{ => discovery}/command-suggestion.ts | 4 +- src/cli/{ => discovery}/flag-help-text.ts | 0 src/cli/{ => discovery}/help.ts | 9 +- .../{ => discovery}/root-help-text-primary.ts | 0 .../root-help-text-secondary.ts | 0 src/cli/{ => discovery}/vocabulary-policy.ts | 2 +- src/cli/{ => dispatch}/dispatch.ts | 4 +- .../{ => dispatch}/handler-group-manifest.ts | 68 +-- .../remote-selection-flag-rejection.ts | 2 +- .../{ => dispatch}/remote-selection-scope.ts | 0 src/cli/emulator/emulator-command-target.ts | 2 +- src/cli/emulator/emulator-permissions-args.ts | 2 +- src/cli/emulator/emulator.ts | 6 +- src/cli/files/file-absolute-paths.test.ts | 2 +- src/cli/files/file-open-call.ts | 2 +- src/cli/files/file-open-position.ts | 2 +- src/cli/files/file.ts | 6 +- src/cli/handlers/core.test.ts | 204 --------- .../handlers/orchestration-gate-cli.test.ts | 197 --------- ...estration-lifecycle-json-rejection.test.ts | 51 --- src/cli/handlers/orchestration.ts | 34 -- .../worker-start-implicit-coordinator.test.ts | 66 --- src/cli/hosts/environment.ts | 6 +- src/cli/hosts/host-handler-groups.ts | 2 +- .../hosts/host-selector-alternatives.test.ts | 34 -- src/cli/hosts/local-environment-selector.ts | 2 +- src/cli/hosts/managed-server-reconnect.ts | 4 +- src/cli/hosts/managed-server.ts | 6 +- src/cli/hosts/vm-env.ts | 2 +- src/cli/hosts/vm.ts | 2 +- src/cli/{ => hosts}/wsl-distro-cli-refusal.ts | 4 +- src/cli/index-agent-launch.test.ts | 16 +- src/cli/index-file-open-headless.test.ts | 67 --- src/cli/index.test.ts | 14 +- src/cli/index.ts | 24 +- src/cli/jira/jira-handler-group.ts | 2 +- src/cli/jira/jira-target.ts | 4 +- src/cli/jira/jira-write.ts | 8 +- src/cli/jira/jira.ts | 6 +- src/cli/linear/linear-comment-write.ts | 6 +- src/cli/linear/linear-handler-group.ts | 2 +- src/cli/linear/linear-list-issues.ts | 6 +- src/cli/linear/linear-relation-write.ts | 6 +- src/cli/linear/linear-request-builders.ts | 4 +- src/cli/linear/linear-save-issue-request.ts | 2 +- src/cli/linear/linear-save-issue.ts | 4 +- src/cli/linear/linear.ts | 6 +- .../orchestration-session-caller-cli.test.ts | 386 ------------------ .../orchestration/agent-view.test.ts | 6 +- .../orchestration/agent-view.ts | 14 +- .../dispatches}/dispatch-handlers.ts | 14 +- .../gates}/gate-handlers.ts | 19 +- .../identity}/agent-server-route.ts | 9 +- .../orchestration-caller-identity-cli.test.ts | 47 +-- .../orchestration-compatibility-envelope.ts | 6 +- .../orchestration-session-caller-cli.test.ts | 139 +++++++ ...ion-structured-session-no-identity.test.ts | 22 +- .../identity}/session-caller-flags.ts | 8 +- .../identity}/terminal-identity.ts | 7 +- .../messages}/ask-agent-view.ts | 8 +- .../messages}/check-keepalive.ts | 0 .../messages}/message-agent-views.ts | 4 +- .../messages}/message-check-handler.ts | 30 +- .../messages}/message-inbox-handlers.ts | 16 +- .../messages}/message-payload.ts | 4 +- .../messages}/message-send-handler.ts | 31 +- .../orchestration-check-identity.test.ts | 6 +- .../messages}/question-handler.ts | 27 +- .../orchestration/numeric-flags.ts | 4 +- .../orchestration-entry.test.ts} | 24 +- .../orchestration-handler-test-context.ts | 4 +- .../orchestration/orchestration-handlers.ts | 34 ++ .../orchestration.test.ts | 8 +- .../orchestration/receipt-next-text.ts | 0 .../mutation-request-show-handler.ts | 8 +- .../recovery}/mutation-request.ts | 7 +- .../older-runtime-run-binding.test.ts | 7 +- .../recovery}/older-runtime-run-binding.ts | 7 +- .../orchestration-legacy-read-only.test.ts | 10 +- .../orchestration-lifecycle-rejection.test.ts | 77 +--- .../orchestration-mutation-recovery.test.ts | 2 +- .../orchestration-mutation-recovery.ts | 12 +- .../orchestration-recovery-command.test.ts | 0 .../orchestration-recovery-command.ts | 0 .../recovery}/retry-request-flag.ts | 6 +- .../recovery}/runtime-compatibility.ts | 2 +- .../runs}/removed-work-format.ts | 0 .../runs}/reset-handler.ts | 8 +- .../runs}/run-handlers.ts | 16 +- .../orchestration-task-list-brief.test.ts | 10 +- .../tasks}/task-agent-views.ts | 2 +- .../tasks}/task-handlers.ts | 19 +- ...ration-federated-legacy-settlement.test.ts | 8 +- .../workers}/orchestration-worker-cli.test.ts | 10 +- .../orchestration-worker-settlement.ts | 4 +- .../workers}/worker-agent-views.ts | 2 +- .../workers}/worker-launch-handler.ts | 31 +- .../workers}/worker-list-run-scope.ts | 6 +- .../workers}/worker-observation-handlers.ts | 10 +- .../workers}/worker-output.ts | 2 +- .../workers}/worker-release-agent-view.ts | 2 +- .../workers}/worker-start-agent-view.ts | 2 +- .../workers}/worker-terminal-handlers.ts | 14 +- src/cli/output/cli-error-context.ts | 11 + src/cli/{ => output}/cli-error.ts | 32 +- src/cli/{ => output}/cli-exit-code.ts | 0 .../command-result-output.test.ts | 0 src/cli/{ => output}/command-result-output.ts | 6 +- src/cli/{ => output}/stdout-line.ts | 0 src/cli/plugins/authoring/plugin-authoring.ts | 2 +- .../dev-watch/plugin-dev-watch.test.ts | 28 +- src/cli/plugins/dev-watch/plugin-dev-watch.ts | 4 +- src/cli/plugins/plugin-approval-rerun.ts | 4 +- src/cli/plugins/plugin-cli-output.ts | 6 +- src/cli/plugins/plugin-dev-emit.ts | 2 +- src/cli/plugins/plugin-dev-request.ts | 4 +- src/cli/plugins/plugin-handler-groups.ts | 2 +- src/cli/plugins/plugin-install.ts | 2 +- src/cli/plugins/plugin-runtime.ts | 2 +- .../plugins/view/plugin-shot-chrome.test.ts | 6 +- src/cli/plugins/view/plugin-shot-chrome.ts | 2 +- .../plugins/view/plugin-shot-editor.test.ts | 6 +- src/cli/plugins/view/plugin-shot-editor.ts | 4 +- .../plugins/view/plugin-shot-scenario.test.ts | 6 +- src/cli/plugins/view/plugin-shot-scenario.ts | 2 +- src/cli/plugins/view/plugin-view.test.ts | 22 +- src/cli/plugins/view/plugin-view.ts | 4 +- .../{ => profiles}/profile-state-location.ts | 5 +- .../profile-state-recovery-admission.test.ts | 34 +- .../profile-state.test.ts | 25 +- .../{handlers => profiles}/profile-state.ts | 16 +- src/cli/projects/project.ts | 10 +- src/cli/projects/repo.ts | 6 +- .../reference-command-arguments.test.ts | 7 +- .../reference-handler-group.ts | 4 +- src/cli/{ => references}/reference-input.ts | 21 +- src/cli/{handlers => references}/reference.ts | 11 +- src/cli/runtime-client.ts | 10 - .../runtime/cli-lifecycle-handlers.test.ts | 98 +++++ .../cli-lifecycle-handlers.ts} | 21 +- src/cli/runtime/client-recovery.test.ts | 7 +- .../client.test.ts} | 10 +- src/cli/runtime/client.ts | 4 +- .../fixtures/runtime-rpc-fixtures.ts} | 4 +- src/cli/runtime/runtime-source-fence.test.ts | 3 +- src/cli/runtime/serve-bind-flag.ts | 2 +- src/cli/runtime/status-caller.test.ts | 2 +- src/cli/runtime/transport.test.ts | 2 +- .../base64-payload-byte-count.ts | 0 .../cli-screenshot-temp-file.ts | 0 src/cli/serve-electron-flag-parity.test.ts | 54 --- src/cli/server/pair.ts | 6 +- .../server/serve-pairing-handler-groups.ts | 2 +- src/cli/server/serve-reset-identity.ts | 2 +- src/cli/server/serve-restore.ts | 4 +- src/cli/server/serve-service.ts | 2 +- .../search-command-arguments.test.ts | 4 +- .../search-command-arguments.ts | 2 +- src/cli/session-search/search.ts | 4 +- .../skills/bundled-skill-install-command.ts | 6 +- src/cli/skills/skill-guide-get.ts | 4 +- src/cli/skills/skill-guide-host-gate.test.ts | 138 ------- src/cli/skills/skill-guide-host-gate.ts | 2 +- src/cli/skills/skill-sharing.test.ts | 2 +- src/cli/skills/skill-sharing.ts | 6 +- .../skills/skills-reference-selector.test.ts | 41 +- src/cli/skills/skills.ts | 4 +- src/cli/specs/account.ts | 3 +- src/cli/specs/agent-hooks.ts | 4 +- src/cli/specs/agent-launch.ts | 4 +- src/cli/specs/artifacts.ts | 4 +- src/cli/specs/automations.ts | 4 +- src/cli/specs/browser-advanced.ts | 4 +- src/cli/specs/browser-basic.ts | 4 +- src/cli/specs/browser-page-target.ts | 2 +- src/cli/specs/chat.ts | 4 +- src/cli/specs/computer.ts | 4 +- src/cli/specs/connector.ts | 4 +- src/cli/specs/core.ts | 4 +- src/cli/specs/diagnostics.ts | 4 +- src/cli/specs/emulator.ts | 4 +- src/cli/specs/environment.ts | 5 +- src/cli/specs/file.ts | 4 +- src/cli/specs/index.ts | 2 +- src/cli/specs/introspection.ts | 4 +- src/cli/specs/jira.ts | 4 +- src/cli/specs/linear-mcp.ts | 4 +- src/cli/specs/linear.ts | 4 +- src/cli/specs/managed-server.ts | 4 +- .../specs/orchestration-full-record-flag.ts | 2 +- src/cli/specs/orchestration-gate-specs.ts | 3 +- src/cli/specs/orchestration-worker-specs.ts | 3 +- src/cli/specs/orchestration.ts | 3 +- src/cli/specs/pair.ts | 4 +- src/cli/specs/plugin-dev-request.ts | 4 +- src/cli/specs/plugin-install.ts | 4 +- src/cli/specs/plugin-view.ts | 4 +- src/cli/specs/plugin.ts | 5 +- src/cli/specs/ports.ts | 4 +- src/cli/specs/profile-state.ts | 4 +- src/cli/specs/project.ts | 4 +- src/cli/specs/reference.ts | 4 +- src/cli/specs/repo.ts | 4 +- src/cli/specs/search.ts | 3 +- src/cli/specs/serve.ts | 4 +- src/cli/specs/skills.ts | 4 +- src/cli/specs/speech.ts | 4 +- src/cli/specs/terminal-close.ts | 4 +- src/cli/specs/terminal-daemon.ts | 4 +- src/cli/specs/terminal-send.ts | 4 +- src/cli/specs/terminal-set-pane-title.ts | 4 +- src/cli/specs/vm-env.ts | 4 +- src/cli/specs/vm.ts | 4 +- src/cli/specs/worktree-create.ts | 4 +- src/cli/specs/worktree-set.ts | 4 +- src/cli/{handlers => speech}/speech.test.ts | 0 src/cli/{handlers => speech}/speech.ts | 7 +- src/cli/terminals/terminal-close.ts | 6 +- src/cli/terminals/terminal-daemon.ts | 4 +- src/cli/terminals/terminal-selector.ts | 2 +- src/cli/terminals/terminal-send.ts | 8 +- src/cli/terminals/terminal.ts | 6 +- src/cli/workspace-ports/ports.ts | 6 +- .../caller-folder-workspace.ts | 2 +- .../enclosing-workspace-rule.test.ts | 2 +- .../selector-ambiguity-recovery.ts | 0 .../workspace-selection/workspace-selector.ts | 2 +- .../workspaces/folder-workspace-mutations.ts | 4 +- .../index-worktree-wsl-selection.test.ts | 2 +- src/cli/workspaces/workspace-address.ts | 2 +- src/cli/workspaces/worktree-activate.ts | 4 +- .../worktree-create-agent-launch.ts | 2 +- .../worktree-create-parent-selector.ts | 2 +- src/cli/workspaces/worktree-handler-groups.ts | 2 +- .../workspaces/worktree-parent-environment.ts | 4 +- src/cli/workspaces/worktree-parent-fields.ts | 2 +- src/cli/workspaces/worktree-project-target.ts | 2 +- .../worktree-removal-current-refusal.ts | 4 +- .../workspaces/worktree-review-link-flags.ts | 2 +- .../worktree-setup-decision-recovery.ts | 2 +- src/cli/workspaces/worktree.ts | 8 +- .../agent-launch-cwd-cli.test-fixture.ts | 2 +- .../cli-runtime-boundary.test.ts | 7 +- tests/e2e/agent-launch-cli.unit.test.ts | 5 +- ...li-agent-unopened-workspace-resume.spec.ts | 2 +- ...completed-worker-retirement-resume.spec.ts | 2 +- .../completed-worker-retirement-fixture.ts | 2 +- tests/e2e/linear-cli-recovery.unit.test.ts | 12 +- tests/e2e/linear-write-lifetime.unit.test.ts | 2 +- ...ackground-terminal-mount-authority.spec.ts | 2 +- .../e2e/local-cli-terminal-retention.spec.ts | 2 +- ...worktree-visibility-runtime-active.spec.ts | 2 +- ...on-follows-terminal-across-remount.spec.ts | 2 +- .../orchestration-idle-mail-delivery.spec.ts | 31 +- .../orchestration-idle-mail-restore.spec.ts | 2 +- ...y-worker-missing-terminal-recovery.spec.ts | 2 +- ...tration-low-level-dispatch-release.spec.ts | 2 +- ...tion-worker-settlement-release-cli.spec.ts | 2 +- ...tration-worker-terminal-visibility.spec.ts | 2 +- ...ration-worker-transcript-providers.spec.ts | 2 +- ...blocked-navigation-graph-authority.spec.ts | 2 +- ...unopened-workspace-terminal-attach.spec.ts | 2 +- ...ettled-worker-tab-survives-restart.spec.ts | 2 +- ...ened-workspace-agent-single-resume.spec.ts | 2 +- .../e2e/worktree-status-warning.unit.test.ts | 39 +- 321 files changed, 1189 insertions(+), 2569 deletions(-) rename src/cli/{ => arguments}/args-repeatable-flags.test.ts (64%) rename src/cli/{ => arguments}/args.test.ts (92%) rename src/cli/{ => arguments}/args.ts (95%) rename src/cli/{ => arguments}/command-body-input.ts (97%) rename src/cli/{ => arguments}/flags.ts (98%) rename src/cli/{ => arguments}/quote-stripped-json-flag.ts (100%) rename src/cli/{ => arguments}/shell-command-quote.ts (75%) rename src/cli/{handlers => connectors}/connector.ts (97%) rename src/cli/{handlers => diagnostics}/diagnostics.ts (70%) rename src/cli/{handlers/introspection.ts => discovery/agent-context-handlers.ts} (67%) rename src/cli/{ => discovery}/agent-context.ts (94%) rename src/cli/{ => discovery}/command-scoped-flag-help.ts (100%) rename src/cli/{ => discovery}/command-spec.ts (100%) rename src/cli/{ => discovery}/command-suggestion-budget.test.ts (52%) rename src/cli/{ => discovery}/command-suggestion-destructive-families.test.ts (98%) rename src/cli/{ => discovery}/command-suggestion.test.ts (96%) rename src/cli/{ => discovery}/command-suggestion.ts (97%) rename src/cli/{ => discovery}/flag-help-text.ts (100%) rename src/cli/{ => discovery}/help.ts (98%) rename src/cli/{ => discovery}/root-help-text-primary.ts (100%) rename src/cli/{ => discovery}/root-help-text-secondary.ts (100%) rename src/cli/{ => discovery}/vocabulary-policy.ts (97%) rename src/cli/{ => dispatch}/dispatch.ts (93%) rename src/cli/{ => dispatch}/handler-group-manifest.ts (67%) rename src/cli/{ => dispatch}/remote-selection-flag-rejection.ts (92%) rename src/cli/{ => dispatch}/remote-selection-scope.ts (100%) delete mode 100644 src/cli/handlers/core.test.ts delete mode 100644 src/cli/handlers/orchestration-gate-cli.test.ts delete mode 100644 src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts delete mode 100644 src/cli/handlers/orchestration.ts delete mode 100644 src/cli/handlers/orchestration/worker-start-implicit-coordinator.test.ts delete mode 100644 src/cli/hosts/host-selector-alternatives.test.ts rename src/cli/{ => hosts}/wsl-distro-cli-refusal.ts (86%) delete mode 100644 src/cli/index-file-open-headless.test.ts delete mode 100644 src/cli/orchestration-session-caller-cli.test.ts rename src/cli/{handlers => }/orchestration/agent-view.test.ts (98%) rename src/cli/{handlers => }/orchestration/agent-view.ts (91%) rename src/cli/{handlers/orchestration => orchestration/dispatches}/dispatch-handlers.ts (88%) rename src/cli/{handlers/orchestration => orchestration/gates}/gate-handlers.ts (87%) rename src/cli/{handlers/orchestration => orchestration/identity}/agent-server-route.ts (92%) rename src/cli/{handlers => orchestration/identity}/orchestration-caller-identity-cli.test.ts (71%) rename src/cli/{runtime => orchestration/identity}/orchestration-compatibility-envelope.ts (89%) create mode 100644 src/cli/orchestration/identity/orchestration-session-caller-cli.test.ts rename src/cli/{ => orchestration/identity}/orchestration-structured-session-no-identity.test.ts (69%) rename src/cli/{ => orchestration/identity}/session-caller-flags.ts (86%) rename src/cli/{handlers/orchestration => orchestration/identity}/terminal-identity.ts (97%) rename src/cli/{handlers/orchestration => orchestration/messages}/ask-agent-view.ts (93%) rename src/cli/{handlers/orchestration => orchestration/messages}/check-keepalive.ts (100%) rename src/cli/{handlers/orchestration => orchestration/messages}/message-agent-views.ts (98%) rename src/cli/{handlers/orchestration => orchestration/messages}/message-check-handler.ts (84%) rename src/cli/{handlers/orchestration => orchestration/messages}/message-inbox-handlers.ts (89%) rename src/cli/{handlers/orchestration => orchestration/messages}/message-payload.ts (95%) rename src/cli/{handlers/orchestration => orchestration/messages}/message-send-handler.ts (90%) rename src/cli/{handlers => orchestration/messages}/orchestration-check-identity.test.ts (86%) rename src/cli/{handlers/orchestration => orchestration/messages}/question-handler.ts (88%) rename src/cli/{handlers => }/orchestration/numeric-flags.ts (81%) rename src/cli/{index-orchestration.test.ts => orchestration/orchestration-entry.test.ts} (72%) rename src/cli/{handlers => orchestration}/orchestration-handler-test-context.ts (81%) create mode 100644 src/cli/orchestration/orchestration-handlers.ts rename src/cli/{handlers => orchestration}/orchestration.test.ts (91%) rename src/cli/{handlers => }/orchestration/receipt-next-text.ts (100%) rename src/cli/{handlers/orchestration => orchestration/recovery}/mutation-request-show-handler.ts (86%) rename src/cli/{handlers/orchestration => orchestration/recovery}/mutation-request.ts (89%) rename src/cli/{handlers/orchestration => orchestration/recovery}/older-runtime-run-binding.test.ts (86%) rename src/cli/{handlers/orchestration => orchestration/recovery}/older-runtime-run-binding.ts (87%) rename src/cli/{handlers => orchestration/recovery}/orchestration-legacy-read-only.test.ts (93%) rename src/cli/{handlers => orchestration/recovery}/orchestration-lifecycle-rejection.test.ts (69%) rename src/cli/{ => orchestration/recovery}/orchestration-mutation-recovery.test.ts (97%) rename src/cli/{ => orchestration/recovery}/orchestration-mutation-recovery.ts (94%) rename src/cli/{runtime => orchestration/recovery}/orchestration-recovery-command.test.ts (100%) rename src/cli/{runtime => orchestration/recovery}/orchestration-recovery-command.ts (100%) rename src/cli/{ => orchestration/recovery}/retry-request-flag.ts (75%) rename src/cli/{handlers/orchestration => orchestration/recovery}/runtime-compatibility.ts (95%) rename src/cli/{handlers/orchestration => orchestration/runs}/removed-work-format.ts (100%) rename src/cli/{handlers/orchestration => orchestration/runs}/reset-handler.ts (80%) rename src/cli/{handlers/orchestration => orchestration/runs}/run-handlers.ts (92%) rename src/cli/{handlers => orchestration/tasks}/orchestration-task-list-brief.test.ts (83%) rename src/cli/{handlers/orchestration => orchestration/tasks}/task-agent-views.ts (95%) rename src/cli/{handlers/orchestration => orchestration/tasks}/task-handlers.ts (88%) rename src/cli/{handlers => orchestration/workers}/orchestration-federated-legacy-settlement.test.ts (77%) rename src/cli/{handlers => orchestration/workers}/orchestration-worker-cli.test.ts (83%) rename src/cli/{handlers => orchestration/workers}/orchestration-worker-settlement.ts (97%) rename src/cli/{handlers/orchestration => orchestration/workers}/worker-agent-views.ts (99%) rename src/cli/{handlers/orchestration => orchestration/workers}/worker-launch-handler.ts (84%) rename src/cli/{handlers/orchestration => orchestration/workers}/worker-list-run-scope.ts (85%) rename src/cli/{handlers/orchestration => orchestration/workers}/worker-observation-handlers.ts (94%) rename src/cli/{handlers/orchestration => orchestration/workers}/worker-output.ts (99%) rename src/cli/{handlers/orchestration => orchestration/workers}/worker-release-agent-view.ts (99%) rename src/cli/{handlers/orchestration => orchestration/workers}/worker-start-agent-view.ts (99%) rename src/cli/{handlers/orchestration => orchestration/workers}/worker-terminal-handlers.ts (95%) create mode 100644 src/cli/output/cli-error-context.ts rename src/cli/{ => output}/cli-error.ts (89%) rename src/cli/{ => output}/cli-exit-code.ts (100%) rename src/cli/{ => output}/command-result-output.test.ts (100%) rename src/cli/{ => output}/command-result-output.ts (61%) rename src/cli/{ => output}/stdout-line.ts (100%) rename src/cli/{ => profiles}/profile-state-location.ts (62%) rename src/cli/{handlers => profiles}/profile-state-recovery-admission.test.ts (95%) rename src/cli/{handlers => profiles}/profile-state.test.ts (94%) rename src/cli/{handlers => profiles}/profile-state.ts (93%) rename src/cli/{ => references}/reference-command-arguments.test.ts (85%) rename src/cli/{ => references}/reference-handler-group.ts (53%) rename src/cli/{ => references}/reference-input.ts (85%) rename src/cli/{handlers => references}/reference.ts (96%) delete mode 100644 src/cli/runtime-client.ts create mode 100644 src/cli/runtime/cli-lifecycle-handlers.test.ts rename src/cli/{handlers/core.ts => runtime/cli-lifecycle-handlers.ts} (90%) rename src/cli/{runtime-client.test.ts => runtime/client.test.ts} (96%) rename src/cli/{test-fixtures.ts => runtime/fixtures/runtime-rpc-fixtures.ts} (95%) rename src/cli/{ => screenshots}/base64-payload-byte-count.ts (100%) rename src/cli/{ => screenshots}/cli-screenshot-temp-file.ts (100%) delete mode 100644 src/cli/serve-electron-flag-parity.test.ts delete mode 100644 src/cli/skills/skill-guide-host-gate.test.ts rename src/cli/{handlers => speech}/speech.test.ts (100%) rename src/cli/{handlers => speech}/speech.ts (93%) rename src/cli/{ => workspace-selection}/selector-ambiguity-recovery.ts (100%) diff --git a/.github/workflows/computer-e2e.yml b/.github/workflows/computer-e2e.yml index 63f1aefb5f0..51ec40e85fe 100644 --- a/.github/workflows/computer-e2e.yml +++ b/.github/workflows/computer-e2e.yml @@ -97,7 +97,7 @@ 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/command-result-output.test.ts + src/cli/output/command-result-output.test.ts src/cli/computer/computer-state-formatting.test.ts src/cli/index.test.ts src/cli/runtime/envelope-schema.test.ts diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index 42bceb8f00f..db8f524f91a 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -297,7 +297,7 @@ 1 test-no-real-time-wait:tests/e2e/markdown-table-row-backspace.spec.ts 1 test-no-real-time-wait:tests/e2e/native-chat-history-prepend-anchor.spec.ts 3 test-no-real-time-wait:tests/e2e/notification-sound-replay.spec.ts -5 test-no-real-time-wait:tests/e2e/orchestration-idle-mail-delivery.spec.ts +4 test-no-real-time-wait:tests/e2e/orchestration-idle-mail-delivery.spec.ts 1 test-no-real-time-wait:tests/e2e/orchestration-idle-mail-restore.spec.ts 4 test-no-real-time-wait:tests/e2e/paced-terminal-typing.ts 1 test-no-real-time-wait:tests/e2e/paired-client-hosted-browser-double-restart.spec.ts @@ -716,7 +716,7 @@ 1 test-timeout-needs-reason:tests/e2e/markdown-review-selection-performance.spec.ts 1 test-timeout-needs-reason:tests/e2e/mobile-subscribe-idle-hidden-pane-fit.spec.ts 1 test-timeout-needs-reason:tests/e2e/orcad-serve-open-url-on-desktop.spec.ts -10 test-timeout-needs-reason:tests/e2e/orchestration-idle-mail-delivery.spec.ts +9 test-timeout-needs-reason:tests/e2e/orchestration-idle-mail-delivery.spec.ts 1 test-timeout-needs-reason:tests/e2e/orchestration-idle-mail-restore.spec.ts 1 test-timeout-needs-reason:tests/e2e/orchestration-legacy-worker-missing-terminal-recovery.spec.ts 1 test-timeout-needs-reason:tests/e2e/orchestration-worker-settlement-release-cli.spec.ts diff --git a/config/process-host-direct-import-baseline.txt b/config/process-host-direct-import-baseline.txt index f01185f213e..7555a4268c5 100644 --- a/config/process-host-direct-import-baseline.txt +++ b/config/process-host-direct-import-baseline.txt @@ -1,7 +1,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/runtime/cli-lifecycle-handlers.ts src/cli/accounts/interactive-login-interruption.ts src/cli/runtime/launch.ts src/main/agent-hooks/installation/locking/managed-hook-owner-identity.ts diff --git a/config/recurring-timer-baseline.txt b/config/recurring-timer-baseline.txt index 94b6d20e756..c2c05011319 100644 --- a/config/recurring-timer-baseline.txt +++ b/config/recurring-timer-baseline.txt @@ -3,7 +3,7 @@ # collector (file-wide). Not counted: destructuring off a global object, a self-rescheduling setTimeout (it must back off or pause while hidden). # This is a RATCHET: counts may only go DOWN. # Prune after removing intervals: pnpm check:recurring-timer-ratchet --prune -1 src/cli/handlers/orchestration/check-keepalive.ts +1 src/cli/orchestration/messages/check-keepalive.ts 1 src/cli/runtime/mac-app-update-bundle.ts 1 src/cli/runtime/serve-supervised-service.ts 1 src/main/agent-hooks/server/server-opencode-binder.ts diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index f86e851e63c..c7091f45669 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -3648,7 +3648,7 @@ "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/cli/runtime/launch.test.ts src/main/updater/serve-update-handoff.test.ts src/main/updater/updater.headless-serve-install.test.ts src/main/updater/mac-install/updater.mac-install.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/cli/runtime/serve-signal-exit-diagnostic.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/startup/serve-desktop-activation.test.ts src/cli/runtime-client.test.ts src/cli/runtime/websocket-transport.test.ts src/main/runtime/construction/orca-runtime.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/startup/serve-desktop-activation.test.ts src/cli/runtime/client.test.ts src/cli/runtime/websocket-transport.test.ts src/main/runtime/construction/orca-runtime.test.ts", "pnpm exec electron-vite build --mode e2e", "pnpm run test:e2e -- tests/e2e/headless-serve-desktop-activation.spec.ts --workers=1" ], @@ -3658,7 +3658,7 @@ "src/cli/runtime/launch.test.ts", "src/cli/runtime/serve-signal-exit-diagnostic.test.ts", "src/main/startup/serve-desktop-activation.test.ts", - "src/cli/runtime-client.test.ts", + "src/cli/runtime/client.test.ts", "src/cli/runtime/websocket-transport.test.ts", "src/main/runtime/construction/orca-runtime.test.ts", "tests/e2e/headless-serve-desktop-activation.spec.ts" @@ -10570,7 +10570,7 @@ "providers": ["local", "daemon", "ssh", "wsl", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": [], - "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.", + "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. CLI command/orchestration owner cleanup intentionally retires three registrations selected by this gate: two mock-supplied lifecycle/Run-home rejection projection examples and the complete manually assembled JSON failure-envelope example. The JSON-envelope suite, its exact command token/testFiles entry and whole assertion reference are removed; the retired Run-home relay assertion is removed from the retained lifecycle suite. These boundary projection alarms are lost without equivalent replacement. Retained fail-closed settlement and mutation-recovery cases keep their own scope. Pure owner moves do not invalidate unrelated dated receipts, which retain their exact original bytes; no fresh reduced-selector execution, native or remote evidence is claimed.", "motivatingLinks": [ "https://github.com/stablyai/orca/pull/11107#discussion_r3663321387", "https://github.com/stablyai/orca/issues/13858", @@ -10583,8 +10583,8 @@ "oracle": "Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed. Historical prior account (preserved verbatim): Audit3814 deliberately retires60 authored/60 finite cases:53runtime compatibility cases,4native XCTest methods and3Python clipboard methods, including the entire StableElementIndexes suite. Clipboard cuts retire the one-over-cap sample, incoming-offer destruction trace and sequential20-copy replay; actual wire, FD/pipe, startup and Xvfb/GTK boundaries remain without equivalent replacement claims. Accepted losses include narrow terminal-send payload/provider projections, legacy and direct no-op/error permutations, timing/work-count examples, private state/title/activity projections and fixture-driven readiness examples, individually enumerated below. These include real bounded production alarms consciously retired for marginal value; retained failed writes, duplicate submission, stale capture, transcript/ring and allocation fences are not equivalent replacements. No fresh native/remote/browser execution or complete transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3806 deliberately retires40 authored/40 finite runtime compatibility cases, including the terminal-side-effect-facts-part03 headless-snapshots-part02 and agent-status-and-waits-part03 fragments, plus20 scalar Swift precondition sites. Lost runtime alarms include status/title/attention projection examples, simple renderer/headless frame restoration and status waiting outcomes detailed in the accepted-loss ledger. Swift cuts retire duplicate generation-map/schema/navigation/bridge and notification-wrapper assertions; no standalone native program is deleted. These include real bounded production alarms consciously retired for marginal value. Retained races, pending writes/reflow, namespace and waiter ownership are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3798 deliberately retires21 authored/24 finite compatibility cases, including the entire SSH-worktree-lifecycle and repository-project-operations fragments. Accepted losses include navigation-only settings acknowledgement, browser session cleanup and host preservation projections, window positive/policy-state examples, terminal recovery/reload and no-incarnation remint examples, terminal listing compatibility/malformed IDs, directory browse/sort/Windows path smoke, SSH create refusal/manual lineage, recursive parent-folder creation and fork/origin/avatar/icon projections. Real bounded production alarms are consciously retired for marginal value; retained authority races, cleanup/clone ownership, pending waiters, nested-folder and scan invalidation cases are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. 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. Retained assertion references and unchanged receipts keep their original scopes; retired callbacks and archived receipts provide no current coverage.", "commands": [ "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/cli/orchestration/orchestration.test.ts src/cli/orchestration/messages/orchestration-check-identity.test.ts src/cli/orchestration/workers/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/orchestration/recovery/orchestration-lifecycle-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/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", @@ -10594,11 +10594,10 @@ "testFiles": [ "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/cli/orchestration/orchestration.test.ts", + "src/cli/orchestration/recovery/orchestration-lifecycle-rejection.test.ts", + "src/cli/orchestration/messages/orchestration-check-identity.test.ts", + "src/cli/orchestration/workers/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", @@ -10616,20 +10615,15 @@ ] }, { - "file": "src/cli/handlers/orchestration-lifecycle-rejection.test.ts", + "file": "src/cli/orchestration/recovery/orchestration-lifecycle-rejection.test.ts", "assertions": [ "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", - "a Run-home relay rejection reaches the CLI error boundary", "post-verification failure preserves the worker_done mutation identity for recovery" ] }, { - "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", + "file": "src/cli/orchestration/messages/orchestration-check-identity.test.ts", "assertions": ["an empty explicit --terminal is refused before reading a mailbox"] }, { @@ -10804,7 +10798,7 @@ "invariant": "A live Dispatch created by orchestration dispatch can be stopped or abandoned even though it has no supervised worker row. Release must durably record the requested outcome, revoke lifecycle authority, close questions, free the exact assignee identity, and block only the Task whose current Dispatch was released. It must never close the unsupervised terminal process, disturb unrelated or supervised workers, or let a repeat or opposite verb rewrite the persisted outcome.", "oracle": "Audit3678 current-source reassessment removes20 authored/24 finite root-unit cases across7 retained test sources; all10 selected current drivers80 authored/93 finite were read, leaving60 authored/69 finite unchanged. Removed alarms are the in-memory WAL PRAGMA constant, ordinary latest-dispatch/gate-creation inventories, self-reported-failure and explicit-terminal retry policy rows, SSH/unsupported-provider output fallback labels, legacy typing no-op/retain-before-report/manual scheduling rows, exited output status and copied resume-session metadata, incomplete inventory deferral/reset cascade inventory, and nominal release/active-state/corrupt external history/stopped-abandoned outcome/generic close-exception rows. These are intentional coverage losses, not replaced alarms. Retained source includes actual SQLite rollback/custody, mutable transcript/deletion and saved-copy compatibility, cursor mutation, clear lineage, auto-release timing/restart/admission and concurrent recovery seams. Historical KEEP decisions are consciously superseded where stated in decisions.json. Source-only evidence; no runtime, CI, native, provider, remote, mobile/folder or global completion credit. Previous oracle (preserved verbatim): Retained assertion references and unchanged receipts keep their original scopes; retired callbacks and archived receipts provide no current coverage.", "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/worker/manual-dispatch-release.test.ts src/main/runtime/orchestration/db/worker-dispatch/orchestration-worker-dispatch-db.test.ts src/main/runtime/rpc/methods/orchestration/worker/workers-recovery.test.ts src/main/runtime/rpc/methods/orchestration/worker/worker-release.test.ts src/cli/handlers/orchestration-worker-cli.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/worker/manual-dispatch-release.test.ts src/main/runtime/orchestration/db/worker-dispatch/orchestration-worker-dispatch-db.test.ts src/main/runtime/rpc/methods/orchestration/worker/workers-recovery.test.ts src/main/runtime/rpc/methods/orchestration/worker/worker-release.test.ts src/cli/orchestration/workers/orchestration-worker-cli.test.ts --reporter=dot", "pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/orchestration-low-level-dispatch-release.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/orchestration-low-level-dispatch-release.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" ], @@ -10813,7 +10807,7 @@ "src/main/runtime/orchestration/db/worker-dispatch/orchestration-worker-dispatch-db.test.ts", "src/main/runtime/rpc/methods/orchestration/worker/workers-recovery.test.ts", "src/main/runtime/rpc/methods/orchestration/worker/worker-release.test.ts", - "src/cli/handlers/orchestration-worker-cli.test.ts", + "src/cli/orchestration/workers/orchestration-worker-cli.test.ts", "tests/e2e/orchestration-low-level-dispatch-release.spec.ts" ], "assertionRefs": [ diff --git a/config/scripts/workflow/source-routing/pr-e2e-source-routing.mjs b/config/scripts/workflow/source-routing/pr-e2e-source-routing.mjs index 9ff01ceca20..c196d9d44ba 100644 --- a/config/scripts/workflow/source-routing/pr-e2e-source-routing.mjs +++ b/config/scripts/workflow/source-routing/pr-e2e-source-routing.mjs @@ -492,7 +492,7 @@ export const PR_E2E_SOURCE_ROUTES = [ matches: (file) => file === 'tests/e2e/helpers/connector-fake-claude.ts' || (isProductSource(file) && - /^src\/(?:main\/external-conversations\/|main\/runtime\/rpc\/methods\/connector\.ts$|cli\/(?:handlers|specs)\/connector\.ts$|shared\/rpc-contract\/connector-params\.ts$)/.test( + /^src\/(?:main\/external-conversations\/|main\/runtime\/rpc\/methods\/connector\.ts$|cli\/(?:connectors|specs)\/connector\.ts$|shared\/rpc-contract\/connector-params\.ts$)/.test( file )) } diff --git a/src/cli/accounts/account-selection.ts b/src/cli/accounts/account-selection.ts index 4fd07123fd8..8f50070e34a 100644 --- a/src/cli/accounts/account-selection.ts +++ b/src/cli/accounts/account-selection.ts @@ -1,5 +1,5 @@ -import type { HandlerContext } from '../dispatch' -import { printResult } from '../command-result-output' +import type { HandlerContext } from '../dispatch/dispatch' +import { printResult } from '../output/command-result-output' import { RuntimeClientError } from '../runtime/types' import { ANTIGRAVITY_ACCOUNTS_RUNTIME_CAPABILITY } from '../../shared/account-runtime-capabilities' import type { diff --git a/src/cli/accounts/account.test.ts b/src/cli/accounts/account.test.ts index 3b62d5bec6a..218f7fbcacf 100644 --- a/src/cli/accounts/account.test.ts +++ b/src/cli/accounts/account.test.ts @@ -52,8 +52,8 @@ vi.mock('../../shared/windows-console-input', () => ({ })) import { ACCOUNT_HANDLERS } from './account' -import { REPEATED_FLAG_SEPARATOR } from '../args' -import type { HandlerContext } from '../dispatch' +import { REPEATED_FLAG_SEPARATOR } from '../arguments/args' +import type { HandlerContext } from '../dispatch/dispatch' import type { RuntimeClient } from '../runtime/client' import { ACCOUNT_IMPORT_RUNTIME_CAPABILITY, diff --git a/src/cli/accounts/account.ts b/src/cli/accounts/account.ts index d8358e377b9..19d2dd42327 100644 --- a/src/cli/accounts/account.ts +++ b/src/cli/accounts/account.ts @@ -2,11 +2,11 @@ import { spawnProcess } from '@orca/process-host' 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 '../command-result-output' +import type { CommandHandler, HandlerContext } from '../dispatch/dispatch' +import { printResult } from '../output/command-result-output' import { RuntimeClientError } from '../runtime/types' import { stripElectronRunAsNode } from '../runtime/orca-app-executable' -import { rejectRemoteSelectionFlags } from '../remote-selection-flag-rejection' +import { rejectRemoteSelectionFlags } from '../dispatch/remote-selection-flag-rejection' import { buildWslExecArgs, buildWslLoginShellCommand } from '../../shared/wsl-login-shell-command' import { quotePosixShell } from '../../shared/shell/launch/shell-argument-quoting' import { isWindowsFnmDefaultAliasDir } from '../../shared/fnm-default-alias-dirs' diff --git a/src/cli/accounts/data-account-commands.ts b/src/cli/accounts/data-account-commands.ts index 309a77d8783..bad8e71137d 100644 --- a/src/cli/accounts/data-account-commands.ts +++ b/src/cli/accounts/data-account-commands.ts @@ -1,9 +1,9 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import type { HandlerContext } from '../dispatch' -import { REPEATED_FLAG_SEPARATOR } from '../args' -import { printResult } from '../command-result-output' +import type { HandlerContext } from '../dispatch/dispatch' +import { REPEATED_FLAG_SEPARATOR } from '../arguments/args' +import { printResult } from '../output/command-result-output' import { RuntimeClientError } from '../runtime/types' import { DATA_ACCOUNT_RUNTIME_CAPABILITY } from '../../shared/account-runtime-capabilities' import type { RuntimeStatus } from '../../shared/runtime-session-contracts' diff --git a/src/cli/agents/agent-hooks.ts b/src/cli/agents/agent-hooks.ts index 8c36a35c5c4..a663b4847f0 100644 --- a/src/cli/agents/agent-hooks.ts +++ b/src/cli/agents/agent-hooks.ts @@ -1,7 +1,7 @@ import { join } from 'node:path' -import type { CommandHandler } from '../dispatch' -import { printResult } from '../command-result-output' -import { rejectRemoteSelectionFlags } from '../remote-selection-flag-rejection' +import type { CommandHandler } from '../dispatch/dispatch' +import { printResult } from '../output/command-result-output' +import { rejectRemoteSelectionFlags } from '../dispatch/remote-selection-flag-rejection' import { RuntimeClientError } from '../runtime/types' import type { RuntimeClient } from '../runtime/client' import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope' @@ -30,7 +30,7 @@ async function getSettingsPath(): Promise { } async function getProfileStateLocation(): Promise { - const { getActiveProfileStateLocation } = await import('../profile-state-location.js') + const { getActiveProfileStateLocation } = await import('../profiles/profile-state-location.js') return getActiveProfileStateLocation() } diff --git a/src/cli/agents/agent-launch-recovery.ts b/src/cli/agents/agent-launch-recovery.ts index 22537ab0bfb..1c69072bcad 100644 --- a/src/cli/agents/agent-launch-recovery.ts +++ b/src/cli/agents/agent-launch-recovery.ts @@ -3,7 +3,7 @@ import { classifyAgentLaunchReplayRefusal } from '../../shared/agent-launch/cont import { recoverableOrchestrationArgs, resolveOrchestrationCliExecutable -} from '../runtime/orchestration-recovery-command' +} from '../orchestration/recovery/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/agents/agent-launch-request.ts b/src/cli/agents/agent-launch-request.ts index 43126b478a4..cd0e33821f2 100644 --- a/src/cli/agents/agent-launch-request.ts +++ b/src/cli/agents/agent-launch-request.ts @@ -27,7 +27,7 @@ import { getRequiredStringFlag, getRequiredStringFlagAllowingEmpty, rejectValuelessFlag -} from '../flags' +} from '../arguments/flags' import { RuntimeClientError } from '../runtime/types' import type { RuntimeClient } from '../runtime/client' import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope' diff --git a/src/cli/agents/agent-launch-test-fixtures.ts b/src/cli/agents/agent-launch-test-fixtures.ts index d4ab7ebca3b..8756b82d989 100644 --- a/src/cli/agents/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 { okFixture } from '../runtime/fixtures/runtime-rpc-fixtures' export function agentLaunchHostFixture() { return okFixture('req_status', { capabilities: [...AGENT_LAUNCH_RUNTIME_CAPABILITIES] }) diff --git a/src/cli/agents/agent-launch.ts b/src/cli/agents/agent-launch.ts index ec99eeb089c..38b4afdfc14 100644 --- a/src/cli/agents/agent-launch.ts +++ b/src/cli/agents/agent-launch.ts @@ -1,4 +1,4 @@ -import type { CommandHandler } from '../dispatch' +import type { CommandHandler } from '../dispatch/dispatch' import { callAgentLaunch, formatAgentLaunch, @@ -6,8 +6,8 @@ import { parseCliAgent, readCliAgentLaunch } from './agent-launch-request' -import { getRequiredStringFlag } from '../flags' -import { printResult } from '../command-result-output' +import { getRequiredStringFlag } from '../arguments/flags' +import { printResult } from '../output/command-result-output' import { RuntimeClientError } from '../runtime/types' import { getRequiredWorktreeSelector, diff --git a/src/cli/agents/chat.ts b/src/cli/agents/chat.ts index 3d9b6671bbd..af2ede701ac 100644 --- a/src/cli/agents/chat.ts +++ b/src/cli/agents/chat.ts @@ -1,6 +1,6 @@ -import type { CommandHandler } from '../dispatch' -import { getPresentStringFlag, getRequiredStringFlag } from '../flags' -import { printResult } from '../command-result-output' +import type { CommandHandler } from '../dispatch/dispatch' +import { getPresentStringFlag, getRequiredStringFlag } from '../arguments/flags' +import { printResult } from '../output/command-result-output' import { RuntimeClientError } from '../runtime/types' import { readInjectedAgentSessionId } from '../../shared/agent-session/lifecycle/agent-session-caller-env' diff --git a/src/cli/args-repeatable-flags.test.ts b/src/cli/arguments/args-repeatable-flags.test.ts similarity index 64% rename from src/cli/args-repeatable-flags.test.ts rename to src/cli/arguments/args-repeatable-flags.test.ts index 58496640d58..03f54f9bb64 100644 --- a/src/cli/args-repeatable-flags.test.ts +++ b/src/cli/arguments/args-repeatable-flags.test.ts @@ -1,11 +1,6 @@ import { describe, expect, it } from 'vitest' -import { - parseArgs, - validateCommandAndFlags, - REPEATED_FLAG_SEPARATOR, - specPaths, - type CommandSpec -} from './args' +import { parseArgs, validateCommandAndFlags } from './args' +import { specPaths, type CommandSpec } from '../discovery/command-spec' const leaf: CommandSpec = { path: ['example', 'search'], @@ -30,22 +25,11 @@ function flags(argv: string[]) { } describe('command-scoped repeatable flags', () => { - it.each(specPaths(leaf))('keeps values before and between %s %s command words', (...path) => { - const parsed = flags(['--agent', 'a', path[0], '--agent=b', path[1], '--agent', 'c']) - expect(parsed.get('agent')).toBe(['a', 'b', 'c'].join(REPEATED_FLAG_SEPARATOR)) - }) - it('uses the leaf rules for all flags even when the parent has different rules', () => { const parsed = flags(['--path', '/a', 'example', '--path', '/b', 'search', '--path', '/c']) expect(parsed.get('path')).toBe('/c') }) - it('still uses the parent rules when the parent itself is invoked', () => { - expect(flags(['--path', '/a', 'example', '--path=/b']).get('path')).toBe( - ['/a', '/b'].join(REPEATED_FLAG_SEPARATOR) - ) - }) - it.each([ ['--agent', '--agent=b'], ['--agent=a', '--agent', '--agent=b'], @@ -65,10 +49,4 @@ describe('command-scoped repeatable flags', () => { `Flag --${flag} requires a value.` ) }) - - it('preserves empty values and equals signs without reinterpreting flag-like values', () => { - expect( - flags(['example', 'search', '--agent=', '--agent=--help', '--agent=a=b']).get('agent') - ).toBe(['', '--help', 'a=b'].join(REPEATED_FLAG_SEPARATOR)) - }) }) diff --git a/src/cli/args.test.ts b/src/cli/arguments/args.test.ts similarity index 92% rename from src/cli/args.test.ts rename to src/cli/arguments/args.test.ts index f54aee5efc5..e77d0451dd3 100644 --- a/src/cli/args.test.ts +++ b/src/cli/arguments/args.test.ts @@ -1,8 +1,7 @@ import { describe, expect, it } from 'vitest' -import type { CommandSpec } from './args' +import type { CommandSpec } from '../discovery/command-spec' import { - REPEATED_FLAG_SEPARATOR, findCommandSpec, normalizeCommandPositionals, parseArgs, @@ -153,12 +152,6 @@ describe('parseArgs', () => { expect(parsed.positionalFlagConflicts).toEqual([]) }) - it('preserves repeated string flags', () => { - const parsed = parseArgs(['linear', 'label', 'add', '--label', 'Bug', '--label=Regression']) - - expect(parsed.flags.get('label')).toBe(`Bug${REPEATED_FLAG_SEPARATOR}Regression`) - }) - it('does not apply repeated flag encoding to ordinary string flags', () => { const parsed = parseArgs(['linear', 'list', '--workspace', 'old', '--workspace', 'new']) @@ -219,19 +212,6 @@ describe('validateCommandAndFlags', () => { } ] - it('allows global runtime selector flags even when the command spec omits them', () => { - const parsed = parseArgs([ - 'demo', - '--pairing-code', - 'remote-runtime', - '--environment', - 'server', - '--json' - ]) - - expect(() => validateCommandAndFlags(specs, parsed)).not.toThrow() - }) - it.each(['environment', 'pairing-code'])('rejects --%s without a value', (flag) => { const parsed = parseArgs([`--${flag}`, 'demo'], [['demo']]) diff --git a/src/cli/args.ts b/src/cli/arguments/args.ts similarity index 95% rename from src/cli/args.ts rename to src/cli/arguments/args.ts index f7083e67601..fbdf2cdc066 100644 --- a/src/cli/args.ts +++ b/src/cli/arguments/args.ts @@ -1,15 +1,12 @@ -import { RuntimeClientError } from './runtime/types' -import { unknownCommandData, unknownFlagData } from './command-suggestion' -import { specPaths, type CommandSpec } from './command-spec' +import { RuntimeClientError } from '../runtime/types' +import { unknownCommandData, unknownFlagData } from '../discovery/command-suggestion' +import { specPaths, type CommandSpec } from '../discovery/command-spec' import { CLI_BOOLEAN_FLAGS, CLI_GLOBAL_FLAGS, CLI_GLOBAL_VALUE_FLAGS, findCliCommandIndex -} from '../shared/cli-argument-boundary' - -export { specPaths } -export type { CommandSpec } +} from '../../shared/cli-argument-boundary' export type ParsedArgs = { commandPath: string[] @@ -17,11 +14,11 @@ export type ParsedArgs = { positionalFlagConflicts?: string[] } -export const GLOBAL_FLAGS = CLI_GLOBAL_FLAGS +const GLOBAL_FLAGS = CLI_GLOBAL_FLAGS const GLOBAL_VALUE_FLAGS = new Set(CLI_GLOBAL_VALUE_FLAGS) /** Global flags a local-only command offers; it still accepts the remote selectors, only to refuse them. */ export const LOCAL_COMMAND_FLAGS = GLOBAL_FLAGS.filter((flag) => !GLOBAL_VALUE_FLAGS.has(flag)) -export const BOOLEAN_FLAGS = CLI_BOOLEAN_FLAGS +const BOOLEAN_FLAGS = CLI_BOOLEAN_FLAGS export const REPEATED_FLAG_SEPARATOR = '\u0000' const REPEATABLE_STRING_FLAGS = new Set(['label', 'skill']) diff --git a/src/cli/command-body-input.ts b/src/cli/arguments/command-body-input.ts similarity index 97% rename from src/cli/command-body-input.ts rename to src/cli/arguments/command-body-input.ts index edcb03bb537..c228a692ed7 100644 --- a/src/cli/command-body-input.ts +++ b/src/cli/arguments/command-body-input.ts @@ -1,7 +1,7 @@ import { readFile } from 'node:fs/promises' import { isAbsolute, join } from 'node:path' import { getRequiredStringFlag, getRequiredStringFlagAllowingEmpty } from './flags' -import { RuntimeClientError } from './runtime-client' +import { RuntimeClientError } from '../runtime/types' type BodyOptions = { required: boolean diff --git a/src/cli/flags.ts b/src/cli/arguments/flags.ts similarity index 98% rename from src/cli/flags.ts rename to src/cli/arguments/flags.ts index 45b0bbe0047..58612c3a2c7 100644 --- a/src/cli/flags.ts +++ b/src/cli/arguments/flags.ts @@ -1,7 +1,7 @@ -import { RuntimeClientError } from './runtime/types' +import { RuntimeClientError } from '../runtime/types' import { REPEATED_FLAG_SEPARATOR } from './args' import { describeQuoteStrippedJsonFlag } from './quote-stripped-json-flag' -import type { RepoKind } from '../shared/repo-types' +import type { RepoKind } from '../../shared/repo-types' export function getOptionalRepoKind(flags: Map): RepoKind | undefined { const kind = getOptionalStringFlag(flags, 'kind') diff --git a/src/cli/quote-stripped-json-flag.ts b/src/cli/arguments/quote-stripped-json-flag.ts similarity index 100% rename from src/cli/quote-stripped-json-flag.ts rename to src/cli/arguments/quote-stripped-json-flag.ts diff --git a/src/cli/shell-command-quote.ts b/src/cli/arguments/shell-command-quote.ts similarity index 75% rename from src/cli/shell-command-quote.ts rename to src/cli/arguments/shell-command-quote.ts index d1c31632069..f9b45323495 100644 --- a/src/cli/shell-command-quote.ts +++ b/src/cli/arguments/shell-command-quote.ts @@ -1,4 +1,4 @@ -import { quotePosixShell } from '../shared/shell/launch/shell-argument-quoting' +import { quotePosixShell } from '../../shared/shell/launch/shell-argument-quoting' export function quoteCliCommandArgument(value: string): string { if (/^[a-zA-Z0-9._:/@-]+$/.test(value)) { diff --git a/src/cli/artifacts/artifacts.ts b/src/cli/artifacts/artifacts.ts index 28aa1498561..22c3f9faa7b 100644 --- a/src/cli/artifacts/artifacts.ts +++ b/src/cli/artifacts/artifacts.ts @@ -17,11 +17,11 @@ import { ARTIFACT_SHARING_DISABLED_MESSAGE, ARTIFACT_SHARING_DISABLED_NEXT_STEPS } from '../../shared/artifacts/artifact-sharing-gate' -import type { CommandHandler, HandlerContext } from '../dispatch' -import { rejectRemoteSelectionFlags } from '../remote-selection-flag-rejection' +import type { CommandHandler, HandlerContext } from '../dispatch/dispatch' +import { rejectRemoteSelectionFlags } from '../dispatch/remote-selection-flag-rejection' import { RuntimeClientError } from '../runtime/types' import { formatArtifactListPage, formatArtifactShared } from './artifact-format' -import { printResult } from '../command-result-output' +import { printResult } from '../output/command-result-output' function stringFlag(ctx: HandlerContext, name: string): string | undefined { const value = ctx.flags.get(name) diff --git a/src/cli/automations/automation-format.ts b/src/cli/automations/automation-format.ts index 48b410f1ecf..db20ad8398f 100644 --- a/src/cli/automations/automation-format.ts +++ b/src/cli/automations/automation-format.ts @@ -7,7 +7,7 @@ import type { AutomationOwnerPrecondition } from '../../shared/automations/owner 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 { quoteCliCommandArgument } from '../arguments/shell-command-quote' export type AutomationListPayload = { automations: Automation[] diff --git a/src/cli/automations/automation-handler-flags.ts b/src/cli/automations/automation-handler-flags.ts index ed329212abe..9bf5550bfb6 100644 --- a/src/cli/automations/automation-handler-flags.ts +++ b/src/cli/automations/automation-handler-flags.ts @@ -18,7 +18,7 @@ import { getOptionalPositiveIntegerFlag, getOptionalStringFlag, getRequiredStringFlag -} from '../flags' +} from '../arguments/flags' import { RuntimeClientError } from '../runtime/types' const PRESET_TRIGGERS = new Set(['hourly', 'daily', 'weekdays', 'weekly']) diff --git a/src/cli/automations/automations.ts b/src/cli/automations/automations.ts index bc4a714e397..cd5138b3457 100644 --- a/src/cli/automations/automations.ts +++ b/src/cli/automations/automations.ts @@ -10,7 +10,7 @@ import { } from '../../shared/work-items/task-source-context' import type { AutomationDestination } from '../../shared/automations/ownership/automation-owner-precondition' import type { ProjectHostSetup } from '../../shared/project-types' -import type { CommandHandler } from '../dispatch' +import type { CommandHandler } from '../dispatch/dispatch' import { formatAutomationList, formatAutomationRemoved, @@ -20,12 +20,12 @@ import { formatAutomationShow, type AutomationShowPayload } from './automation-format' -import { printResult } from '../command-result-output' +import { printResult } from '../output/command-result-output' import { getOptionalPositiveIntegerFlag, getOptionalStringFlag, getRequiredStringFlag -} from '../flags' +} from '../arguments/flags' import { resolveAutomationDestination, routeAutomationCreate } from './automation-destination' import { AUTOMATION_RUNS_PAGE_SIZE, diff --git a/src/cli/browser/browser-capture.ts b/src/cli/browser/browser-capture.ts index fbb42e2b209..44481206d5c 100644 --- a/src/cli/browser/browser-capture.ts +++ b/src/cli/browser/browser-capture.ts @@ -7,9 +7,9 @@ import type { BrowserInterceptedRequest, BrowserNetworkLogResult } from '../../shared/browser/runtime/runtime-browser-contracts' -import type { CommandHandler } from '../dispatch' -import { printResult } from '../command-result-output' -import { getOptionalPositiveIntegerFlag, getOptionalStringFlag } from '../flags' +import type { CommandHandler } from '../dispatch/dispatch' +import { printResult } from '../output/command-result-output' +import { getOptionalPositiveIntegerFlag, getOptionalStringFlag } from '../arguments/flags' import { getBrowserCommandTarget } from './browser-command-target' export const BROWSER_CAPTURE_HANDLERS: Record = { diff --git a/src/cli/browser/browser-command-target.ts b/src/cli/browser/browser-command-target.ts index 9f9faef38ad..cad6d2825d8 100644 --- a/src/cli/browser/browser-command-target.ts +++ b/src/cli/browser/browser-command-target.ts @@ -1,7 +1,7 @@ import { BROWSER_EXPECT_URL_RUNTIME_CAPABILITY } from '../../shared/browser/runtime/browser-runtime-capabilities' import type { RuntimeStatus } from '../../shared/runtime-types' -import { getOptionalStringFlag, getPresentStringFlag } from '../flags' -import type { RuntimeClient } from '../runtime-client' +import { getOptionalStringFlag, getPresentStringFlag } from '../arguments/flags' +import type { RuntimeClient } from '../runtime/client' import { RuntimeClientError } from '../runtime/types' import { assertLocalCwdWorktreeSelector } from '../hosts/local-environment-selector' import { diff --git a/src/cli/browser/browser-cookie.ts b/src/cli/browser/browser-cookie.ts index e43f53780a6..61d55698b29 100644 --- a/src/cli/browser/browser-cookie.ts +++ b/src/cli/browser/browser-cookie.ts @@ -3,13 +3,13 @@ import type { BrowserCookieGetResult, BrowserCookieSetResult } from '../../shared/browser/runtime/runtime-browser-contracts' -import type { CommandHandler } from '../dispatch' -import { printResult } from '../command-result-output' +import type { CommandHandler } from '../dispatch/dispatch' +import { printResult } from '../output/command-result-output' import { getOptionalStringFlag, getRequiredStringFlag, getRequiredStringFlagAllowingEmpty -} from '../flags' +} from '../arguments/flags' import { RuntimeClientError } from '../runtime/types' import { getBrowserCommandTarget } from './browser-command-target' diff --git a/src/cli/browser/browser-empty-values.test.ts b/src/cli/browser/browser-empty-values.test.ts index 8fe411e3611..0460a073ea1 100644 --- a/src/cli/browser/browser-empty-values.test.ts +++ b/src/cli/browser/browser-empty-values.test.ts @@ -1,49 +1,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as RuntimeTypes from '../runtime/types' const callMock = vi.fn() -vi.mock('../runtime/types', () => { - 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 { RuntimeClientError, RuntimeRpcFailureError } -}) - -vi.mock('../runtime-client', async () => { +vi.mock('../runtime/client', () => { class RuntimeClient { call = callMock getCliStatus = vi.fn() openOrca = vi.fn() } - - const { RuntimeClientError, RuntimeRpcFailureError } = - await vi.importMock('../runtime/types') - - return { - RuntimeClient, - RuntimeClientError, - RuntimeRpcFailureError - } + return { RuntimeClient } }) import { main } from '../index' -import { okFixture, queueFixtures } from '../test-fixtures' describe('orca cli storage set preserves an empty value', () => { beforeEach(() => { @@ -55,57 +23,7 @@ describe('orca cli storage set preserves an empty value', () => { vi.restoreAllMocks() }) - it('passes an empty --value through to browser.storage.local.set', async () => { - queueFixtures(callMock, okFixture('req_storage_local_set', { success: true })) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main( - ['storage', 'local', 'set', '--key', 'flag', '--value', '', '--worktree', 'all', '--json'], - '/tmp/not-an-orca-worktree' - ) - - expect(callMock).toHaveBeenCalledTimes(1) - expect(callMock).toHaveBeenCalledWith('browser.storage.local.set', { - key: 'flag', - value: '', - worktree: undefined - }) - }) - - it('passes an empty --value through to browser.storage.session.set', async () => { - queueFixtures(callMock, okFixture('req_storage_session_set', { success: true })) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main( - ['storage', 'session', 'set', '--key', 'flag', '--value', '', '--worktree', 'all', '--json'], - '/tmp/not-an-orca-worktree' - ) - - expect(callMock).toHaveBeenCalledTimes(1) - expect(callMock).toHaveBeenCalledWith('browser.storage.session.set', { - key: 'flag', - value: '', - worktree: undefined - }) - }) - // PowerShell 5.1 drops empty native arguments; equals form preserves them. - it('passes an empty --value= (equals form) through to browser.storage.local.set', async () => { - queueFixtures(callMock, okFixture('req_storage_local_set', { success: true })) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main( - ['storage', 'local', 'set', '--key=flag', '--value=', '--worktree', 'all', '--json'], - '/tmp/not-an-orca-worktree' - ) - - expect(callMock).toHaveBeenCalledTimes(1) - expect(callMock).toHaveBeenCalledWith('browser.storage.local.set', { - key: 'flag', - value: '', - worktree: undefined - }) - }) it('still rejects an empty --key before RPC dispatch', async () => { const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) @@ -150,40 +68,6 @@ describe('orca cli cookie set and set credentials preserve an empty value', () = vi.restoreAllMocks() }) - it('passes an empty --value through to browser.cookie.set', async () => { - queueFixtures(callMock, okFixture('req_cookie_set', { success: true })) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main( - ['cookie', 'set', '--name', 'sid', '--value', '', '--worktree', 'all', '--json'], - '/tmp/not-an-orca-worktree' - ) - - expect(callMock).toHaveBeenCalledTimes(1) - expect(callMock).toHaveBeenCalledWith('browser.cookie.set', { - name: 'sid', - value: '', - worktree: undefined - }) - }) - - it('passes an empty --pass through to browser.setCredentials', async () => { - queueFixtures(callMock, okFixture('req_set_credentials', { success: true })) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main( - ['set', 'credentials', '--user', 'token', '--pass', '', '--worktree', 'all', '--json'], - '/tmp/not-an-orca-worktree' - ) - - expect(callMock).toHaveBeenCalledTimes(1) - expect(callMock).toHaveBeenCalledWith('browser.setCredentials', { - user: 'token', - pass: '', - worktree: undefined - }) - }) - it('still rejects an empty --name before RPC dispatch', async () => { const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) const priorExitCode = process.exitCode @@ -216,34 +100,3 @@ describe('orca cli cookie set and set credentials preserve an empty value', () = process.exitCode = priorExitCode }) }) - -describe('orca cli fill and select preserve an empty value', () => { - beforeEach(() => { - callMock.mockReset() - process.exitCode = undefined - }) - - afterEach(() => { - vi.restoreAllMocks() - }) - - it.each([ - ['fill', 'browser.fill', { filled: 'ref_1' }], - ['select', 'browser.select', { selected: 'ref_1' }] - ])('passes an empty --value through %s to %s', async (command, method, result) => { - queueFixtures(callMock, okFixture(`req_${command}`, result)) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main( - [command, '--element', 'ref_1', '--value', '', '--worktree', 'all', '--json'], - '/tmp/not-an-orca-worktree' - ) - - expect(callMock).toHaveBeenCalledTimes(1) - expect(callMock).toHaveBeenCalledWith(method, { - element: 'ref_1', - value: '', - worktree: undefined - }) - }) -}) diff --git a/src/cli/browser/browser-env.ts b/src/cli/browser/browser-env.ts index 640a15691a9..2c6ce4ec792 100644 --- a/src/cli/browser/browser-env.ts +++ b/src/cli/browser/browser-env.ts @@ -2,15 +2,15 @@ import type { BrowserGeolocationResult, BrowserViewportResult } from '../../shared/browser/runtime/runtime-browser-contracts' -import type { CommandHandler } from '../dispatch' -import { printResult } from '../command-result-output' +import type { CommandHandler } from '../dispatch/dispatch' +import { printResult } from '../output/command-result-output' import { getOptionalStringFlag, getRequiredFiniteNumber, getRequiredPositiveNumber, getRequiredStringFlag, getRequiredStringFlagAllowingEmpty -} from '../flags' +} from '../arguments/flags' import { RuntimeClientError } from '../runtime/types' import { getBrowserCommandTarget } from './browser-command-target' diff --git a/src/cli/browser/browser-expect-url.test.ts b/src/cli/browser/browser-expect-url.test.ts index bbc7b0a5dfc..934bef74e50 100644 --- a/src/cli/browser/browser-expect-url.test.ts +++ b/src/cli/browser/browser-expect-url.test.ts @@ -8,7 +8,7 @@ const { callMock, runtimeClientConstructorMock, serveOrcaAppMock, getDefaultUser getDefaultUserDataPathMock: vi.fn(() => '/tmp/orca-user-data') })) -vi.mock('../runtime-client', async () => { +vi.mock('../runtime/client', async () => { const { createRuntimeClientModuleMock } = await import('../index-test-harness.js') return createRuntimeClientModuleMock({ callMock, @@ -18,62 +18,24 @@ vi.mock('../runtime-client', async () => { }) }) +vi.mock('../runtime/launch', async (importOriginal) => ({ + ...(await importOriginal>()), + serveOrcaApp: serveOrcaAppMock +})) + +vi.mock('../runtime/metadata', async (importOriginal) => ({ + ...(await importOriginal>()), + getDefaultUserDataPath: getDefaultUserDataPathMock +})) + import { BROWSER_EXPECT_URL_RUNTIME_CAPABILITY } from '../../shared/browser/runtime/browser-runtime-capabilities' -import { RPC_PARAMS_BY_METHOD } from '../../shared/rpc-contract/rpc-params-catalog.generated' + import { main } from '../index' -import { okFixture } from '../test-fixtures' +import { okFixture } from '../runtime/fixtures/runtime-rpc-fixtures' const EXPECT_URL = 'https://example.com/chat/a' // Every guarded command, with arguments that reach its RPC and the RPC it must carry the URL on. -const GUARDED_COMMANDS: Record< - string, - { args: string[]; method: keyof typeof RPC_PARAMS_BY_METHOD } -> = { - back: { args: [], method: 'browser.back' }, - check: { args: ['--element', '@e1'], method: 'browser.check' }, - clear: { args: ['--element', '@e1'], method: 'browser.clear' }, - click: { args: ['--element', '@e1'], method: 'browser.click' }, - dblclick: { args: ['--element', '@e1'], method: 'browser.dblclick' }, - 'dialog accept': { args: [], method: 'browser.dialogAccept' }, - 'dialog dismiss': { args: [], method: 'browser.dialogDismiss' }, - download: { args: ['--selector', '@e1', '--path', '/tmp/f'], method: 'browser.download' }, - drag: { args: ['--from', '@e1', '--to', '@e2'], method: 'browser.drag' }, - eval: { args: ['--expression', '1'], method: 'browser.eval' }, - fill: { args: ['--element', '@e1', '--value', 'x'], method: 'browser.fill' }, - find: { - args: ['--locator', 'role', '--value', 'button', '--action', 'click'], - method: 'browser.find' - }, - focus: { args: ['--element', '@e1'], method: 'browser.focus' }, - forward: { args: [], method: 'browser.forward' }, - goto: { args: ['--url', 'https://example.com/b'], method: 'browser.goto' }, - hover: { args: ['--element', '@e1'], method: 'browser.hover' }, - inserttext: { args: ['--text', 'x'], method: 'browser.keyboardInsertText' }, - keypress: { args: ['--key', 'Enter'], method: 'browser.keypress' }, - 'mouse down': { args: [], method: 'browser.mouseDown' }, - 'mouse move': { args: ['--x', '1', '--y', '2'], method: 'browser.mouseMove' }, - 'mouse up': { args: [], method: 'browser.mouseUp' }, - 'mouse wheel': { args: ['--dy', '1'], method: 'browser.mouseWheel' }, - reload: { args: [], method: 'browser.reload' }, - scroll: { args: ['--direction', 'down'], method: 'browser.scroll' }, - scrollintoview: { args: ['--element', '@e1'], method: 'browser.scrollIntoView' }, - select: { args: ['--element', '@e1', '--value', 'x'], method: 'browser.select' }, - 'select-all': { args: ['--element', '@e1'], method: 'browser.selectAll' }, - 'storage local clear': { args: [], method: 'browser.storage.local.clear' }, - 'storage local set': { - args: ['--key', 'k', '--value', 'v'], - method: 'browser.storage.local.set' - }, - 'storage session clear': { args: [], method: 'browser.storage.session.clear' }, - 'storage session set': { - args: ['--key', 'k', '--value', 'v'], - method: 'browser.storage.session.set' - }, - type: { args: ['--input', 'x'], method: 'browser.type' }, - uncheck: { args: ['--element', '@e1'], method: 'browser.check' }, - upload: { args: ['--element', '@e1', '--files', '/tmp/f'], method: 'browser.upload' } -} function answerRuntime(capabilities: string[]): void { callMock.mockImplementation(async (method: string) => @@ -96,24 +58,6 @@ describe('--expect-url', () => { process.exitCode = undefined }) - it.each(Object.entries(GUARDED_COMMANDS))( - '%s sends the URL on an RPC whose schema keeps it', - async (path, { args, method }) => { - answerRuntime([BROWSER_EXPECT_URL_RUNTIME_CAPABILITY]) - - await main( - [...path.split(' '), ...args, '--page', 'page-1', '--expect-url', EXPECT_URL, '--json'], - '/tmp/not-an-orca-worktree' - ) - - const call = callMock.mock.calls.find(([called]) => called === method) - expect(call?.[1]).toMatchObject({ page: 'page-1', expectUrl: EXPECT_URL }) - expect(RPC_PARAMS_BY_METHOD[method]?.parse(call?.[1])).toMatchObject({ - expectUrl: EXPECT_URL - }) - } - ) - it('refuses before acting when the runtime would drop the field', async () => { answerRuntime(['runtime.v1']) diff --git a/src/cli/browser/browser-extension.ts b/src/cli/browser/browser-extension.ts index 1bd892c8eaf..c498e550bb3 100644 --- a/src/cli/browser/browser-extension.ts +++ b/src/cli/browser/browser-extension.ts @@ -2,9 +2,9 @@ import type { BrowserExtensionSummaryListResult, BrowserExtensionReloadResult } from '../../shared/browser/extensions/browser-extension-types' -import type { CommandHandler } from '../dispatch' -import { getPresentStringFlag } from '../flags' -import { printResult } from '../command-result-output' +import type { CommandHandler } from '../dispatch/dispatch' +import { getPresentStringFlag } from '../arguments/flags' +import { printResult } from '../output/command-result-output' import { resolveRepoPathArgument } from '../projects/repo-path-arguments' export const BROWSER_EXTENSION_HANDLERS: Record = { diff --git a/src/cli/browser/browser-format.ts b/src/cli/browser/browser-format.ts index 2bcd1f0796a..b6e80a3a3d5 100644 --- a/src/cli/browser/browser-format.ts +++ b/src/cli/browser/browser-format.ts @@ -1,6 +1,6 @@ import { readBrowserActionEffects } from '../../shared/browser-action-effects' import { formatBrowserPasskeyRequest } from '../../shared/browser-passkey-request' -import { writeCliScreenshotTempFile } from '../cli-screenshot-temp-file' +import { writeCliScreenshotTempFile } from '../screenshots/cli-screenshot-temp-file' import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope' import { formatBrowserAnnotationsAsMarkdown } from '../../shared/browser/annotations/browser-annotation-output' import type { diff --git a/src/cli/browser/browser-handler-groups.ts b/src/cli/browser/browser-handler-groups.ts index 356fcc787f7..04b9636a26a 100644 --- a/src/cli/browser/browser-handler-groups.ts +++ b/src/cli/browser/browser-handler-groups.ts @@ -1,5 +1,5 @@ import { ORCA_BROWSER_CLI_COMMAND_KEYS } from '../../shared/orca-browser-cli-commands' -import type { HandlerGroup } from '../handler-group-manifest' +import type { HandlerGroup } from '../dispatch/handler-group-manifest' export const BROWSER_HANDLER_GROUPS: readonly HandlerGroup[] = [ { diff --git a/src/cli/browser/browser-identity.ts b/src/cli/browser/browser-identity.ts index 1b1936b0d03..b8687030cc6 100644 --- a/src/cli/browser/browser-identity.ts +++ b/src/cli/browser/browser-identity.ts @@ -5,9 +5,9 @@ import type { } from '../../shared/browser-user-agent-mode' import { BROWSER_IDENTITY_RUNTIME_CAPABILITY } from '../../shared/browser/runtime/browser-runtime-capabilities' import type { RuntimeStatus } from '../../shared/runtime-session-contracts' -import type { CommandHandler, HandlerContext } from '../dispatch' -import { getRequiredStringFlag } from '../flags' -import { printResult } from '../command-result-output' +import type { CommandHandler, HandlerContext } from '../dispatch/dispatch' +import { getRequiredStringFlag } from '../arguments/flags' +import { printResult } from '../output/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 f156b0a01dc..ddbbdd53154 100644 --- a/src/cli/browser/browser-interact.ts +++ b/src/cli/browser/browser-interact.ts @@ -12,16 +12,16 @@ import type { BrowserTypeResult, BrowserUploadResult } from '../../shared/browser/runtime/runtime-browser-contracts' -import type { CommandHandler } from '../dispatch' +import type { CommandHandler } from '../dispatch/dispatch' import { resolveRepoPathArgument } from '../projects/repo-path-arguments' -import { printResult } from '../command-result-output' +import { printResult } from '../output/command-result-output' import { getOptionalNumberFlag, getOptionalStringFlag, getRequiredFiniteNumber, getRequiredStringFlag, getRequiredStringFlagAllowingEmpty -} from '../flags' +} from '../arguments/flags' import { getBrowserCommandTarget } from './browser-command-target' const checkHandler = diff --git a/src/cli/browser/browser-nav.ts b/src/cli/browser/browser-nav.ts index aff3df6d7b7..8fba9f4e6b8 100644 --- a/src/cli/browser/browser-nav.ts +++ b/src/cli/browser/browser-nav.ts @@ -10,14 +10,14 @@ import type { BrowserSnapshotResult, BrowserWaitResult } from '../../shared/browser/runtime/runtime-browser-contracts' -import type { CommandHandler } from '../dispatch' +import type { CommandHandler } from '../dispatch/dispatch' import { formatScreenshot, formatSnapshot, saveBrowserScreenshot } from './browser-format' -import { printResult } from '../command-result-output' +import { printResult } from '../output/command-result-output' import { getOptionalPositiveIntegerFlag, getOptionalStringFlag, getRequiredStringFlag -} from '../flags' +} from '../arguments/flags' import { RuntimeClientError } from '../runtime/types' import { getBrowserCommandTarget } from './browser-command-target' import { browserWaitRequestTimeoutMs } from '../../shared/browser-wait-timeout' diff --git a/src/cli/browser/browser-profile.ts b/src/cli/browser/browser-profile.ts index 38773dbc618..0b7bf227ed9 100644 --- a/src/cli/browser/browser-profile.ts +++ b/src/cli/browser/browser-profile.ts @@ -6,14 +6,14 @@ import type { BrowserTabProfileShowResult, BrowserTabSetProfileResult } from '../../shared/browser/runtime/runtime-browser-contracts' -import type { CommandHandler } from '../dispatch' -import { getOptionalStringFlag, getRequiredStringFlag } from '../flags' +import type { CommandHandler } from '../dispatch/dispatch' +import { getOptionalStringFlag, getRequiredStringFlag } from '../arguments/flags' import { formatBrowserProfileList, formatTabProfileClone, formatTabProfileShow } from './browser-format' -import { printResult } from '../command-result-output' +import { printResult } from '../output/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 76e98a0883d..b4917a5153f 100644 --- a/src/cli/browser/browser-storage.ts +++ b/src/cli/browser/browser-storage.ts @@ -1,6 +1,6 @@ -import type { CommandHandler } from '../dispatch' -import { printResult } from '../command-result-output' -import { getRequiredStringFlag, getRequiredStringFlagAllowingEmpty } from '../flags' +import type { CommandHandler } from '../dispatch/dispatch' +import { printResult } from '../output/command-result-output' +import { getRequiredStringFlag, getRequiredStringFlagAllowingEmpty } from '../arguments/flags' import { getBrowserCommandTarget } from './browser-command-target' export const BROWSER_STORAGE_HANDLERS: Record = { diff --git a/src/cli/browser/browser-tab.ts b/src/cli/browser/browser-tab.ts index 06d79c4821b..3cf37c338c4 100644 --- a/src/cli/browser/browser-tab.ts +++ b/src/cli/browser/browser-tab.ts @@ -5,20 +5,20 @@ import type { BrowserTabShowResult, BrowserTabSwitchResult } from '../../shared/browser/runtime/runtime-browser-contracts' -import type { CommandHandler } from '../dispatch' +import type { CommandHandler } from '../dispatch/dispatch' import { formatTabAnnotations, formatTabList, formatTabListWithProfiles, formatTabShow } from './browser-format' -import { printResult } from '../command-result-output' +import { printResult } from '../output/command-result-output' import { getOptionalNonNegativeIntegerFlag, getOptionalStringFlag, getPresentStringFlag, getRequiredStringFlag -} from '../flags' +} from '../arguments/flags' import { RuntimeClientError } from '../runtime/types' import { isBrowserTabSplitDirection } from '../../shared/browser-tab-split-direction' import { getBrowserWorktreeSelector } from '../workspace-selection/workspace-selector' diff --git a/src/cli/computer/computer-action-flags.ts b/src/cli/computer/computer-action-flags.ts index 9fb948e40dd..3d5134617c9 100644 --- a/src/cli/computer/computer-action-flags.ts +++ b/src/cli/computer/computer-action-flags.ts @@ -10,7 +10,7 @@ import { getOptionalStringFlag, getRequiredStringFlag, getRequiredStringFlagAllowingEmpty -} from '../flags' +} from '../arguments/flags' import { RuntimeClientError } from '../runtime/types' import { validateDragTarget, diff --git a/src/cli/computer/computer-command-target.ts b/src/cli/computer/computer-command-target.ts index 96cca961ee0..6aab1247787 100644 --- a/src/cli/computer/computer-command-target.ts +++ b/src/cli/computer/computer-command-target.ts @@ -1,7 +1,7 @@ import type { ComputerAppQuery } from '../../shared/computer-use-runtime-types' import type { RuntimeClient } from '../runtime/client' import { RuntimeClientError } from '../runtime/types' -import { getOptionalStringFlag, getRequiredStringFlag } from '../flags' +import { getOptionalStringFlag, getRequiredStringFlag } from '../arguments/flags' import { getBrowserWorktreeSelector } from '../workspace-selection/workspace-selector' export type ComputerCliTarget = { diff --git a/src/cli/computer/computer-format.ts b/src/cli/computer/computer-format.ts index 05b6dd980ac..a00f42f2ce7 100644 --- a/src/cli/computer/computer-format.ts +++ b/src/cli/computer/computer-format.ts @@ -1,6 +1,6 @@ -import { writeCliScreenshotTempFile } from '../cli-screenshot-temp-file' -import { formatBase64PayloadByteCount } from '../base64-payload-byte-count' -import { quoteCliCommandArgument } from '../shell-command-quote' +import { writeCliScreenshotTempFile } from '../screenshots/cli-screenshot-temp-file' +import { formatBase64PayloadByteCount } from '../screenshots/base64-payload-byte-count' +import { quoteCliCommandArgument } from '../arguments/shell-command-quote' import type { ComputerActionMetadata, ComputerActionResult, diff --git a/src/cli/computer/computer-state-formatting.test.ts b/src/cli/computer/computer-state-formatting.test.ts index 881f68fa892..3098d0a1bf1 100644 --- a/src/cli/computer/computer-state-formatting.test.ts +++ b/src/cli/computer/computer-state-formatting.test.ts @@ -16,7 +16,7 @@ vi.mock('../runtime/client', () => { }) import { main } from '../index' -import { okFixture, queueFixtures } from '../test-fixtures' +import { okFixture, queueFixtures } from '../runtime/fixtures/runtime-rpc-fixtures' describe('orca computer get-app-state formatting', () => { let screenshotDirectory: string diff --git a/src/cli/computer/computer.ts b/src/cli/computer/computer.ts index 30dd04b8f7f..af844b40ef5 100644 --- a/src/cli/computer/computer.ts +++ b/src/cli/computer/computer.ts @@ -5,12 +5,12 @@ import type { ComputerProviderCapabilities, ComputerSnapshotResult } from '../../shared/computer-use-runtime-types' -import type { CommandHandler } from '../dispatch' +import type { CommandHandler } from '../dispatch/dispatch' import { getOptionalPositiveIntegerFlag, getOptionalStringFlag, getRequiredStringFlag -} from '../flags' +} from '../arguments/flags' import { queryComputerTreeText } from './computer-tree-query' import { RuntimeClientError } from '../runtime/types' import { @@ -19,7 +19,7 @@ import { formatListApps, formatListWindows } from './computer-format' -import { printResult } from '../command-result-output' +import { printResult } from '../output/command-result-output' import { getComputerCommandTarget } from './computer-command-target' import { getComputerActionObserveFlags, diff --git a/src/cli/handlers/connector.ts b/src/cli/connectors/connector.ts similarity index 97% rename from src/cli/handlers/connector.ts rename to src/cli/connectors/connector.ts index d87fdfbd58b..9458436358b 100644 --- a/src/cli/handlers/connector.ts +++ b/src/cli/connectors/connector.ts @@ -1,14 +1,14 @@ import { randomUUID } from 'node:crypto' import { ORCA_SCRUB_SAFE_PANE_ENV } from '../../shared/agent-hook-listener/transport/agent-hook-scrub-safe-env' import { CONNECTOR_REPLY_UNAVAILABLE } from '../../shared/rpc-contract/connector-params' -import type { CommandHandler, HandlerContext } from '../dispatch' +import type { CommandHandler, HandlerContext } from '../dispatch/dispatch' import { getOptionalNonNegativeIntegerFlag, getOptionalStringFlag, getRequiredStringFlag -} from '../flags' -import { printResult } from '../command-result-output' -import { RuntimeClientError } from '../runtime-client' +} from '../arguments/flags' +import { printResult } from '../output/command-result-output' +import { RuntimeClientError } from '../runtime/types' import { getRequiredWorktreeSelector } from '../workspace-selection/workspace-selector' type ConnectorDelivery = { outcome: string; reason?: string; reopened?: boolean } diff --git a/src/cli/handlers/diagnostics.ts b/src/cli/diagnostics/diagnostics.ts similarity index 70% rename from src/cli/handlers/diagnostics.ts rename to src/cli/diagnostics/diagnostics.ts index 1bfe5ab1ac9..a5d62f885f1 100644 --- a/src/cli/handlers/diagnostics.ts +++ b/src/cli/diagnostics/diagnostics.ts @@ -1,7 +1,7 @@ import type { MemorySnapshot } from '../../shared/process-stats-types' -import type { CommandHandler } from '../dispatch' -import { formatMemorySnapshot } from '../diagnostics/memory-snapshot-format' -import { printResult } from '../command-result-output' +import type { CommandHandler } from '../dispatch/dispatch' +import { formatMemorySnapshot } from './memory-snapshot-format' +import { printResult } from '../output/command-result-output' import { TERMINAL_DAEMON_HANDLERS } from '../terminals/terminal-daemon' export const DIAGNOSTICS_HANDLERS: Record = { diff --git a/src/cli/handlers/introspection.ts b/src/cli/discovery/agent-context-handlers.ts similarity index 67% rename from src/cli/handlers/introspection.ts rename to src/cli/discovery/agent-context-handlers.ts index abc55372b80..86344a8030e 100644 --- a/src/cli/handlers/introspection.ts +++ b/src/cli/discovery/agent-context-handlers.ts @@ -1,6 +1,6 @@ -import type { CommandHandler } from '../dispatch' -import { COMMAND_SPECS } from '../specs' -import { buildAgentContext, formatAgentContextSummary } from '../agent-context' +import type { CommandHandler } from '../dispatch/dispatch' +import { COMMAND_SPECS } from '../specs/index' +import { buildAgentContext, formatAgentContextSummary } from './agent-context' export const INTROSPECTION_HANDLERS: Record = { // Keep schema output runtime-free so it works offline and over SSH. diff --git a/src/cli/agent-context.ts b/src/cli/discovery/agent-context.ts similarity index 94% rename from src/cli/agent-context.ts rename to src/cli/discovery/agent-context.ts index 224eec63b5a..f960abd979c 100644 --- a/src/cli/agent-context.ts +++ b/src/cli/discovery/agent-context.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from './args' -import { effectiveAllowedFlags } from './args' +import type { CommandSpec } from './command-spec' +import { effectiveAllowedFlags } from '../arguments/args' const SCHEMA_VERSION = 1 diff --git a/src/cli/command-scoped-flag-help.ts b/src/cli/discovery/command-scoped-flag-help.ts similarity index 100% rename from src/cli/command-scoped-flag-help.ts rename to src/cli/discovery/command-scoped-flag-help.ts diff --git a/src/cli/command-spec.ts b/src/cli/discovery/command-spec.ts similarity index 100% rename from src/cli/command-spec.ts rename to src/cli/discovery/command-spec.ts diff --git a/src/cli/command-suggestion-budget.test.ts b/src/cli/discovery/command-suggestion-budget.test.ts similarity index 52% rename from src/cli/command-suggestion-budget.test.ts rename to src/cli/discovery/command-suggestion-budget.test.ts index d2d1d7256f5..14a0b90a2d1 100644 --- a/src/cli/command-suggestion-budget.test.ts +++ b/src/cli/discovery/command-suggestion-budget.test.ts @@ -1,8 +1,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import * as distance from '../shared/edit-distance' + import { suggestCommands, unknownFlagData } from './command-suggestion' import type { CommandSpec } from './command-spec' -import { COMMAND_SPECS } from './specs' const specs: CommandSpec[] = [ { path: ['list'], summary: '', usage: '', allowedFlags: [] }, @@ -12,28 +11,6 @@ const specs: CommandSpec[] = [ afterEach(() => vi.restoreAllMocks()) describe('suggestion distance work', () => { - it('does no distance calculations for a long command, including destructive intent', () => { - const spy = vi.spyOn(distance, 'levenshtein') - expect(suggestCommands(specs, ['x'.repeat(32_768)])).toEqual([]) - expect(spy).not.toHaveBeenCalled() - }) - - it('keeps the live destructive alias registry out of long-input distance work', () => { - const spy = vi.spyOn(distance, 'levenshtein') - expect(suggestCommands(COMMAND_SPECS, ['emulator', 'x'.repeat(32_768)])).toEqual([]) - expect(spy).not.toHaveBeenCalled() - }) - - it('does no distance calculations for a long flag but still lists valid flags', () => { - const spy = vi.spyOn(distance, 'levenshtein') - expect(unknownFlagData('x'.repeat(32_768), ['worktree', 'json'])).toEqual({ - validFlags: ['json', 'worktree'], - suggestions: [], - nextSteps: ['Valid flags: --json, --worktree'] - }) - expect(spy).not.toHaveBeenCalled() - }) - it('keeps the inclusive three-edit suggestion boundary', () => { expect(suggestCommands(specs, ['listxxx'])).toEqual(['list']) expect(unknownFlagData('jsonxxx', ['json']).suggestions).toEqual(['json']) diff --git a/src/cli/command-suggestion-destructive-families.test.ts b/src/cli/discovery/command-suggestion-destructive-families.test.ts similarity index 98% rename from src/cli/command-suggestion-destructive-families.test.ts rename to src/cli/discovery/command-suggestion-destructive-families.test.ts index eb797d8abc9..46b9183d8f9 100644 --- a/src/cli/command-suggestion-destructive-families.test.ts +++ b/src/cli/discovery/command-suggestion-destructive-families.test.ts @@ -1,8 +1,8 @@ import { describe, expect, it } from 'vitest' -import { normalizeCommandPositionals, parseArgs, validateCommandAndFlags } from './args' +import { normalizeCommandPositionals, parseArgs, validateCommandAndFlags } from '../arguments/args' import type { CommandSpec } from './command-spec' import { suggestCommands, unknownCommandData } from './command-suggestion' -import { COMMAND_SPECS } from './specs' +import { COMMAND_SPECS } from '../specs/index' const blocked = [ ['orchestration resume', 'orchestration reset'], diff --git a/src/cli/command-suggestion.test.ts b/src/cli/discovery/command-suggestion.test.ts similarity index 96% rename from src/cli/command-suggestion.test.ts rename to src/cli/discovery/command-suggestion.test.ts index 803be19271d..caf95cdcc0e 100644 --- a/src/cli/command-suggestion.test.ts +++ b/src/cli/discovery/command-suggestion.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' -import type { CommandSpec } from './args' +import type { CommandSpec } from './command-spec' import { suggestCommands } from './command-suggestion' const specs: CommandSpec[] = [ diff --git a/src/cli/command-suggestion.ts b/src/cli/discovery/command-suggestion.ts similarity index 97% rename from src/cli/command-suggestion.ts rename to src/cli/discovery/command-suggestion.ts index d0e96637f1b..e36ff52b97d 100644 --- a/src/cli/command-suggestion.ts +++ b/src/cli/discovery/command-suggestion.ts @@ -1,6 +1,6 @@ import { specPaths, type CommandSpec } from './command-spec' -import { levenshtein } from '../shared/edit-distance' -import { isTerminalHandle } from '../shared/terminal-handle-prefix' +import { levenshtein } from '../../shared/edit-distance' +import { isTerminalHandle } from '../../shared/terminal-handle-prefix' const SUGGESTION_THRESHOLD = 3 const MAX_SUGGESTIONS = 3 diff --git a/src/cli/flag-help-text.ts b/src/cli/discovery/flag-help-text.ts similarity index 100% rename from src/cli/flag-help-text.ts rename to src/cli/discovery/flag-help-text.ts diff --git a/src/cli/help.ts b/src/cli/discovery/help.ts similarity index 98% rename from src/cli/help.ts rename to src/cli/discovery/help.ts index 65afa70ee63..5c10500e047 100644 --- a/src/cli/help.ts +++ b/src/cli/discovery/help.ts @@ -1,5 +1,10 @@ -import type { CommandSpec } from './args' -import { findCommandSpec, isCommandGroup, matches, supportsBrowserPageFlag } from './args' +import type { CommandSpec } from './command-spec' +import { + findCommandSpec, + isCommandGroup, + matches, + supportsBrowserPageFlag +} from '../arguments/args' import { unknownCommandData } from './command-suggestion' import { formatCommandScopedFlagHelp } from './command-scoped-flag-help' import { FLAG_HELP_TEXT } from './flag-help-text' diff --git a/src/cli/root-help-text-primary.ts b/src/cli/discovery/root-help-text-primary.ts similarity index 100% rename from src/cli/root-help-text-primary.ts rename to src/cli/discovery/root-help-text-primary.ts diff --git a/src/cli/root-help-text-secondary.ts b/src/cli/discovery/root-help-text-secondary.ts similarity index 100% rename from src/cli/root-help-text-secondary.ts rename to src/cli/discovery/root-help-text-secondary.ts diff --git a/src/cli/vocabulary-policy.ts b/src/cli/discovery/vocabulary-policy.ts similarity index 97% rename from src/cli/vocabulary-policy.ts rename to src/cli/discovery/vocabulary-policy.ts index 6728068a2ef..69caea8a3da 100644 --- a/src/cli/vocabulary-policy.ts +++ b/src/cli/discovery/vocabulary-policy.ts @@ -1,4 +1,4 @@ -import type { CommandSpec } from './args' +import type { CommandSpec } from './command-spec' // Grandfather existing verb divergences to avoid breaking compatibility. diff --git a/src/cli/dispatch.ts b/src/cli/dispatch/dispatch.ts similarity index 93% rename from src/cli/dispatch.ts rename to src/cli/dispatch/dispatch.ts index 47373b0e7b4..e7174df3ad7 100644 --- a/src/cli/dispatch.ts +++ b/src/cli/dispatch/dispatch.ts @@ -1,5 +1,5 @@ -import type { RuntimeClient } from './runtime-client' -import { RuntimeClientError } from './runtime/types' +import type { RuntimeClient } from '../runtime/client' +import { RuntimeClientError } from '../runtime/types' import { HANDLER_GROUPS, type HandlerGroup } from './handler-group-manifest' export type HandlerContext = { diff --git a/src/cli/handler-group-manifest.ts b/src/cli/dispatch/handler-group-manifest.ts similarity index 67% rename from src/cli/handler-group-manifest.ts rename to src/cli/dispatch/handler-group-manifest.ts index 2ebbc3ec79e..b1671a76bb2 100644 --- a/src/cli/handler-group-manifest.ts +++ b/src/cli/dispatch/handler-group-manifest.ts @@ -1,12 +1,12 @@ import type { CommandHandler } from './dispatch' -import { BROWSER_HANDLER_GROUPS } from './browser/browser-handler-groups' -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 './server/serve-pairing-handler-groups' -import { PLUGIN_HANDLER_GROUPS } from './plugins/plugin-handler-groups' -import { HOST_HANDLER_GROUPS } from './hosts/host-handler-groups' -import { WORKTREE_HANDLER_GROUPS } from './workspaces/worktree-handler-groups' +import { BROWSER_HANDLER_GROUPS } from '../browser/browser-handler-groups' +import { JIRA_HANDLER_GROUP } from '../jira/jira-handler-group' +import { LINEAR_HANDLER_GROUP } from '../linear/linear-handler-group' +import { REFERENCE_HANDLER_GROUP } from '../references/reference-handler-group' +import { SERVE_PAIRING_HANDLER_GROUPS } from '../server/serve-pairing-handler-groups' +import { PLUGIN_HANDLER_GROUPS } from '../plugins/plugin-handler-groups' +import { HOST_HANDLER_GROUPS } from '../hosts/host-handler-groups' +import { WORKTREE_HANDLER_GROUPS } from '../workspaces/worktree-handler-groups' export type HandlerGroup = { name: string @@ -22,24 +22,24 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [ { name: 'core', keys: ['claude-teams', 'open', 'serve', 'status'], - load: async () => (await import('./handlers/core.js')).CORE_HANDLERS + load: async () => (await import('../runtime/cli-lifecycle-handlers.js')).CORE_HANDLERS }, ...SERVE_PAIRING_HANDLER_GROUPS, { name: 'serve-reset-identity', keys: ['serve reset-identity'], load: async () => - (await import('./server/serve-reset-identity.js')).SERVE_RESET_IDENTITY_HANDLERS + (await import('../server/serve-reset-identity.js')).SERVE_RESET_IDENTITY_HANDLERS }, { name: 'serve-service', keys: ['serve service install', 'serve service status', 'serve service uninstall'], - load: async () => (await import('./server/serve-service.js')).SERVE_SERVICE_HANDLERS + load: async () => (await import('../server/serve-service.js')).SERVE_SERVICE_HANDLERS }, { name: 'account', keys: ['account add', 'account list', 'account select', 'account rm'], - load: async () => (await import('./accounts/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('./artifacts/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('./automations/automations.js')).AUTOMATION_HANDLERS + load: async () => (await import('../automations/automations.js')).AUTOMATION_HANDLERS }, { name: 'project', @@ -76,7 +76,7 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [ 'project setup-update', 'project setup-delete' ], - load: async () => (await import('./projects/project.js')).PROJECT_HANDLERS + load: async () => (await import('../projects/project.js')).PROJECT_HANDLERS }, { name: 'repo', @@ -90,13 +90,13 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [ 'repo set-base-ref', 'repo search-refs' ], - load: async () => (await import('./projects/repo.js')).REPO_HANDLERS + load: async () => (await import('../projects/repo.js')).REPO_HANDLERS }, ...WORKTREE_HANDLER_GROUPS, { name: 'file', keys: ['file open', 'file diff', 'file open-changed'], - load: async () => (await import('./files/file.js')).FILE_HANDLERS + load: async () => (await import('../files/file.js')).FILE_HANDLERS }, { name: 'terminal', @@ -114,7 +114,7 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [ 'terminal close', 'terminal split' ], - load: async () => (await import('./terminals/terminal.js')).TERMINAL_HANDLERS + load: async () => (await import('../terminals/terminal.js')).TERMINAL_HANDLERS }, ...BROWSER_HANDLER_GROUPS, { @@ -154,7 +154,8 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [ 'orchestration gate-list', 'orchestration reset' ], - load: async () => (await import('./handlers/orchestration.js')).ORCHESTRATION_HANDLERS + load: async () => + (await import('../orchestration/orchestration-handlers.js')).ORCHESTRATION_HANDLERS }, { name: 'emulator', @@ -176,7 +177,7 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [ 'emulator ax', 'emulator logcat' ], - load: async () => (await import('./emulator/emulator.js')).EMULATOR_HANDLERS + load: async () => (await import('../emulator/emulator.js')).EMULATOR_HANDLERS }, { name: 'computer', @@ -196,22 +197,22 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [ 'computer paste-text', 'computer set-value' ], - load: async () => (await import('./computer/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('./agents/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('./agents/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('./agents/chat.js')).CHAT_HANDLERS + load: async () => (await import('../agents/chat.js')).CHAT_HANDLERS }, { name: 'connector', @@ -224,48 +225,49 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [ 'connector watch', 'connector reply' ], - load: async () => (await import('./handlers/connector.js')).CONNECTOR_HANDLERS + load: async () => (await import('../connectors/connector.js')).CONNECTOR_HANDLERS }, { name: 'profile-state', keys: ['profile state exports', 'profile state rollback'], - load: async () => (await import('./handlers/profile-state.js')).PROFILE_STATE_HANDLERS + load: async () => (await import('../profiles/profile-state.js')).PROFILE_STATE_HANDLERS }, { name: 'diagnostics', keys: ['diagnostics memory', 'terminal-daemon status', 'terminal-daemon restart'], - load: async () => (await import('./handlers/diagnostics.js')).DIAGNOSTICS_HANDLERS + load: async () => (await import('../diagnostics/diagnostics.js')).DIAGNOSTICS_HANDLERS }, { name: 'speech', keys: ['speech openai-key status', 'speech openai-key set', 'speech openai-key clear'], - load: async () => (await import('./handlers/speech.js')).SPEECH_HANDLERS + load: async () => (await import('../speech/speech.js')).SPEECH_HANDLERS }, { name: 'introspection', keys: ['agent-context'], - load: async () => (await import('./handlers/introspection.js')).INTROSPECTION_HANDLERS + load: async () => + (await import('../discovery/agent-context-handlers.js')).INTROSPECTION_HANDLERS }, ...HOST_HANDLER_GROUPS, { name: 'skill-sharing', keys: ['skills installed', 'skills share'], - load: async () => (await import('./skills/skill-sharing.js')).SKILL_SHARING_HANDLERS + load: async () => (await import('../skills/skill-sharing.js')).SKILL_SHARING_HANDLERS }, ...PLUGIN_HANDLER_GROUPS, { name: 'skills', keys: ['skills list', 'skills get', 'skills install', 'skills update'], - load: async () => (await import('./skills/skills.js')).SKILL_HANDLERS + load: async () => (await import('../skills/skills.js')).SKILL_HANDLERS }, { name: 'search', keys: ['search'], - load: async () => (await import('./session-search/search.js')).SEARCH_HANDLERS + load: async () => (await import('../session-search/search.js')).SEARCH_HANDLERS }, { name: 'ports', keys: ['ports'], - load: async () => (await import('./workspace-ports/ports.js')).PORTS_HANDLERS + load: async () => (await import('../workspace-ports/ports.js')).PORTS_HANDLERS } ] diff --git a/src/cli/remote-selection-flag-rejection.ts b/src/cli/dispatch/remote-selection-flag-rejection.ts similarity index 92% rename from src/cli/remote-selection-flag-rejection.ts rename to src/cli/dispatch/remote-selection-flag-rejection.ts index 86b560ad111..6aa6f3bfce2 100644 --- a/src/cli/remote-selection-flag-rejection.ts +++ b/src/cli/dispatch/remote-selection-flag-rejection.ts @@ -1,4 +1,4 @@ -import { RuntimeClientError } from './runtime/types' +import { RuntimeClientError } from '../runtime/types' // Local-only command families reject explicit runtime selectors rather than silently ignoring them. export const REMOTE_SELECTION_FLAGS = ['environment', 'pairing-code'] as const diff --git a/src/cli/remote-selection-scope.ts b/src/cli/dispatch/remote-selection-scope.ts similarity index 100% rename from src/cli/remote-selection-scope.ts rename to src/cli/dispatch/remote-selection-scope.ts diff --git a/src/cli/emulator/emulator-command-target.ts b/src/cli/emulator/emulator-command-target.ts index 6f5a28b6935..eafb7ba4ce1 100644 --- a/src/cli/emulator/emulator-command-target.ts +++ b/src/cli/emulator/emulator-command-target.ts @@ -1,7 +1,7 @@ import type { RuntimeClient } from '../runtime/client' import { RuntimeClientError } from '../runtime/types' import { assertLocalCwdWorktreeSelector } from '../hosts/local-environment-selector' -import { getOptionalStringFlag } from '../flags' +import { getOptionalStringFlag } from '../arguments/flags' import { resolveCallerPaneWorktreeSelector, type WorkspaceSelectionPurpose diff --git a/src/cli/emulator/emulator-permissions-args.ts b/src/cli/emulator/emulator-permissions-args.ts index 0f02c5342ad..531290dbb6f 100644 --- a/src/cli/emulator/emulator-permissions-args.ts +++ b/src/cli/emulator/emulator-permissions-args.ts @@ -1,4 +1,4 @@ -import { getOptionalStringFlag, getRequiredStringFlag } from '../flags' +import { getOptionalStringFlag, getRequiredStringFlag } from '../arguments/flags' import { RuntimeClientError } from '../runtime/types' export type EmulatorPermissionRequest = { diff --git a/src/cli/emulator/emulator.ts b/src/cli/emulator/emulator.ts index 8619fecfef8..5cc8d80fc40 100644 --- a/src/cli/emulator/emulator.ts +++ b/src/cli/emulator/emulator.ts @@ -1,14 +1,14 @@ -import type { CommandHandler } from '../dispatch' +import type { CommandHandler } from '../dispatch/dispatch' import { formatLogcat } from './emulator-logcat-format' import { parseEmulatorPermissionRequest } from './emulator-permissions-args' -import { printResult } from '../command-result-output' +import { printResult } from '../output/command-result-output' import { resolveRepoPathArgument } from '../projects/repo-path-arguments' import { getOptionalPositiveIntegerFlag, getOptionalStringFlag, getRequiredFiniteNumber, getRequiredStringFlag -} from '../flags' +} from '../arguments/flags' import { getEmulatorCommandTarget } from './emulator-command-target' import { RuntimeClientError } from '../runtime/types' import { EMULATOR_ATTACH_RPC_TIMEOUT_MS } from '../../shared/emulator-attach-timeouts' diff --git a/src/cli/files/file-absolute-paths.test.ts b/src/cli/files/file-absolute-paths.test.ts index baf48ac7834..5ec565d517f 100644 --- a/src/cli/files/file-absolute-paths.test.ts +++ b/src/cli/files/file-absolute-paths.test.ts @@ -14,7 +14,7 @@ vi.mock('../runtime/client', () => { }) import { main } from '../index' -import { buildWorktree, okFixture, queueFixtures } from '../test-fixtures' +import { buildWorktree, okFixture, queueFixtures } from '../runtime/fixtures/runtime-rpc-fixtures' describe('absolute file CLI paths', () => { beforeEach(() => { diff --git a/src/cli/files/file-open-call.ts b/src/cli/files/file-open-call.ts index e50028a7b48..645f71aa037 100644 --- a/src/cli/files/file-open-call.ts +++ b/src/cli/files/file-open-call.ts @@ -1,5 +1,5 @@ import type { RuntimeFileOpenResult } from '../../shared/file-access/runtime-editor-file-open' -import type { HandlerContext } from '../dispatch' +import type { HandlerContext } from '../dispatch/dispatch' import { RuntimeClientError } from '../runtime/types' import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope' diff --git a/src/cli/files/file-open-position.ts b/src/cli/files/file-open-position.ts index 0975d8ea4f4..d98a4c0597f 100644 --- a/src/cli/files/file-open-position.ts +++ b/src/cli/files/file-open-position.ts @@ -1,5 +1,5 @@ import type { RuntimeFileOpenPosition } from '../../shared/file-access/runtime-editor-file-open' -import { getOptionalPositiveIntegerFlag } from '../flags' +import { getOptionalPositiveIntegerFlag } from '../arguments/flags' import { RuntimeClientError } from '../runtime/types' export function getFileOpenPosition( diff --git a/src/cli/files/file.ts b/src/cli/files/file.ts index 40308b481a2..7631507de8d 100644 --- a/src/cli/files/file.ts +++ b/src/cli/files/file.ts @@ -5,9 +5,9 @@ import type { RuntimeWorktreeRecord } from '../../shared/runtime-worktree-contra 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 '../command-result-output' +import type { CommandHandler, HandlerContext } from '../dispatch/dispatch' +import { getOptionalStringFlag, getRequiredStringFlag } from '../arguments/flags' +import { printResult } from '../output/command-result-output' import { RuntimeClientError } from '../runtime/types' import { callFileOpen } from './file-open-call' import { diff --git a/src/cli/handlers/core.test.ts b/src/cli/handlers/core.test.ts deleted file mode 100644 index d8bed3fe14c..00000000000 --- a/src/cli/handlers/core.test.ts +++ /dev/null @@ -1,204 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { spawnMock, reclaimStaleLockMock, printReclaimResultMock } = vi.hoisted(() => ({ - spawnMock: vi.fn(), - reclaimStaleLockMock: vi.fn(), - printReclaimResultMock: vi.fn() -})) - -vi.mock('node:child_process', () => ({ spawn: spawnMock })) -vi.mock('../../main/orcad/orcad-stale-lock-reclaim.js', () => ({ - reclaimStaleOrcadInstanceLock: reclaimStaleLockMock, - printOrcadStaleLockReclaimResult: printReclaimResultMock -})) - -// Exclude the socket runtime graph; this handler needs only errors and serveOrcaApp. -vi.mock('../runtime-client', () => ({ - RuntimeClientError: class RuntimeClientError extends Error { - readonly code: string - constructor(code: string, message: string) { - super(message) - this.code = code - } - }, - serveOrcaApp: vi.fn() -})) - -import { CORE_HANDLERS } from './core' -import type { HandlerContext } from '../dispatch' -import type { RuntimeClient } from '../runtime-client' - -type SpawnEnv = Record - -// Emit exit on the next microtask so the spawned-process promise settles deterministically. -function mockClaudeChild(): { once: (event: string, cb: (...args: unknown[]) => void) => unknown } { - const child = { - once(event: string, cb: (...args: unknown[]) => void) { - if (event === 'exit') { - queueMicrotask(() => cb(0, null)) - } - return child - } - } - return child -} - -describe('orca claude-teams CLI handler', () => { - const isWindows = process.platform === 'win32' - let previousRunAsNode: string | undefined - let previousPaneKey: string | undefined - let previousExitCode: typeof process.exitCode - - const callMock = vi.fn() - const client = { call: callMock } as unknown as RuntimeClient - - function runClaudeTeams(): Promise { - const ctx: HandlerContext = { - flags: new Map(), - client, - cwd: '/tmp/repo', - json: false, - rawArgs: [] - } - return CORE_HANDLERS['claude-teams'](ctx) - } - - beforeEach(() => { - reclaimStaleLockMock.mockReset() - reclaimStaleLockMock.mockRejectedValue(new Error('Unexpected stale-lock reclaim')) - printReclaimResultMock.mockReset() - spawnMock.mockReset() - spawnMock.mockImplementation(() => mockClaudeChild()) - callMock.mockReset() - callMock.mockResolvedValue({ - result: { - launch: { env: { CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS: '1', PATH: '/shim:/usr/bin' } } - } - }) - previousRunAsNode = process.env.ELECTRON_RUN_AS_NODE - previousPaneKey = process.env.ORCA_PANE_KEY - previousExitCode = process.exitCode - // Reproduce the Electron-as-Node flag inherited from the orca launcher. - process.env.ELECTRON_RUN_AS_NODE = '1' - process.env.ORCA_PANE_KEY = 'tab-1:leaf-1' - }) - - afterEach(() => { - if (previousRunAsNode === undefined) { - delete process.env.ELECTRON_RUN_AS_NODE - } else { - process.env.ELECTRON_RUN_AS_NODE = previousRunAsNode - } - if (previousPaneKey === undefined) { - delete process.env.ORCA_PANE_KEY - } else { - process.env.ORCA_PANE_KEY = previousPaneKey - } - process.exitCode = previousExitCode - }) - - // Windows refuses the command before reaching child-process creation. - it.skipIf(isWindows)( - 'does not leak ELECTRON_RUN_AS_NODE into the spawned claude child', - async () => { - await runClaudeTeams() - - expect(spawnMock).toHaveBeenCalledWith('claude', expect.any(Array), expect.any(Object)) - const spawnEnv = spawnMock.mock.calls.at(-1)?.[2].env as SpawnEnv - expect(spawnEnv.ELECTRON_RUN_AS_NODE).toBeUndefined() - - const prepareLaunchEnv = (callMock.mock.calls[0][1] as { env: SpawnEnv }).env - expect(prepareLaunchEnv.ELECTRON_RUN_AS_NODE).toBeUndefined() - } - ) - - it.skipIf(isWindows)( - 'still forwards non-Electron parent env and prepareLaunch env to claude', - async () => { - const previousMarker = process.env.ORCA_TEST_MARKER - process.env.ORCA_TEST_MARKER = 'keep-me' - try { - await runClaudeTeams() - } finally { - if (previousMarker === undefined) { - delete process.env.ORCA_TEST_MARKER - } else { - process.env.ORCA_TEST_MARKER = previousMarker - } - } - - const spawnEnv = spawnMock.mock.calls.at(-1)?.[2].env as SpawnEnv - expect(spawnEnv.ORCA_TEST_MARKER).toBe('keep-me') - expect(spawnEnv.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS).toBe('1') - expect(spawnEnv.PATH).toBe('/shim:/usr/bin') - } - ) - - it.skipIf(isWindows)('removes managed auth variables before spawning Claude', async () => { - const previousApiKey = process.env.ANTHROPIC_API_KEY - process.env.ANTHROPIC_API_KEY = 'sk-ant-inherited' - callMock.mockResolvedValueOnce({ - result: { - launch: { - env: { - CLAUDE_CONFIG_DIR: '/managed/claude', - CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS: '1' - }, - envToDelete: ['ANTHROPIC_API_KEY'] - } - } - }) - try { - await runClaudeTeams() - } finally { - if (previousApiKey === undefined) { - delete process.env.ANTHROPIC_API_KEY - } else { - process.env.ANTHROPIC_API_KEY = previousApiKey - } - } - - const spawnEnv = spawnMock.mock.calls.at(-1)?.[2].env as SpawnEnv - expect(spawnEnv.ANTHROPIC_API_KEY).toBeUndefined() - expect(spawnEnv.CLAUDE_CONFIG_DIR).toBe('/managed/claude') - }) - - it.skipIf(isWindows)('preserves API-key auth when no managed deletion is requested', async () => { - const previousApiKey = process.env.ANTHROPIC_API_KEY - process.env.ANTHROPIC_API_KEY = 'sk-ant-system' - try { - await runClaudeTeams() - } finally { - if (previousApiKey === undefined) { - delete process.env.ANTHROPIC_API_KEY - } else { - process.env.ANTHROPIC_API_KEY = previousApiKey - } - } - - const spawnEnv = spawnMock.mock.calls.at(-1)?.[2].env as SpawnEnv - expect(spawnEnv.ANTHROPIC_API_KEY).toBe('sk-ant-system') - }) - - // #32177: an empty --data-root must never fall back to the default profile's lock. - it('refuses `orca serve --reclaim-stale-lock` with a --data-root that names no directory', async () => { - const ctx: HandlerContext = { - flags: new Map([ - ['reclaim-stale-lock', true], - ['data-root', true], - ['yes', true] - ]), - client, - cwd: '/tmp', - json: true, - rawArgs: [] - } - await expect(CORE_HANDLERS.serve(ctx)).rejects.toMatchObject({ - code: 'invalid_argument', - message: - '--data-root expects a directory. Usage: orca serve --reclaim-stale-lock [--data-root ] [--yes] [--json]' - }) - expect(reclaimStaleLockMock).not.toHaveBeenCalled() - expect(printReclaimResultMock).not.toHaveBeenCalled() - }) -}) diff --git a/src/cli/handlers/orchestration-gate-cli.test.ts b/src/cli/handlers/orchestration-gate-cli.test.ts deleted file mode 100644 index 90a47131c42..00000000000 --- a/src/cli/handlers/orchestration-gate-cli.test.ts +++ /dev/null @@ -1,197 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { callMock, getTerminalHandleMock } = vi.hoisted(() => ({ - callMock: vi.fn(), - getTerminalHandleMock: vi.fn() -})) - -vi.mock('../runtime/client', async () => { - // Error formatting uses instanceof, so preserve the production error classes. - const { RuntimeClientError, RuntimeRpcFailureError } = await import('../runtime/types.js') - class RuntimeClient { - readonly isRemote = false - call = callMock - getCliStatus = vi.fn() - openOrca = vi.fn() - } - return { - RuntimeClient, - RuntimeClientError, - RuntimeRpcFailureError, - serveOrcaApp: vi.fn(), - getDefaultUserDataPath: vi.fn(() => '/tmp/orca-user-data') - } -}) - -vi.mock('../runtime/metadata', async (importOriginal) => ({ - ...(await importOriginal>()), - getDefaultUserDataPath: vi.fn(() => '/tmp/orca-user-data') -})) - -vi.mock('../runtime/launch', async (importOriginal) => ({ - ...(await importOriginal>()), - serveOrcaApp: vi.fn() -})) -vi.mock('../terminals/terminal-selector', async (importOriginal) => ({ - ...(await importOriginal>()), - getTerminalHandle: getTerminalHandleMock -})) - -import { main } from '../index' -import { RuntimeClientError } from '../runtime/types' -import { okFixture, queueFixtures } from '../test-fixtures' - -const originalTerminalHandle = process.env.ORCA_TERMINAL_HANDLE -const originalPaneKey = process.env.ORCA_PANE_KEY -// Isolate inherited session markers so the runner cannot change the refusal branch. -const originalStructuredSession = process.env.ORCA_STRUCTURED_SESSION -const originalCodexThreadId = process.env.CODEX_THREAD_ID - -const restoreEnv = (name: string, value: string | undefined): void => { - if (value === undefined) { - delete process.env[name] - } else { - process.env[name] = value - } -} - -describe('orchestration gate commands carry caller identity', () => { - let logSpy: ReturnType - let errorSpy: ReturnType - - beforeEach(() => { - callMock.mockReset() - getTerminalHandleMock.mockReset() - logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - delete process.env.ORCA_TERMINAL_HANDLE - delete process.env.ORCA_PANE_KEY - delete process.env.ORCA_STRUCTURED_SESSION - delete process.env.CODEX_THREAD_ID - process.exitCode = 0 - }) - - afterEach(() => { - logSpy.mockRestore() - errorSpy.mockRestore() - restoreEnv('ORCA_TERMINAL_HANDLE', originalTerminalHandle) - restoreEnv('ORCA_PANE_KEY', originalPaneKey) - restoreEnv('ORCA_STRUCTURED_SESSION', originalStructuredSession) - restoreEnv('CODEX_THREAD_ID', originalCodexThreadId) - process.exitCode = 0 - }) - - const paramsFor = (method: string): Record => - callMock.mock.calls.find((call) => call[0] === method)?.[1] as Record - - it('inspects a named Run without resolving a caller terminal', async () => { - getTerminalHandleMock.mockRejectedValue( - new RuntimeClientError('no_active_terminal', 'no active terminal') - ) - queueFixtures( - callMock, - okFixture('req_list', { - gates: [ - { - id: 'gate_1', - task_id: 'task_1', - question: 'ship?', - options: '["yes","no"]', - status: 'pending', - resolution: null, - created_at: '2026-10-31 00:00:00' - } - ], - count: 1 - }) - ) - - await main(['orchestration', 'gate-list', '--run', 'run_adopted', '--json'], '/tmp/repo') - - expect(process.exitCode).toBe(0) - expect(JSON.parse(String(logSpy.mock.calls[0]?.[0])).result.gates).toEqual([ - { - id: 'gate_1', - taskId: 'task_1', - status: 'pending', - question: 'ship?', - options: '["yes","no"]' - } - ]) - expect(getTerminalHandleMock).not.toHaveBeenCalled() - expect(paramsFor('orchestration.gateList')).toEqual( - expect.objectContaining({ run: 'run_adopted', from: undefined }) - ) - }) - - it('fails an unbound gate-create with an actionable error and no mutation', async () => { - getTerminalHandleMock.mockRejectedValue( - new RuntimeClientError('no_active_terminal', 'no active terminal') - ) - - await main( - ['orchestration', 'gate-create', '--task', 'task_1', '--question', 'ship?'], - '/tmp/repo' - ) - - expect(process.exitCode).toBe(1) - const stderr = errorSpy.mock.calls.map((call) => String(call[0])).join('\n') - expect(stderr).toContain("Pass --from with your own terminal's handle") - expect(callMock).not.toHaveBeenCalledWith('orchestration.gateCreate', expect.anything()) - }) - - it('reports idempotent recovery when a mutation connection drops', async () => { - process.env.ORCA_TERMINAL_HANDLE = 'term_coord' - callMock - .mockResolvedValueOnce( - okFixture('req_identity', { identity: { handle: 'term_coord', live: true } }) - ) - .mockRejectedValueOnce( - new RuntimeClientError( - 'runtime_unavailable', - 'The Orca runtime closed the connection before responding. Restart Orca and try again. Orchestration mutation request ID: mutation_1.', - { - orchestrationRequestId: 'mutation_1', - originalCommand: [ - 'orca', - 'orchestration', - 'gate-create', - '--task', - 'task_1', - '--question', - 'ship?', - '--json' - ], - failedStage: 'dispatch_input', - residualResources: [ - { kind: 'worktree', id: 'repo::child' }, - { kind: 'terminal', id: 'term_worker' } - ] - } - ) - ) - - await main( - ['orchestration', 'gate-create', '--task', 'task_1', '--question', 'ship?', '--json'], - '/tmp/repo' - ) - - expect(process.exitCode).toBe(1) - const output = JSON.parse(String(logSpy.mock.calls[0]?.[0])) as { - error: { message: string; data: Record } - } - expect(output.error.message).toContain('--retry-request mutation_1') - expect(output.error.message).toContain('may already have taken effect') - expect(output.error.message).toContain('Failed stage: dispatch_input') - expect(output.error.message).toMatch(/Residual resources:.*repo::child.*term_worker/) - expect(output.error.message).not.toMatch(/restart Orca/i) - expect(output.error.data).toMatchObject({ - orchestrationRequestId: 'mutation_1', - failedStage: 'dispatch_input', - residualResources: expect.arrayContaining([ - expect.objectContaining({ kind: 'worktree', id: 'repo::child' }), - expect.objectContaining({ kind: 'terminal', id: 'term_worker' }) - ]) - }) - }) -}) diff --git a/src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts b/src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts deleted file mode 100644 index ba0452a890b..00000000000 --- a/src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { afterEach, expect, it, vi } from 'vitest' -import { reportCliError } from '../cli-error' -import { ORCHESTRATION_HANDLERS } from './orchestration' - -afterEach(() => { - vi.restoreAllMocks() -}) - -it('prints a rejected lifecycle verdict as a JSON failure envelope', async () => { - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - const client = { - call: vi.fn().mockResolvedValue({ - result: { - message: { id: 'msg_rejected' }, - lifecycle: { - action: 'rejected', - code: 'sender_not_assignee', - reason: 'dispatch ctx_1 expected the assigned pane' - } - } - }) - } - let rejection: unknown - try { - await ORCHESTRATION_HANDLERS['orchestration send']({ - flags: new Map([ - ['from', 'term_foreign'], - ['to', 'term_coord'], - ['subject', 'done'], - ['type', 'worker_done'], - ['outcome', 'succeeded'] - ]), - client, - cwd: '/tmp/repo', - json: true - } as never) - } catch (error) { - rejection = error - } - - expect(rejection).toBeDefined() - reportCliError(rejection, true, { commandPath: ['orchestration', 'send'] }) - - expect(JSON.parse(String(log.mock.calls[0]?.[0]))).toMatchObject({ - ok: false, - error: { - code: 'sender_not_assignee', - message: 'dispatch ctx_1 expected the assigned pane' - } - }) -}) diff --git a/src/cli/handlers/orchestration.ts b/src/cli/handlers/orchestration.ts deleted file mode 100644 index a6e5b610ce9..00000000000 --- a/src/cli/handlers/orchestration.ts +++ /dev/null @@ -1,34 +0,0 @@ -import type { CommandHandler } from '../dispatch' -import { ORCHESTRATION_CHECK_HANDLER } from './orchestration/message-check-handler' -import { - ORCHESTRATION_DISPATCH_HANDLER, - ORCHESTRATION_DISPATCH_INSPECTION_HANDLERS -} from './orchestration/dispatch-handlers' -import { ORCHESTRATION_GATE_HANDLERS } from './orchestration/gate-handlers' -import { ORCHESTRATION_INBOX_HANDLERS } from './orchestration/message-inbox-handlers' -import { ORCHESTRATION_QUESTION_HANDLER } from './orchestration/question-handler' -import { ORCHESTRATION_REQUEST_SHOW_HANDLER } from './orchestration/mutation-request-show-handler' -import { ORCHESTRATION_RESET_HANDLER } from './orchestration/reset-handler' -import { ORCHESTRATION_RUN_HANDLERS } from './orchestration/run-handlers' -import { ORCHESTRATION_SEND_HANDLER } from './orchestration/message-send-handler' -import { ORCHESTRATION_TASK_HANDLERS } from './orchestration/task-handlers' -import { ORCHESTRATION_WORKER_LAUNCH_HANDLER } from './orchestration/worker-launch-handler' -import { ORCHESTRATION_WORKER_OBSERVATION_HANDLERS } from './orchestration/worker-observation-handlers' -import { ORCHESTRATION_WORKER_TERMINAL_HANDLERS } from './orchestration/worker-terminal-handlers' - -export const ORCHESTRATION_HANDLERS: Record = { - ...ORCHESTRATION_RUN_HANDLERS, - ...ORCHESTRATION_SEND_HANDLER, - ...ORCHESTRATION_CHECK_HANDLER, - ...ORCHESTRATION_INBOX_HANDLERS, - ...ORCHESTRATION_TASK_HANDLERS, - ...ORCHESTRATION_WORKER_LAUNCH_HANDLER, - ...ORCHESTRATION_WORKER_OBSERVATION_HANDLERS, - ...ORCHESTRATION_WORKER_TERMINAL_HANDLERS, - ...ORCHESTRATION_DISPATCH_HANDLER, - ...ORCHESTRATION_QUESTION_HANDLER, - ...ORCHESTRATION_DISPATCH_INSPECTION_HANDLERS, - ...ORCHESTRATION_REQUEST_SHOW_HANDLER, - ...ORCHESTRATION_GATE_HANDLERS, - ...ORCHESTRATION_RESET_HANDLER -} diff --git a/src/cli/handlers/orchestration/worker-start-implicit-coordinator.test.ts b/src/cli/handlers/orchestration/worker-start-implicit-coordinator.test.ts deleted file mode 100644 index 895772c3eae..00000000000 --- a/src/cli/handlers/orchestration/worker-start-implicit-coordinator.test.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { ORCHESTRATION_HANDLERS } from '../orchestration' -import { RuntimeClient } from '../../runtime-client' -import { okFixture } from '../../test-fixtures' - -const client = new RuntimeClient('/tmp/orca-implicit-coordinator', 60_000, null, null) -const COORDINATOR_WORKTREE = { id: 'repo::/tmp/coord', repoId: 'repo', path: '/tmp/coord' } - -describe('worker-start infers its coordinator from the caller, not the worker placement (#33579)', () => { - const calls: { method: string; params: unknown }[] = [] - - beforeEach(() => { - calls.length = 0 - vi.stubEnv('ORCA_TERMINAL_HANDLE', '') - vi.stubEnv('ORCA_PANE_KEY', '') - vi.stubEnv('ORCA_AGENT_SESSION_ID', undefined) - vi.stubEnv('ORCA_STRUCTURED_SESSION', '') - vi.spyOn(console, 'log').mockImplementation(() => {}) - vi.spyOn(client, 'call').mockImplementation(async (method: string, params?: unknown) => { - calls.push({ method, params }) - if (method === 'worktree.list') { - return okFixture('req_list', { worktrees: [COORDINATOR_WORKTREE] }) - } - if (method === 'folderWorkspace.list') { - return okFixture('req_folders', { folderWorkspaces: [] }) - } - if (method === 'terminal.resolveActive') { - const worktree = - params && typeof params === 'object' && 'worktree' in params ? params.worktree : undefined - if (worktree !== `id:${COORDINATOR_WORKTREE.id}`) { - throw Object.assign(new Error('selector_not_found'), { code: 'selector_not_found' }) - } - return okFixture('req_active', { handle: 'term_coord' }) - } - if (method === 'orchestration.workerStart') { - return okFixture('req_start', { state: 'ready', effects: [], residualResources: [] }) - } - throw new Error(`Unexpected RPC: ${method}`) - }) - }) - - afterEach(() => { - vi.unstubAllEnvs() - vi.restoreAllMocks() - process.exitCode = undefined - }) - - const placements: [string, Record][] = [ - ['an exact worktree on another server', { on: 'wsl', worktree: 'id:remote::/srv/app' }], - ['a new child worktree', { worktree: 'new-child' }], - ['a reused worker terminal', { worktree: 'id:repo::/tmp/other', terminal: 'term_worker' }] - ] - - it.each(placements)('for %s', async (_label, placement) => { - await ORCHESTRATION_HANDLERS['orchestration worker-start']({ - flags: new Map([['spec', 'audit'], ...Object.entries(placement)]), - client, - cwd: '/tmp/coord/src', - json: true - }) - - expect(calls.find((call) => call.method === 'orchestration.workerStart')?.params).toMatchObject( - { from: 'term_coord', ...placement } - ) - }) -}) diff --git a/src/cli/hosts/environment.ts b/src/cli/hosts/environment.ts index 11480b5b926..23d1d4797be 100644 --- a/src/cli/hosts/environment.ts +++ b/src/cli/hosts/environment.ts @@ -1,7 +1,7 @@ -import type { CommandHandler } from '../dispatch' +import type { CommandHandler } from '../dispatch/dispatch' import { formatEnvironment, formatEnvironmentList } from './environment-format' import { formatHostList, formatHostName, type HostNameResult } from './host-format' -import { printResult } from '../command-result-output' +import { printResult } from '../output/command-result-output' import { parseHostFlag } from './execution-host-flag' import { fetchSshTargetSummaries, @@ -15,7 +15,7 @@ import { RuntimeClientError } from '../runtime/types' import type { RuntimeClient } from '../runtime/client' import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope' -import { rejectRemoteSelectionFlags } from '../remote-selection-flag-rejection' +import { rejectRemoteSelectionFlags } from '../dispatch/remote-selection-flag-rejection' import { redactRuntimeEnvironment } from '../../shared/remote-runtime/host-catalog/runtime-environments' import type { RuntimeStatus } from '../../shared/runtime-session-contracts' import { diff --git a/src/cli/hosts/host-handler-groups.ts b/src/cli/hosts/host-handler-groups.ts index 70a31c6ef7a..bc1531b8948 100644 --- a/src/cli/hosts/host-handler-groups.ts +++ b/src/cli/hosts/host-handler-groups.ts @@ -1,4 +1,4 @@ -import type { HandlerGroup } from '../handler-group-manifest' +import type { HandlerGroup } from '../dispatch/handler-group-manifest' // The machines Orca reaches: saved hosts and paired environments, the Orca servers it manages on // them, and recipe VMs. diff --git a/src/cli/hosts/host-selector-alternatives.test.ts b/src/cli/hosts/host-selector-alternatives.test.ts deleted file mode 100644 index eaa97360035..00000000000 --- a/src/cli/hosts/host-selector-alternatives.test.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { listSshTargets } from './host-selector-alternatives' -import { RuntimeClient } from '../runtime/client' -import { okFixture } from '../test-fixtures' - -const SSH_TARGETS = [{ id: 'ssh-1755000000000-a1b2c3', label: 'openclaw' }] - -afterEach(() => vi.restoreAllMocks()) - -function clientWithCall(call: RuntimeClient['call']): RuntimeClient { - const client = new RuntimeClient('/tmp/orca-host-alternatives-test', 60_000, null, null) - vi.spyOn(client, 'call').mockImplementation(call) - return client -} - -describe('listSshTargets', () => { - it('enriches legacy target rows from host-owned connection state', async () => { - const { RuntimeClientError } = await import('../runtime/types.js') - const call = vi - .fn() - .mockRejectedValueOnce(new RuntimeClientError('method_not_found', 'Unknown method')) - .mockResolvedValueOnce(okFixture('targets', { targets: SSH_TARGETS })) - .mockResolvedValueOnce( - okFixture('state', { - state: { status: 'connected', remotePlatform: 'win32' } - }) - ) - - await expect(listSshTargets(clientWithCall(call))).resolves.toEqual([ - { ...SSH_TARGETS[0], connected: true, connectionStatus: 'connected', remotePlatform: 'win32' } - ]) - expect(call).toHaveBeenCalledWith('ssh.getState', { targetId: SSH_TARGETS[0].id }) - }) -}) diff --git a/src/cli/hosts/local-environment-selector.ts b/src/cli/hosts/local-environment-selector.ts index a85d88f5e17..62d409d84ae 100644 --- a/src/cli/hosts/local-environment-selector.ts +++ b/src/cli/hosts/local-environment-selector.ts @@ -1,7 +1,7 @@ import { normalizeTypedName } from '../../shared/typed-name-normalization' import type { RuntimeClient } from '../runtime/client' import { RuntimeClientError } from '../runtime/types' -import { quoteCliCommandArgument } from '../shell-command-quote' +import { quoteCliCommandArgument } from '../arguments/shell-command-quote' /** `--environment local`: the caller's own Orca, even over an ambient ORCA_ENVIRONMENT or pairing code. */ export const LOCAL_ENVIRONMENT = 'local' diff --git a/src/cli/hosts/managed-server-reconnect.ts b/src/cli/hosts/managed-server-reconnect.ts index e100fa69834..f49d43c5547 100644 --- a/src/cli/hosts/managed-server-reconnect.ts +++ b/src/cli/hosts/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 '../command-result-output' +import type { HandlerContext } from '../dispatch/dispatch' +import { printResult } from '../output/command-result-output' import { RuntimeClientError } from '../runtime/types' import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope' diff --git a/src/cli/hosts/managed-server.ts b/src/cli/hosts/managed-server.ts index 2626133b1b3..aa02114109c 100644 --- a/src/cli/hosts/managed-server.ts +++ b/src/cli/hosts/managed-server.ts @@ -10,9 +10,9 @@ import type { import { ORCAD_RECOVERY_CHANGED_STATE_CODE } from '../../shared/orcad-managed-runtime' import { MANAGED_SERVER_RUNTIME_CAPABILITY } from '../../shared/host-runtime-capabilities' import type { RuntimeStatus } from '../../shared/runtime-session-contracts' -import type { CommandHandler, HandlerContext } from '../dispatch' -import { getRequiredStringFlag } from '../flags' -import { printResult } from '../command-result-output' +import type { CommandHandler, HandlerContext } from '../dispatch/dispatch' +import { getRequiredStringFlag } from '../arguments/flags' +import { printResult } from '../output/command-result-output' import { RuntimeClientError } from '../runtime/types' import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope' import { formatManagedServerStatus } from './managed-server-format' diff --git a/src/cli/hosts/vm-env.ts b/src/cli/hosts/vm-env.ts index 75a749b1fce..1494fde4bf6 100644 --- a/src/cli/hosts/vm-env.ts +++ b/src/cli/hosts/vm-env.ts @@ -1,5 +1,5 @@ import { resolve } from 'node:path' -import type { CommandHandler } from '../dispatch' +import type { CommandHandler } from '../dispatch/dispatch' import { formatEnvironmentDoctorChecks, type EnvironmentDoctorResult diff --git a/src/cli/hosts/vm.ts b/src/cli/hosts/vm.ts index c904747e9b2..27610005138 100644 --- a/src/cli/hosts/vm.ts +++ b/src/cli/hosts/vm.ts @@ -1,6 +1,6 @@ import { existsSync, readFileSync } from 'node:fs' import { join } from 'node:path' -import type { CommandHandler } from '../dispatch' +import type { CommandHandler } from '../dispatch/dispatch' import { RuntimeClientError } from '../runtime/types' import { parseOrcaYaml } from '../../shared/orca-yaml' import { diff --git a/src/cli/wsl-distro-cli-refusal.ts b/src/cli/hosts/wsl-distro-cli-refusal.ts similarity index 86% rename from src/cli/wsl-distro-cli-refusal.ts rename to src/cli/hosts/wsl-distro-cli-refusal.ts index cfdd17abffe..c0fee6a681f 100644 --- a/src/cli/wsl-distro-cli-refusal.ts +++ b/src/cli/hosts/wsl-distro-cli-refusal.ts @@ -1,5 +1,5 @@ -import { readableWslDistroHoldText } from '../shared/wsl-distro-stopped-hold' -import { parseWslUncPath } from '../shared/wsl-paths' +import { readableWslDistroHoldText } from '../../shared/wsl-distro-stopped-hold' +import { parseWslUncPath } from '../../shared/wsl-paths' const FOLDER_UNAVAILABLE_PREFIX = 'folder_workspace_path_unavailable:' diff --git a/src/cli/index-agent-launch.test.ts b/src/cli/index-agent-launch.test.ts index f60e8a2ff23..2fd46b23aea 100644 --- a/src/cli/index-agent-launch.test.ts +++ b/src/cli/index-agent-launch.test.ts @@ -18,7 +18,7 @@ const { spawnMock: vi.fn() })) -vi.mock('./runtime-client', async () => { +vi.mock('./runtime/client', async () => { const { createRuntimeClientModuleMock } = await import('./index-test-harness.js') return createRuntimeClientModuleMock({ callMock, @@ -28,6 +28,16 @@ vi.mock('./runtime-client', async () => { }) }) +vi.mock('./runtime/launch', async (importOriginal) => ({ + ...(await importOriginal>()), + serveOrcaApp: serveOrcaAppMock +})) + +vi.mock('./runtime/metadata', async (importOriginal) => ({ + ...(await importOriginal>()), + getDefaultUserDataPath: getDefaultUserDataPathMock +})) + vi.mock('./runtime/environments', () => ({ addEnvironmentFromPairingCode: addEnvironmentFromPairingCodeMock, removeEnvironment: vi.fn(), @@ -44,8 +54,8 @@ vi.mock('child_process', async () => { }) import { main } from './index' -import { RuntimeClientError, RuntimeRpcFailureError } from './runtime-client' -import { queueFixtures } from './test-fixtures' +import { RuntimeClientError, RuntimeRpcFailureError } from './runtime/types' +import { queueFixtures } from './runtime/fixtures/runtime-rpc-fixtures' import { useWorktreeAwarenessEnvironment } from './index-test-harness' import { agentLaunchHostFixture } from './agents/agent-launch-test-fixtures' diff --git a/src/cli/index-file-open-headless.test.ts b/src/cli/index-file-open-headless.test.ts deleted file mode 100644 index 3c0a9044a47..00000000000 --- a/src/cli/index-file-open-headless.test.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const mocks = vi.hoisted(() => ({ - callMock: vi.fn(), - runtimeClientConstructorMock: vi.fn(), - serveOrcaAppMock: vi.fn(), - getDefaultUserDataPathMock: vi.fn(() => '/tmp/orca-user-data') -})) -vi.mock('./runtime-client', async () => { - const { createRuntimeClientModuleMock } = await import('./index-test-harness.js') - return createRuntimeClientModuleMock(mocks) -}) - -import { main } from './index' -import { okFixture } from './test-fixtures' -import { RuntimeRpcFailureError } from './runtime/types' - -function headlessRefusal(): RuntimeRpcFailureError { - return new RuntimeRpcFailureError({ - id: 'req_open', - ok: false, - error: { code: 'runtime_error', message: 'renderer_unavailable' }, - _meta: { runtimeId: 'runtime-1' } - }) -} - -describe('file commands on a server with no app window', () => { - const priorExitCode = process.exitCode - afterEach(() => { - process.exitCode = priorExitCode - vi.restoreAllMocks() - }) - beforeEach(() => { - vi.restoreAllMocks() - mocks.callMock.mockReset() - process.exitCode = undefined - vi.spyOn(console, 'log').mockImplementation(() => {}) - vi.spyOn(console, 'error').mockImplementation(() => {}) - }) - - it('stops open-changed at the first refusal with the same explanation', async () => { - mocks.callMock - .mockResolvedValueOnce( - okFixture('req_status', { - entries: [ - { path: 'a.ts', status: 'modified', area: 'unstaged' }, - { path: 'b.ts', status: 'modified', area: 'unstaged' } - ] - }) - ) - .mockRejectedValueOnce(headlessRefusal()) - - await main(['file', 'open-changed', '--worktree', 'id:wt-1'], '/tmp/repo') - - expect(mocks.callMock.mock.calls).toEqual([ - ['git.status', { worktree: 'id:wt-1' }], - [ - 'files.openDiff', - { worktree: 'id:wt-1', relativePath: 'a.ts', staged: false, navigation: 'caller' } - ] - ]) - - expect(String(vi.mocked(console.error).mock.calls[0]?.[0])).toContain( - 'This Orca server has no app window' - ) - }) -}) diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 67c70568124..d1d487542ee 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -18,7 +18,7 @@ const { spawnMock: vi.fn() })) -vi.mock('./runtime-client', async () => { +vi.mock('./runtime/client', async () => { const { createRuntimeClientModuleMock } = await import('./index-test-harness.js') return createRuntimeClientModuleMock({ callMock, @@ -28,6 +28,16 @@ vi.mock('./runtime-client', async () => { }) }) +vi.mock('./runtime/launch', async (importOriginal) => ({ + ...(await importOriginal>()), + serveOrcaApp: serveOrcaAppMock +})) + +vi.mock('./runtime/metadata', async (importOriginal) => ({ + ...(await importOriginal>()), + getDefaultUserDataPath: getDefaultUserDataPathMock +})) + vi.mock('./runtime/environments', () => ({ addEnvironmentFromPairingCode: addEnvironmentFromPairingCodeMock, removeEnvironment: vi.fn(), @@ -44,7 +54,7 @@ vi.mock('child_process', async () => { }) import { main } from './index' -import { okFixture, queueFixtures } from './test-fixtures' +import { okFixture, queueFixtures } from './runtime/fixtures/runtime-rpc-fixtures' describe('command aliases dispatch to the canonical handler', () => { let logSpy: ReturnType diff --git a/src/cli/index.ts b/src/cli/index.ts index 5d5f94686ec..862d3b443d1 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -5,37 +5,35 @@ import { normalizeCommandPositionals, parseArgs, resolveHelpPath, - specPaths, validateCommandAndFlags -} from './args' +} from './arguments/args' +import { specPaths } from './discovery/command-spec' import { readOrcaCliVersion } from './cli-version' -import { dispatch } from './dispatch' +import { dispatch } from './dispatch/dispatch' import { resolveEnvironmentSelectorForStore, resolveHostFlagEnvironmentId } from './hosts/execution-host-flag' import { fetchSshTargetSummaries, listSshTargets } from './hosts/host-selector-alternatives' -import { reportCliError } from './cli-error' +import { reportCliError } from './output/cli-error' import { RuntimeClientError } from './runtime/types' -import { cliErrorExitCode } from './cli-exit-code' -import { printHelp } from './help' -import type { RuntimeClient } from './runtime-client' +import { cliErrorExitCode } from './output/cli-exit-code' +import { printHelp } from './discovery/help' +import type { RuntimeClient } from './runtime/client' import { COMMAND_SPECS } from './specs' -import { resolveOrchestrationCliExecutable } from './runtime/orchestration-recovery-command' -import { refuseConflictingSessionCallerFlags } from './session-caller-flags' -import { ignoresRemoteSelection } from './remote-selection-scope' +import { resolveOrchestrationCliExecutable } from './orchestration/recovery/orchestration-recovery-command' +import { refuseConflictingSessionCallerFlags } from './orchestration/identity/session-caller-flags' +import { ignoresRemoteSelection } from './dispatch/remote-selection-scope' import { isLocalEnvironmentSelector, refuseLocalManagementSelector } from './hosts/local-environment-selector' -export { COMMAND_SPECS } from './specs' - const COMMAND_PATHS = COMMAND_SPECS.flatMap((spec) => specPaths(spec)) // Defer the runtime graph until after help and validation; await it to keep ctx.client synchronous. async function loadRuntimeClientClass(): Promise { - return (await import('./runtime-client.js')).RuntimeClient + return (await import('./runtime/client.js')).RuntimeClient } // The SSH bridge runs here, but ORCA_CLI_CWD carries the remote caller's directory. diff --git a/src/cli/jira/jira-handler-group.ts b/src/cli/jira/jira-handler-group.ts index be17fbf0c25..88eebe7a142 100644 --- a/src/cli/jira/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 '../dispatch/handler-group-manifest' export const JIRA_HANDLER_GROUP: HandlerGroup = { name: 'jira', diff --git a/src/cli/jira/jira-target.ts b/src/cli/jira/jira-target.ts index 444e62eee80..26f8f9275e2 100644 --- a/src/cli/jira/jira-target.ts +++ b/src/cli/jira/jira-target.ts @@ -6,8 +6,8 @@ import { JIRA_ISSUE_KEY_PATTERN, parseJiraIssueUrl } from '../../shared/jira/jira-issue-url' -import type { HandlerContext } from '../dispatch' -import { getOptionalStringFlag } from '../flags' +import type { HandlerContext } from '../dispatch/dispatch' +import { getOptionalStringFlag } from '../arguments/flags' import { RuntimeClientError } from '../runtime/types' export function resolveJiraTarget( diff --git a/src/cli/jira/jira-write.ts b/src/cli/jira/jira-write.ts index 5cabb2de15b..d31f7b15376 100644 --- a/src/cli/jira/jira-write.ts +++ b/src/cli/jira/jira-write.ts @@ -6,15 +6,15 @@ import type { JiraProject, JiraTransition } from '../../shared/jira/jira-types' -import type { CommandHandler, HandlerContext } from '../dispatch' -import { readCommandBody } from '../command-body-input' +import type { CommandHandler, HandlerContext } from '../dispatch/dispatch' +import { readCommandBody } from '../arguments/command-body-input' import { getOptionalJsonFlag, getOptionalStringFlag, getRepeatedStringFlag, getRequiredStringFlag -} from '../flags' -import { printResult } from '../command-result-output' +} from '../arguments/flags' +import { printResult } from '../output/command-result-output' import { formatJiraCreate } from './jira-format' import { resolveJiraTarget } from './jira-target' import { RuntimeClientError } from '../runtime/types' diff --git a/src/cli/jira/jira.ts b/src/cli/jira/jira.ts index a15bfbf3e1f..19995ec6648 100644 --- a/src/cli/jira/jira.ts +++ b/src/cli/jira/jira.ts @@ -11,13 +11,13 @@ import type { JiraUser } from '../../shared/jira/jira-types' import { isResolvedJiraIssueMatch, parseJiraIssueUrl } from '../../shared/jira/jira-issue-url' -import type { CommandHandler, HandlerContext } from '../dispatch' +import type { CommandHandler, HandlerContext } from '../dispatch/dispatch' import { getOptionalPositiveIntegerFlag, getOptionalStringFlag, getRequiredStringFlag -} from '../flags' -import { printResult } from '../command-result-output' +} from '../arguments/flags' +import { printResult } from '../output/command-result-output' import { formatJiraCommentList, formatJiraIssue, diff --git a/src/cli/linear/linear-comment-write.ts b/src/cli/linear/linear-comment-write.ts index e92e6ba1b4a..b681b9970d5 100644 --- a/src/cli/linear/linear-comment-write.ts +++ b/src/cli/linear/linear-comment-write.ts @@ -6,9 +6,9 @@ import type { 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 '../command-result-output' +import type { CommandHandler } from '../dispatch/dispatch' +import { getOptionalStringFlag, getRequiredStringFlag } from '../arguments/flags' +import { printResult } from '../output/command-result-output' import { formatLinearCommentAdd, formatLinearCommentDelete, diff --git a/src/cli/linear/linear-handler-group.ts b/src/cli/linear/linear-handler-group.ts index 9e84a81dbf2..549232c3020 100644 --- a/src/cli/linear/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 '../dispatch/handler-group-manifest' export const LINEAR_HANDLER_GROUP: HandlerGroup = { name: 'linear', diff --git a/src/cli/linear/linear-list-issues.ts b/src/cli/linear/linear-list-issues.ts index d4ec8666afd..46f3add8302 100644 --- a/src/cli/linear/linear-list-issues.ts +++ b/src/cli/linear/linear-list-issues.ts @@ -2,13 +2,13 @@ import type { LinearMcpIssueListRequest, LinearMcpIssueListResult } from '../../shared/linear/mcp-issue-list' -import type { CommandHandler } from '../dispatch' +import type { CommandHandler } from '../dispatch/dispatch' import { getOptionalNonNegativeIntegerFlag, getOptionalPositiveIntegerFlag, getOptionalStringFlag -} from '../flags' -import { printResult } from '../command-result-output' +} from '../arguments/flags' +import { printResult } from '../output/command-result-output' import { formatLinearMcpIssueList, printLinearMcpIssueListWarnings } from './linear-format' import { RuntimeClientError } from '../runtime/types' diff --git a/src/cli/linear/linear-relation-write.ts b/src/cli/linear/linear-relation-write.ts index c11cdefc4e1..ff0771df997 100644 --- a/src/cli/linear/linear-relation-write.ts +++ b/src/cli/linear/linear-relation-write.ts @@ -3,9 +3,9 @@ import type { LinearIssueRelationWriteRequest, LinearIssueRelationWriteResult } from '../../shared/linear/issue-relation-write' -import type { CommandHandler } from '../dispatch' -import { getRequiredStringFlag } from '../flags' -import { printResult } from '../command-result-output' +import type { CommandHandler } from '../dispatch/dispatch' +import { getRequiredStringFlag } from '../arguments/flags' +import { printResult } from '../output/command-result-output' import { formatLinearRelationWrite } from './linear-format' import { buildWriteTargetRequest } from './linear-request-builders' import { RuntimeClientError } from '../runtime/types' diff --git a/src/cli/linear/linear-request-builders.ts b/src/cli/linear/linear-request-builders.ts index f3f434da18f..db3d7ad527a 100644 --- a/src/cli/linear/linear-request-builders.ts +++ b/src/cli/linear/linear-request-builders.ts @@ -1,4 +1,4 @@ -import { readCommandBody } from '../command-body-input' +import { readCommandBody } from '../arguments/command-body-input' import type { LinearIssueInclude, LinearIssueListRequest, @@ -17,7 +17,7 @@ import { getOptionalStringFlag, getRepeatedStringFlag, getRequiredStringFlag -} from '../flags' +} from '../arguments/flags' import { RuntimeClientError } from '../runtime/types' const LINEAR_PRIORITY_VALUES = new Map([ diff --git a/src/cli/linear/linear-save-issue-request.ts b/src/cli/linear/linear-save-issue-request.ts index 1c2033506ae..0cc4148adb4 100644 --- a/src/cli/linear/linear-save-issue-request.ts +++ b/src/cli/linear/linear-save-issue-request.ts @@ -3,7 +3,7 @@ import { getOptionalNullableNumberFlag, getOptionalStringFlag, getRepeatedStringFlag -} from '../flags' +} from '../arguments/flags' import { buildLinearCurrentContext, getDueDateFlag, diff --git a/src/cli/linear/linear-save-issue.ts b/src/cli/linear/linear-save-issue.ts index 2fb6418f2b3..07e4ac9bf67 100644 --- a/src/cli/linear/linear-save-issue.ts +++ b/src/cli/linear/linear-save-issue.ts @@ -1,7 +1,7 @@ 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 '../command-result-output' +import type { CommandHandler } from '../dispatch/dispatch' +import { printResult } from '../output/command-result-output' import { formatLinearSaveIssue } from './linear-format' import { buildSaveIssueRequest } from './linear-save-issue-request' diff --git a/src/cli/linear/linear.ts b/src/cli/linear/linear.ts index aa82959b272..f6a77d9109d 100644 --- a/src/cli/linear/linear.ts +++ b/src/cli/linear/linear.ts @@ -21,15 +21,15 @@ import type { LinearTeamStatesResult } from '../../shared/linear/agent-result-types' import { clampLinearSearchLimit } from '../../shared/linear/agent-access' -import type { CommandHandler } from '../dispatch' -import { printResult } from '../command-result-output' +import type { CommandHandler } from '../dispatch/dispatch' +import { printResult } from '../output/command-result-output' import { RuntimeClientError } from '../runtime/types' import { getOptionalPositiveIntegerFlag, getOptionalStringFlag, getRepeatedStringFlag, getRequiredStringFlag -} from '../flags' +} from '../arguments/flags' import { buildAssigneeSetRequest, buildIssueRequest, diff --git a/src/cli/orchestration-session-caller-cli.test.ts b/src/cli/orchestration-session-caller-cli.test.ts deleted file mode 100644 index 862c8fb1c81..00000000000 --- a/src/cli/orchestration-session-caller-cli.test.ts +++ /dev/null @@ -1,386 +0,0 @@ -// Inherited pane identity and an available sibling must never override the injected session caller. - -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const callMock = vi.hoisted(() => vi.fn()) -const getTerminalHandleMock = vi.hoisted(() => vi.fn()) - -vi.mock('./command-result-output', () => ({ printResult: vi.fn() })) -vi.mock('./terminals/terminal-selector', () => ({ getTerminalHandle: getTerminalHandleMock })) - -import { ORCHESTRATION_HANDLERS } from './handlers/orchestration' -import { findCommandSpec } from './args' -import { COMMAND_SPECS } from './specs' -import { refuseConflictingSessionCallerFlags } from './session-caller-flags' -import { createOrchestrationCompatibilityEnvelope } from './runtime/orchestration-compatibility-envelope' - -import { formatCliError } from './cli-error' -import { RuntimeRpcFailureError } from './runtime/types' - -const SESSION = 'f7a1c0de-1111-4222-8333-444455556666' -const IDENTITY_ENV = [ - 'ORCA_AGENT_SESSION_ID', - 'ORCA_TERMINAL_HANDLE', - 'ORCA_PANE_KEY', - 'ORCA_STRUCTURED_SESSION' -] as const -const originalEnv = Object.fromEntries(IDENTITY_ENV.map((name) => [name, process.env[name]])) - -const RESULT = { - result: { - run: { id: 'run_1', objective: 'o', consumer_generation: 1 }, - runs: [], - nextCursor: null, - messages: [], - count: 0, - message: { id: 'msg_1' }, - lifecycle: { action: 'completed' }, - dispatch: { id: 'dispatch_1', task_id: 'task_1', status: 'dispatched' }, - gate: { id: 'gate_1', task_id: 'task_1', status: 'pending', resolution: 'r' }, - gates: [], - task: { id: 'task_1', status: 'pending' }, - tasks: [], - answer: 'yes', - messageId: 'msg_1', - threadId: 'thread_1', - timedOut: false, - state: 'ready', - runId: 'run_1', - taskId: 'task_1', - dispatchId: 'dispatch_1', - effects: [], - residualResources: [], - workers: [], - counts: {} - } -} - -type Verb = { - command: string - flags: Record - callerFlag?: 'from' | 'terminal' - method: string - callerParam: 'from' | 'terminal' | 'callerTerminalHandle' -} - -/** dispatch-show is excluded: its --from fills preview text rather than naming the caller. */ -const CALLER_VERBS: Verb[] = [ - { - command: 'run-create', - flags: { objective: 'o' }, - callerFlag: 'from', - method: 'runCreate', - callerParam: 'from' - }, - { - command: 'run-use', - flags: { id: 'run_1' }, - callerFlag: 'from', - method: 'runUse', - callerParam: 'from' - }, - { - command: 'run-current', - flags: {}, - callerFlag: 'from', - method: 'runCurrent', - callerParam: 'from' - }, - { command: 'check', flags: {}, callerFlag: 'terminal', method: 'check', callerParam: 'terminal' }, - { - command: 'send', - flags: { to: 'term_worker', subject: 's', body: 'b' }, - callerFlag: 'from', - method: 'send', - callerParam: 'from' - }, - { - command: 'reply', - flags: { id: 'msg_1', body: 'b' }, - callerFlag: 'from', - method: 'reply', - callerParam: 'from' - }, - { - command: 'ask', - flags: { to: 'term_worker', question: 'q' }, - callerFlag: 'from', - method: 'ask', - callerParam: 'from' - }, - { - command: 'dispatch', - flags: { task: 'task_1', to: 'term_worker' }, - callerFlag: 'from', - method: 'dispatch', - callerParam: 'from' - }, - { - command: 'gate-create', - flags: { task: 'task_1', question: 'q' }, - callerFlag: 'from', - method: 'gateCreate', - callerParam: 'from' - }, - { - command: 'gate-resolve', - flags: { id: 'gate_1', resolution: 'r' }, - callerFlag: 'from', - method: 'gateResolve', - callerParam: 'from' - }, - { command: 'gate-list', flags: {}, callerFlag: 'from', method: 'gateList', callerParam: 'from' }, - { - command: 'task-create', - flags: { spec: 's' }, - callerFlag: 'from', - method: 'taskCreate', - callerParam: 'callerTerminalHandle' - }, - { - command: 'task-list', - flags: {}, - callerFlag: 'from', - method: 'taskList', - callerParam: 'callerTerminalHandle' - }, - { - command: 'task-update', - flags: { id: 'task_1', status: 'completed' }, - callerFlag: 'from', - method: 'taskUpdate', - callerParam: 'callerTerminalHandle' - }, - { - command: 'worker-start', - flags: { spec: 's' }, - callerFlag: 'from', - method: 'workerStart', - callerParam: 'from' - }, - { command: 'worker-list', flags: {}, method: 'runCurrent', callerParam: 'from' } -] - -const EVERY_REQUIRED_FLAG = { - objective: 'o', - id: 'id_1', - task: 'task_1', - spec: 's', - question: 'q', - resolution: 'r', - subject: 's', - body: 'b', - to: 'term_worker', - status: 'completed', - preamble: true, - request: 'req_1' -} as const - -function flagMap(flags: Record): Map { - return new Map(Object.entries(flags)) -} - -async function invoke( - command: string, - flags: Map, - json = true -): Promise { - const handler = ORCHESTRATION_HANDLERS[`orchestration ${command}`] - if (!handler) { - throw new Error(`no handler for ${command}`) - } - refuseConflictingSessionCallerFlags( - findCommandSpec(COMMAND_SPECS, ['orchestration', command]), - flags - ) - await handler({ - flags, - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: these handlers read only `call`; RuntimeClient is a class, so a structural double cannot satisfy it without the cast. - client: { call: callMock } as never, - cwd: '/tmp/repo', - json - }) -} - -function isParams(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} - -function callsTo(method: string): Record[] { - return callMock.mock.calls - .filter(([name]) => name === `orchestration.${method}`) - .map(([, params]) => (isParams(params) ? params : {})) -} - -function setEnv(env: Partial>): void { - for (const name of IDENTITY_ENV) { - const value = env[name] - if (value === undefined) { - delete process.env[name] - } else { - process.env[name] = value - } - } -} - -function asSessionWithInheritedPane(): void { - setEnv({ - ORCA_AGENT_SESSION_ID: SESSION, - ORCA_TERMINAL_HANDLE: 'term_inherited_pane', - ORCA_PANE_KEY: 'tab_inherited:11111111-1111-4111-8111-111111111111' - }) -} - -beforeEach(() => { - callMock.mockReset().mockResolvedValue(RESULT) - getTerminalHandleMock.mockReset().mockResolvedValue('term_sibling') - vi.spyOn(console, 'log').mockImplementation(() => {}) - vi.spyOn(console, 'error').mockImplementation(() => {}) -}) - -afterEach(() => { - vi.restoreAllMocks() - setEnv(originalEnv) - process.exitCode = undefined -}) - -describe.each(CALLER_VERBS)('orchestration $command run as an agent session', (verb) => { - beforeEach(asSessionWithInheritedPane) - - it.runIf(verb.callerFlag !== undefined)( - 'refuses a caller flag naming another caller, before any request', - async () => { - const flags = flagMap({ ...verb.flags, [verb.callerFlag ?? 'from']: 'term_sibling' }) - - await expect(invoke(verb.command, flags)).rejects.toMatchObject({ - code: 'consumer_fenced', - message: expect.stringContaining(`agent session ${SESSION}`) - }) - expect(callMock).not.toHaveBeenCalled() - expect(getTerminalHandleMock).not.toHaveBeenCalled() - } - ) - - it.runIf(verb.callerFlag !== undefined)( - 'refuses an inherited pane handle too: the session, not the pane, is the caller', - async () => { - const flags = flagMap({ ...verb.flags, [verb.callerFlag ?? 'from']: 'term_inherited_pane' }) - - await expect(invoke(verb.command, flags)).rejects.toMatchObject({ code: 'consumer_fenced' }) - expect(callMock).not.toHaveBeenCalled() - } - ) -}) - -describe.each([ - { command: 'gate-list', method: 'gateList', callerParam: 'from' }, - { command: 'task-list', method: 'taskList', callerParam: 'callerTerminalHandle' } -])('orchestration $command --run run as an agent session', ({ command, method, callerParam }) => { - beforeEach(asSessionWithInheritedPane) - - it('needs no caller, but refuses a --from naming another caller, before any request', async () => { - await invoke(command, flagMap({ run: 'run_1' })) - expect(callsTo(method)[0]).toMatchObject({ run: 'run_1' }) - expect(callsTo(method)[0]?.[callerParam]).toBeUndefined() - - callMock.mockClear() - await expect( - invoke(command, flagMap({ run: 'run_1', from: 'term_sibling' })) - ).rejects.toMatchObject({ code: 'consumer_fenced' }) - expect(callMock).not.toHaveBeenCalled() - }) -}) - -describe('the identity a session presents', () => { - it("lets a structured worker restate its own minted handle, and nobody else's", async () => { - setEnv({ ORCA_AGENT_SESSION_ID: SESSION, ORCA_TERMINAL_HANDLE: 'structworker_self' }) - - await invoke('send', flagMap({ from: 'structworker_self', to: 'run:run_1', subject: 's' })) - expect(callsTo('send')[0]?.from).toBeUndefined() - - callMock.mockClear() - await expect( - invoke('send', flagMap({ from: 'structworker_other', to: 'run:run_1', subject: 's' })) - ).rejects.toMatchObject({ code: 'consumer_fenced' }) - expect(callMock).not.toHaveBeenCalled() - }) - - it('keeps the identity-less refusal, without --from advice, for a child that has no id', async () => { - setEnv({ ORCA_STRUCTURED_SESSION: '1' }) - - await expect(invoke('reply', flagMap({ id: 'msg_1', body: 'b' }))).rejects.toMatchObject({ - code: 'no_active_sender_terminal', - message: expect.not.stringContaining('Pass --from') - }) - expect(getTerminalHandleMock).not.toHaveBeenCalled() - expect(callMock).not.toHaveBeenCalled() - }) -}) - -describe('a host refusal of the session', () => { - const WORKER_GONE = new RuntimeRpcFailureError({ - id: 'rpc_1', - ok: false, - error: { - code: 'session_caller_not_live', - message: `Agent session ${SESSION} is a structured worker whose worker identity this host no longer has, so it cannot act in orchestration. No effects were applied.`, - data: { effectsApplied: false } - }, - _meta: { runtimeId: 'runtime_1' } - }) - - it.each(['check', 'run-current', 'worker-list'])( - 'surfaces from %s verbatim, never widened, retried or turned into a terminal guess', - async (command) => { - asSessionWithInheritedPane() - callMock.mockRejectedValue(WORKER_GONE) - - await expect(invoke(command, flagMap({}))).rejects.toBe(WORKER_GONE) - expect(getTerminalHandleMock).not.toHaveBeenCalled() - expect(formatCliError(WORKER_GONE)).toBe(WORKER_GONE.message) - } - ) -}) - -describe('the orchestration envelope', () => { - it('carries the injected id beside whatever terminal evidence the process also has', () => { - const envelope = createOrchestrationCompatibilityEnvelope({ - ORCA_AGENT_SESSION_ID: ` ${SESSION} `, - ORCA_TERMINAL_HANDLE: 'term_inherited_pane' - }) - - expect(envelope.orchestrationCompatibilityEvidence).toEqual({ - terminalHandle: 'term_inherited_pane', - agentSessionId: SESSION - }) - }) - - it('claims no session without an injected id', () => { - expect( - createOrchestrationCompatibilityEnvelope({ ORCA_AGENT_SESSION_ID: ' ' }) - .orchestrationCompatibilityEvidence - ).toBeUndefined() - }) -}) - -describe('which flag names the caller, declared on every spec', () => { - const ORCHESTRATION_SPECS = COMMAND_SPECS.filter((spec) => spec.path[0] === 'orchestration') - - const callerFlagVerbs = ORCHESTRATION_SPECS.flatMap((spec) => - (['from', 'terminal'] as const) - .filter((flag) => spec.identityFlagRoles?.[flag] === 'caller') - .map((flag) => ({ command: spec.path[1] ?? '', flag })) - ) - - it.each(callerFlagVerbs)( - '$command refuses --$flag naming another caller, before any request', - async ({ command, flag }) => { - asSessionWithInheritedPane() - await expect( - invoke(command, flagMap({ ...EVERY_REQUIRED_FLAG, [flag]: 'term_sibling' })) - ).rejects.toMatchObject({ code: 'consumer_fenced' }) - expect(callMock).not.toHaveBeenCalled() - expect(getTerminalHandleMock).not.toHaveBeenCalled() - } - ) -}) diff --git a/src/cli/handlers/orchestration/agent-view.test.ts b/src/cli/orchestration/agent-view.test.ts similarity index 98% rename from src/cli/handlers/orchestration/agent-view.test.ts rename to src/cli/orchestration/agent-view.test.ts index 4aca1935831..c7b3384acec 100644 --- a/src/cli/handlers/orchestration/agent-view.test.ts +++ b/src/cli/orchestration/agent-view.test.ts @@ -1,9 +1,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -vi.mock('../../terminals/terminal-selector', () => ({ getTerminalHandle: vi.fn() })) +vi.mock('../terminals/terminal-selector', () => ({ getTerminalHandle: vi.fn() })) -import { ORCHESTRATION_HANDLERS } from '../orchestration' -import { orchestrationTestContext } from '../orchestration-handler-test-context' +import { ORCHESTRATION_HANDLERS } from './orchestration-handlers' +import { orchestrationTestContext } from './orchestration-handler-test-context' const callMock = vi.fn() const originalExitCode = process.exitCode diff --git a/src/cli/handlers/orchestration/agent-view.ts b/src/cli/orchestration/agent-view.ts similarity index 91% rename from src/cli/handlers/orchestration/agent-view.ts rename to src/cli/orchestration/agent-view.ts index aeef0db4a3f..10413ed4547 100644 --- a/src/cli/handlers/orchestration/agent-view.ts +++ b/src/cli/orchestration/agent-view.ts @@ -1,11 +1,11 @@ -import type { HandlerContext } from '../../dispatch' -import { printResult } from '../../command-result-output' -import { formatOrchestrationErrorLine } from '../../cli-error' -import { renderCommand } from '../../orchestration-mutation-recovery' -import { resolveOrchestrationCliExecutable } from '../../runtime/orchestration-recovery-command' -import type { RuntimeRpcSuccess } from '../../runtime-client' +import type { HandlerContext } from '../dispatch/dispatch' +import { printResult } from '../output/command-result-output' +import { formatOrchestrationErrorLine } from '../output/cli-error' +import { renderCommand } from './recovery/orchestration-mutation-recovery' +import { resolveOrchestrationCliExecutable } from './recovery/orchestration-recovery-command' +import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope' import { withReceiptNext } from './receipt-next-text' -import { escapeTerminalControlCharacters } from '../../../shared/terminal/output/terminal-control-character-escape' +import { escapeTerminalControlCharacters } from '../../shared/terminal/output/terminal-control-character-escape' type AgentViewFields = Record diff --git a/src/cli/handlers/orchestration/dispatch-handlers.ts b/src/cli/orchestration/dispatches/dispatch-handlers.ts similarity index 88% rename from src/cli/handlers/orchestration/dispatch-handlers.ts rename to src/cli/orchestration/dispatches/dispatch-handlers.ts index 1328edecdff..d9346bdeb56 100644 --- a/src/cli/handlers/orchestration/dispatch-handlers.ts +++ b/src/cli/orchestration/dispatches/dispatch-handlers.ts @@ -1,11 +1,11 @@ -import type { CommandHandler } from '../../dispatch' -import { printOrchestrationReceipt } from './agent-view' -import { getOptionalStringFlag, getRequiredStringFlag } from '../../flags' -import { RuntimeClientError } from '../../runtime-client' +import type { CommandHandler } from '../../dispatch/dispatch' +import { printOrchestrationReceipt } from '../agent-view' +import { getOptionalStringFlag, getRequiredStringFlag } from '../../arguments/flags' +import { RuntimeClientError } from '../../runtime/types' import { orchestrationMigrationData } from '../../../shared/orchestration/orchestration-rpc-contract' -import { callOrchestrationMutation } from './mutation-request' -import { isDevCliInvocation } from './runtime-compatibility' -import { resolveCoordinatorTerminalHandle } from './terminal-identity' +import { callOrchestrationMutation } from '../recovery/mutation-request' +import { isDevCliInvocation } from '../recovery/runtime-compatibility' +import { resolveCoordinatorTerminalHandle } from '../identity/terminal-identity' import { injectedSessionAddress } from '../../../shared/agent-session/lifecycle/agent-session-caller-env' export const ORCHESTRATION_DISPATCH_HANDLER: Record = { diff --git a/src/cli/handlers/orchestration/gate-handlers.ts b/src/cli/orchestration/gates/gate-handlers.ts similarity index 87% rename from src/cli/handlers/orchestration/gate-handlers.ts rename to src/cli/orchestration/gates/gate-handlers.ts index 2745e7a2e55..2ab544ccbea 100644 --- a/src/cli/handlers/orchestration/gate-handlers.ts +++ b/src/cli/orchestration/gates/gate-handlers.ts @@ -1,9 +1,16 @@ -import type { CommandHandler } from '../../dispatch' -import { printResult } from '../../command-result-output' -import { printOrchestrationResult } from './agent-view' -import { getOptionalJsonFlag, getOptionalStringFlag, getRequiredStringFlag } from '../../flags' -import { callOrchestrationMutation } from './mutation-request' -import { resolveCoordinatorTerminalHandle, runScopedSessionCaller } from './terminal-identity' +import type { CommandHandler } from '../../dispatch/dispatch' +import { printResult } from '../../output/command-result-output' +import { printOrchestrationResult } from '../agent-view' +import { + getOptionalJsonFlag, + getOptionalStringFlag, + getRequiredStringFlag +} from '../../arguments/flags' +import { callOrchestrationMutation } from '../recovery/mutation-request' +import { + resolveCoordinatorTerminalHandle, + runScopedSessionCaller +} from '../identity/terminal-identity' export const ORCHESTRATION_GATE_HANDLERS: Record = { 'orchestration gate-create': async ({ flags, client, cwd, json }) => { diff --git a/src/cli/handlers/orchestration/agent-server-route.ts b/src/cli/orchestration/identity/agent-server-route.ts similarity index 92% rename from src/cli/handlers/orchestration/agent-server-route.ts rename to src/cli/orchestration/identity/agent-server-route.ts index 3112b6d7d84..c9f4764ed0e 100644 --- a/src/cli/handlers/orchestration/agent-server-route.ts +++ b/src/cli/orchestration/identity/agent-server-route.ts @@ -1,9 +1,10 @@ -import type { HandlerContext } from '../../dispatch' -import { RuntimeClient, RuntimeClientError } from '../../runtime-client' +import type { HandlerContext } from '../../dispatch/dispatch' +import { RuntimeClient } from '../../runtime/client' +import { RuntimeClientError } from '../../runtime/types' import { readInjectedAgentSessionId } from '../../../shared/agent-session/lifecycle/agent-session-caller-env' import type { OrchestrationCallerShowResult } from '../../../shared/orchestration/orchestration-caller-status' -import { renderOrchestrationArgv } from './agent-view' -import type { RuntimeStatus } from '../../../shared/runtime-types' +import { renderOrchestrationArgv } from '../agent-view' +import type { RuntimeStatus } from '../../../shared/runtime-session-contracts' import { ORCHESTRATION_PEER_MAIL_RUNTIME_CAPABILITY } from '../../../shared/orchestration/orchestration-runtime-capabilities' type AgentServerRoutedCommand = 'send' | 'worker-start' | 'check' diff --git a/src/cli/handlers/orchestration-caller-identity-cli.test.ts b/src/cli/orchestration/identity/orchestration-caller-identity-cli.test.ts similarity index 71% rename from src/cli/handlers/orchestration-caller-identity-cli.test.ts rename to src/cli/orchestration/identity/orchestration-caller-identity-cli.test.ts index 764fdb98a00..ff0c742053a 100644 --- a/src/cli/handlers/orchestration-caller-identity-cli.test.ts +++ b/src/cli/orchestration/identity/orchestration-caller-identity-cli.test.ts @@ -4,25 +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('../command-result-output', () => ({ printResult: vi.fn() })) -vi.mock('../terminals/terminal-selector', () => ({ getTerminalHandle: getTerminalHandleMock })) +vi.mock('../../output/command-result-output', () => ({ printResult: vi.fn() })) +vi.mock('../../terminals/terminal-selector', () => ({ getTerminalHandle: getTerminalHandleMock })) -import { ORCHESTRATION_HANDLERS } from './orchestration' -import { RuntimeClientError } from '../runtime-client' -import { printResult } from '../command-result-output' +import { ORCHESTRATION_HANDLERS } from '../orchestration-handlers' +import { RuntimeClientError } from '../../runtime/types' +import { printResult } from '../../output/command-result-output' function staleHandleError(): RuntimeClientError { return new RuntimeClientError('terminal_handle_stale', 'terminal_handle_stale') } -function stubStaleHandleRemintFailure(error: RuntimeClientError): void { - callMock.mockResolvedValueOnce(notLiveIdentity()).mockRejectedValueOnce(error) -} - -function notLiveIdentity(): { result: { identity: { live: false } } } { - return { result: { identity: { live: false } } } -} - afterEach(() => { getTerminalHandleMock.mockReset() if (originalTerminalHandle === undefined) { @@ -83,35 +75,6 @@ describe('orchestration dispatch coordinator handle', () => { expect(getTerminalHandleMock).not.toHaveBeenCalled() }) - it('propagates unexpected caller pane remint failures for coordinator commands', async () => { - process.env.ORCA_TERMINAL_HANDLE = 'term_stale_coord' - process.env.ORCA_PANE_KEY = 'tab_coord:leaf_coord' - stubStaleHandleRemintFailure( - new RuntimeClientError('runtime_unavailable', 'runtime_unavailable') - ) - getTerminalHandleMock.mockResolvedValue('term_wrong_active') - - await expect( - invokeDispatch( - new Map([ - ['task', 'task_1'], - ['to', 'term_worker'] - ]) - ) - ).rejects.toMatchObject({ - code: 'runtime_unavailable' - }) - - expect(callMock).toHaveBeenNthCalledWith(1, 'terminal.resolveIdentity', { - terminal: 'term_stale_coord' - }) - expect(callMock).toHaveBeenNthCalledWith(2, 'terminal.resolvePane', { - paneKey: 'tab_coord:leaf_coord' - }) - expect(callMock).toHaveBeenCalledTimes(2) - expect(getTerminalHandleMock).not.toHaveBeenCalled() - }) - it('retires the legacy coordinator command without runtime effects', async () => { await expect( invokeRun(new Map([['spec', 'run the plan']])) diff --git a/src/cli/runtime/orchestration-compatibility-envelope.ts b/src/cli/orchestration/identity/orchestration-compatibility-envelope.ts similarity index 89% rename from src/cli/runtime/orchestration-compatibility-envelope.ts rename to src/cli/orchestration/identity/orchestration-compatibility-envelope.ts index c7f2d62f6cb..31d02b0d83b 100644 --- a/src/cli/runtime/orchestration-compatibility-envelope.ts +++ b/src/cli/orchestration/identity/orchestration-compatibility-envelope.ts @@ -1,7 +1,7 @@ import { randomUUID } from 'node:crypto' -import { readInjectedAgentSessionId } from '../../shared/agent-session/lifecycle/agent-session-caller-env' -import { readOrchestrationCompatibilityEvidence } from '../../shared/orchestration/orchestration-compatibility-evidence' -import type { RuntimeOrchestrationEnvelope } from '../../shared/runtime-rpc-envelope' +import { readInjectedAgentSessionId } from '../../../shared/agent-session/lifecycle/agent-session-caller-env' +import { readOrchestrationCompatibilityEvidence } from '../../../shared/orchestration/orchestration-compatibility-evidence' +import type { RuntimeOrchestrationEnvelope } from '../../../shared/runtime-rpc-envelope' export function createOrchestrationCompatibilityEnvelope( env: NodeJS.ProcessEnv diff --git a/src/cli/orchestration/identity/orchestration-session-caller-cli.test.ts b/src/cli/orchestration/identity/orchestration-session-caller-cli.test.ts new file mode 100644 index 00000000000..bb88c63d84a --- /dev/null +++ b/src/cli/orchestration/identity/orchestration-session-caller-cli.test.ts @@ -0,0 +1,139 @@ +// Inherited pane identity and an available sibling must never override the injected session caller. + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const callMock = vi.hoisted(() => vi.fn()) +const getTerminalHandleMock = vi.hoisted(() => vi.fn()) + +vi.mock('../../output/command-result-output', () => ({ printResult: vi.fn() })) +vi.mock('../../terminals/terminal-selector', () => ({ getTerminalHandle: getTerminalHandleMock })) + +import { ORCHESTRATION_HANDLERS } from '../orchestration-handlers' +import { findCommandSpec } from '../../arguments/args' +import { COMMAND_SPECS } from '../../specs/index' +import { refuseConflictingSessionCallerFlags } from './session-caller-flags' +import { createOrchestrationCompatibilityEnvelope } from './orchestration-compatibility-envelope' + +const SESSION = 'f7a1c0de-1111-4222-8333-444455556666' +const IDENTITY_ENV = [ + 'ORCA_AGENT_SESSION_ID', + 'ORCA_TERMINAL_HANDLE', + 'ORCA_PANE_KEY', + 'ORCA_STRUCTURED_SESSION' +] as const +const originalEnv = Object.fromEntries(IDENTITY_ENV.map((name) => [name, process.env[name]])) + +const RESULT = { + result: { + run: { id: 'run_1', objective: 'o', consumer_generation: 1 }, + runs: [], + nextCursor: null, + messages: [], + count: 0, + message: { id: 'msg_1' }, + lifecycle: { action: 'completed' }, + dispatch: { id: 'dispatch_1', task_id: 'task_1', status: 'dispatched' }, + gate: { id: 'gate_1', task_id: 'task_1', status: 'pending', resolution: 'r' }, + gates: [], + task: { id: 'task_1', status: 'pending' }, + tasks: [], + answer: 'yes', + messageId: 'msg_1', + threadId: 'thread_1', + timedOut: false, + state: 'ready', + runId: 'run_1', + taskId: 'task_1', + dispatchId: 'dispatch_1', + effects: [], + residualResources: [], + workers: [], + counts: {} + } +} + +/** dispatch-show is excluded: its --from fills preview text rather than naming the caller. */ + +function flagMap(flags: Record): Map { + return new Map(Object.entries(flags)) +} + +async function invoke( + command: string, + flags: Map, + json = true +): Promise { + const handler = ORCHESTRATION_HANDLERS[`orchestration ${command}`] + if (!handler) { + throw new Error(`no handler for ${command}`) + } + refuseConflictingSessionCallerFlags( + findCommandSpec(COMMAND_SPECS, ['orchestration', command]), + flags + ) + await handler({ + flags, + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: these handlers read only `call`; RuntimeClient is a class, so a structural double cannot satisfy it without the cast. + client: { call: callMock } as never, + cwd: '/tmp/repo', + json + }) +} + +function setEnv(env: Partial>): void { + for (const name of IDENTITY_ENV) { + const value = env[name] + if (value === undefined) { + delete process.env[name] + } else { + process.env[name] = value + } + } +} + +beforeEach(() => { + callMock.mockReset().mockResolvedValue(RESULT) + getTerminalHandleMock.mockReset().mockResolvedValue('term_sibling') + vi.spyOn(console, 'log').mockImplementation(() => {}) + vi.spyOn(console, 'error').mockImplementation(() => {}) +}) + +afterEach(() => { + vi.restoreAllMocks() + setEnv(originalEnv) + process.exitCode = undefined +}) + +describe('the identity a session presents', () => { + it('keeps the identity-less refusal, without --from advice, for a child that has no id', async () => { + setEnv({ ORCA_STRUCTURED_SESSION: '1' }) + + await expect(invoke('reply', flagMap({ id: 'msg_1', body: 'b' }))).rejects.toMatchObject({ + code: 'no_active_sender_terminal', + message: expect.not.stringContaining('Pass --from') + }) + expect(getTerminalHandleMock).not.toHaveBeenCalled() + expect(callMock).not.toHaveBeenCalled() + }) +}) + +describe('the orchestration envelope', () => { + it('carries the injected id beside whatever terminal evidence the process also has', () => { + const envelope = createOrchestrationCompatibilityEnvelope({ + ORCA_AGENT_SESSION_ID: ` ${SESSION} `, + ORCA_TERMINAL_HANDLE: 'term_inherited_pane' + }) + + expect(envelope.orchestrationCompatibilityEvidence).toEqual({ + terminalHandle: 'term_inherited_pane', + agentSessionId: SESSION + }) + }) + + it('claims no session without an injected id', () => { + expect( + createOrchestrationCompatibilityEnvelope({ ORCA_AGENT_SESSION_ID: ' ' }) + .orchestrationCompatibilityEvidence + ).toBeUndefined() + }) +}) diff --git a/src/cli/orchestration-structured-session-no-identity.test.ts b/src/cli/orchestration/identity/orchestration-structured-session-no-identity.test.ts similarity index 69% rename from src/cli/orchestration-structured-session-no-identity.test.ts rename to src/cli/orchestration/identity/orchestration-structured-session-no-identity.test.ts index ecca72674e7..6e789f53af8 100644 --- a/src/cli/orchestration-structured-session-no-identity.test.ts +++ b/src/cli/orchestration/identity/orchestration-structured-session-no-identity.test.ts @@ -1,13 +1,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { ORCA_STRUCTURED_SESSION_ENV } from '../shared/structured-session-marker' +import { ORCA_STRUCTURED_SESSION_ENV } from '../../../shared/structured-session-marker' const callMock = vi.hoisted(() => vi.fn()) const getTerminalHandleMock = vi.hoisted(() => vi.fn()) -vi.mock('./command-result-output', () => ({ printResult: vi.fn() })) -vi.mock('./terminals/terminal-selector', () => ({ getTerminalHandle: getTerminalHandleMock })) +vi.mock('../../output/command-result-output', () => ({ printResult: vi.fn() })) +vi.mock('../../terminals/terminal-selector', () => ({ getTerminalHandle: getTerminalHandleMock })) -import { ORCHESTRATION_HANDLERS } from './handlers/orchestration' +import { ORCHESTRATION_HANDLERS } from '../orchestration-handlers' const originalMarker = process.env[ORCA_STRUCTURED_SESSION_ENV] const originalHandle = process.env.ORCA_TERMINAL_HANDLE @@ -52,18 +52,4 @@ describe('a structured chat session with no orchestration identity', () => { expect(getTerminalHandleMock).not.toHaveBeenCalled() expect(callMock).not.toHaveBeenCalled() }) - - it('refuses a bare send for the same reason, naming --from', async () => { - await expect( - invoke( - 'orchestration send', - new Map([ - ['to', 'term_coord'], - ['subject', 'hi'], - ['body', 'hello'] - ]) - ) - ).rejects.toMatchObject({ message: expect.stringContaining('--from') }) - expect(callMock).not.toHaveBeenCalled() - }) }) diff --git a/src/cli/session-caller-flags.ts b/src/cli/orchestration/identity/session-caller-flags.ts similarity index 86% rename from src/cli/session-caller-flags.ts rename to src/cli/orchestration/identity/session-caller-flags.ts index 482b2de3d83..b9f7e7ac938 100644 --- a/src/cli/session-caller-flags.ts +++ b/src/cli/orchestration/identity/session-caller-flags.ts @@ -1,12 +1,12 @@ // Fence caller flags before dispatch: older hosts would let a session act as another caller. -import type { CommandSpec, IdentityFlag } from './command-spec' -import { RuntimeClientError } from './runtime/types' +import type { CommandSpec, IdentityFlag } from '../../discovery/command-spec' +import { RuntimeClientError } from '../../runtime/types' import { injectedSessionAddress, readInjectedAgentSessionId -} from '../shared/agent-session/lifecycle/agent-session-caller-env' -import { ORCA_SESSION_ADDRESS_PREFIX } from '../shared/orca-session-address-prefix' +} from '../../../shared/agent-session/lifecycle/agent-session-caller-env' +import { ORCA_SESSION_ADDRESS_PREFIX } from '../../../shared/orca-session-address-prefix' export function refuseConflictingSessionCallerFlags( spec: CommandSpec | undefined, diff --git a/src/cli/handlers/orchestration/terminal-identity.ts b/src/cli/orchestration/identity/terminal-identity.ts similarity index 97% rename from src/cli/handlers/orchestration/terminal-identity.ts rename to src/cli/orchestration/identity/terminal-identity.ts index d219b785356..cf6b47adb42 100644 --- a/src/cli/handlers/orchestration/terminal-identity.ts +++ b/src/cli/orchestration/identity/terminal-identity.ts @@ -1,12 +1,13 @@ -import { getOptionalStringFlag, getPresentStringFlag } from '../../flags' -import { type RuntimeClient, RuntimeClientError } from '../../runtime-client' +import { getOptionalStringFlag, getPresentStringFlag } from '../../arguments/flags' +import type { RuntimeClient } from '../../runtime/client' +import { RuntimeClientError } from '../../runtime/types' import { getTerminalHandle } from '../../terminals/terminal-selector' import { hasStructuredSessionMarker } from '../../../shared/structured-session-marker' import { injectedSessionAddress, readInjectedAgentSessionId } from '../../../shared/agent-session/lifecycle/agent-session-caller-env' -import { sessionAddressForHost } from '../../session-caller-flags' +import { sessionAddressForHost } from './session-caller-flags' // --worktree/--terminal name the command's target, possibly on another host; only the caller's cwd scopes inference. const callerScopeFlags = (): Map => new Map() diff --git a/src/cli/handlers/orchestration/ask-agent-view.ts b/src/cli/orchestration/messages/ask-agent-view.ts similarity index 93% rename from src/cli/handlers/orchestration/ask-agent-view.ts rename to src/cli/orchestration/messages/ask-agent-view.ts index 37644e34055..9be090a0f84 100644 --- a/src/cli/handlers/orchestration/ask-agent-view.ts +++ b/src/cli/orchestration/messages/ask-agent-view.ts @@ -1,8 +1,8 @@ -import { renderCommand } from '../../orchestration-mutation-recovery' -import { resolveOrchestrationCliExecutable } from '../../runtime/orchestration-recovery-command' +import { renderCommand } from '../recovery/orchestration-mutation-recovery' +import { resolveOrchestrationCliExecutable } from '../recovery/orchestration-recovery-command' import type { LegacyCompatibilityResult } from '../../../shared/orchestration/mailbox/orchestration-check-output' -import type { OrchestrationAgentView } from './agent-view' -import { withReceiptNext } from './receipt-next-text' +import type { OrchestrationAgentView } from '../agent-view' +import { withReceiptNext } from '../receipt-next-text' export type AskResult = { answer: string | null diff --git a/src/cli/handlers/orchestration/check-keepalive.ts b/src/cli/orchestration/messages/check-keepalive.ts similarity index 100% rename from src/cli/handlers/orchestration/check-keepalive.ts rename to src/cli/orchestration/messages/check-keepalive.ts diff --git a/src/cli/handlers/orchestration/message-agent-views.ts b/src/cli/orchestration/messages/message-agent-views.ts similarity index 98% rename from src/cli/handlers/orchestration/message-agent-views.ts rename to src/cli/orchestration/messages/message-agent-views.ts index 290fbf4fac2..01799642c33 100644 --- a/src/cli/handlers/orchestration/message-agent-views.ts +++ b/src/cli/orchestration/messages/message-agent-views.ts @@ -7,8 +7,8 @@ import { } from '../../../shared/orchestration/mailbox/orchestration-check-output' import { formatReportFollowUpLine } from '../../../shared/orchestration/mailbox/orchestration-report-follow-up' import { escapeTerminalControlCharacters } from '../../../shared/terminal/output/terminal-control-character-escape' -import { formatFieldPairs, orchestrationCliName, type OrchestrationAgentView } from './agent-view' -import { withReceiptNext } from './receipt-next-text' +import { formatFieldPairs, orchestrationCliName, type OrchestrationAgentView } from '../agent-view' +import { withReceiptNext } from '../receipt-next-text' /** A message as the agent acts on it: storage columns dropped, the payload parsed but kept apart. */ export type MessageView = { diff --git a/src/cli/handlers/orchestration/message-check-handler.ts b/src/cli/orchestration/messages/message-check-handler.ts similarity index 84% rename from src/cli/handlers/orchestration/message-check-handler.ts rename to src/cli/orchestration/messages/message-check-handler.ts index f46543bfea5..86d71061393 100644 --- a/src/cli/handlers/orchestration/message-check-handler.ts +++ b/src/cli/orchestration/messages/message-check-handler.ts @@ -1,12 +1,12 @@ -import type { CommandHandler } from '../../dispatch' -import { refuseAgentServerRoute } from './agent-server-route' -import { printResult } from '../../command-result-output' -import { withReceiptNext } from './receipt-next-text' -import { printOrchestrationResult } from './agent-view' +import type { CommandHandler } from '../../dispatch/dispatch' +import { refuseAgentServerRoute } from '../identity/agent-server-route' +import { printResult } from '../../output/command-result-output' +import { withReceiptNext } from '../receipt-next-text' +import { printOrchestrationResult } from '../agent-view' import { checkView } from './message-agent-views' -import { getOptionalStringFlag } from '../../flags' -import { RuntimeClientError } from '../../runtime-client' -import type { RuntimeRpcSuccess } from '../../runtime-client' +import { getOptionalStringFlag } from '../../arguments/flags' +import { RuntimeClientError } from '../../runtime/types' +import type { RuntimeRpcSuccess } from '../../../shared/runtime-rpc-envelope' import { formatOrchestrationCheckText, prepareOrchestrationCheckOutput, @@ -14,10 +14,16 @@ import { type OrchestrationMessageSummary as MessageSummary } from '../../../shared/orchestration/mailbox/orchestration-check-output' import { startCheckKeepalive } from './check-keepalive' -import { callOrchestrationMutation } from './mutation-request' -import { getOptionalPositiveIntegerValueFlag } from './numeric-flags' -import { flushOrchestrationStdout, resolveCompatibilityCliCommand } from './runtime-compatibility' -import { orchestrationCallerLabel, resolveOrchestrationTerminalHandle } from './terminal-identity' +import { callOrchestrationMutation } from '../recovery/mutation-request' +import { getOptionalPositiveIntegerValueFlag } from '../numeric-flags' +import { + flushOrchestrationStdout, + resolveCompatibilityCliCommand +} from '../recovery/runtime-compatibility' +import { + orchestrationCallerLabel, + resolveOrchestrationTerminalHandle +} from '../identity/terminal-identity' type CheckResult = { messages: MessageSummary[] diff --git a/src/cli/handlers/orchestration/message-inbox-handlers.ts b/src/cli/orchestration/messages/message-inbox-handlers.ts similarity index 89% rename from src/cli/handlers/orchestration/message-inbox-handlers.ts rename to src/cli/orchestration/messages/message-inbox-handlers.ts index 69b29a47a8c..24c18be4b46 100644 --- a/src/cli/handlers/orchestration/message-inbox-handlers.ts +++ b/src/cli/orchestration/messages/message-inbox-handlers.ts @@ -1,20 +1,20 @@ -import type { CommandHandler } from '../../dispatch' -import { printResult } from '../../command-result-output' +import type { CommandHandler } from '../../dispatch/dispatch' +import { printResult } from '../../output/command-result-output' import { getOptionalPositiveIntegerFlag, getOptionalStringFlag, getPresentStringFlag, getRequiredStringFlag -} from '../../flags' +} from '../../arguments/flags' import { formatMessageReadOnlyTag, type OrchestrationMessageSummary as MessageSummary } from '../../../shared/orchestration/mailbox/orchestration-check-output' -import { callOrchestrationMutation } from './mutation-request' -import { requirePeerMailCarrier } from './agent-server-route' -import { resolveOrchestrationTerminalHandle } from './terminal-identity' -import { withReceiptNext } from './receipt-next-text' -import { printOrchestrationResult } from './agent-view' +import { callOrchestrationMutation } from '../recovery/mutation-request' +import { requirePeerMailCarrier } from '../identity/agent-server-route' +import { resolveOrchestrationTerminalHandle } from '../identity/terminal-identity' +import { withReceiptNext } from '../receipt-next-text' +import { printOrchestrationResult } from '../agent-view' import { formatMessageViewText, toMessageView, type MessageView } from './message-agent-views' export const ORCHESTRATION_INBOX_HANDLERS: Record = { diff --git a/src/cli/handlers/orchestration/message-payload.ts b/src/cli/orchestration/messages/message-payload.ts similarity index 95% rename from src/cli/handlers/orchestration/message-payload.ts rename to src/cli/orchestration/messages/message-payload.ts index 26213dd3b00..d0bbda5eead 100644 --- a/src/cli/handlers/orchestration/message-payload.ts +++ b/src/cli/orchestration/messages/message-payload.ts @@ -1,5 +1,5 @@ -import { getOptionalJsonFlag, getOptionalStringFlag } from '../../flags' -import { RuntimeClientError } from '../../runtime-client' +import { getOptionalJsonFlag, getOptionalStringFlag } from '../../arguments/flags' +import { RuntimeClientError } from '../../runtime/types' export function getOptionalStructuredMessagePayload( flags: Map diff --git a/src/cli/handlers/orchestration/message-send-handler.ts b/src/cli/orchestration/messages/message-send-handler.ts similarity index 90% rename from src/cli/handlers/orchestration/message-send-handler.ts rename to src/cli/orchestration/messages/message-send-handler.ts index 08d6129be96..4104625ede1 100644 --- a/src/cli/handlers/orchestration/message-send-handler.ts +++ b/src/cli/orchestration/messages/message-send-handler.ts @@ -1,22 +1,25 @@ -import type { CommandHandler } from '../../dispatch' -import { printResult } from '../../command-result-output' -import { printOrchestrationResult } from './agent-view' -import { withReceiptNext } from './receipt-next-text' -import { formatWorkerStart } from './worker-output' -import { WORKER_FOLLOW_UP_VIEW, type WorkerFollowUpReceipt } from './worker-start-agent-view' -import { withResolvedNextCommands } from '../../orchestration-mutation-recovery' -import { getOptionalStringFlag, getRequiredStringFlag } from '../../flags' -import { RuntimeClientError } from '../../runtime-client' +import type { CommandHandler } from '../../dispatch/dispatch' +import { printResult } from '../../output/command-result-output' +import { printOrchestrationResult } from '../agent-view' +import { withReceiptNext } from '../receipt-next-text' +import { formatWorkerStart } from '../workers/worker-output' +import { + WORKER_FOLLOW_UP_VIEW, + type WorkerFollowUpReceipt +} from '../workers/worker-start-agent-view' +import { withResolvedNextCommands } from '../recovery/orchestration-mutation-recovery' +import { getOptionalStringFlag, getRequiredStringFlag } from '../../arguments/flags' +import { RuntimeClientError } from '../../runtime/types' import { readInjectedAgentSessionId } from '../../../shared/agent-session/lifecycle/agent-session-caller-env' -import { requireWorkerDoneSettlement } from '../orchestration-worker-settlement' +import { requireWorkerDoneSettlement } from '../workers/orchestration-worker-settlement' import { getOptionalStructuredMessagePayload } from './message-payload' -import { callOrchestrationMutation } from './mutation-request' -import { isDevCliInvocation } from './runtime-compatibility' -import { refuseAgentServerRoute, requirePeerMailCarrier } from './agent-server-route' +import { callOrchestrationMutation } from '../recovery/mutation-request' +import { isDevCliInvocation } from '../recovery/runtime-compatibility' +import { refuseAgentServerRoute, requirePeerMailCarrier } from '../identity/agent-server-route' import { resolveOrchestrationTerminalHandle, throwNoActiveSenderTerminal -} from './terminal-identity' +} from '../identity/terminal-identity' const WORKER_DONE_UNAVAILABLE_RETRY_MS = 120_000 diff --git a/src/cli/handlers/orchestration-check-identity.test.ts b/src/cli/orchestration/messages/orchestration-check-identity.test.ts similarity index 86% rename from src/cli/handlers/orchestration-check-identity.test.ts rename to src/cli/orchestration/messages/orchestration-check-identity.test.ts index 98df085d5fa..e53408fe198 100644 --- a/src/cli/handlers/orchestration-check-identity.test.ts +++ b/src/cli/orchestration/messages/orchestration-check-identity.test.ts @@ -6,10 +6,10 @@ const originalTerminalHandle = process.env.ORCA_TERMINAL_HANDLE const originalPaneKey = process.env.ORCA_PANE_KEY const printResultMock = vi.hoisted(() => vi.fn()) -vi.mock('../command-result-output', () => ({ printResult: printResultMock })) -vi.mock('../terminals/terminal-selector', () => ({ getTerminalHandle: getTerminalHandleMock })) +vi.mock('../../output/command-result-output', () => ({ printResult: printResultMock })) +vi.mock('../../terminals/terminal-selector', () => ({ getTerminalHandle: getTerminalHandleMock })) -import { ORCHESTRATION_HANDLERS } from './orchestration' +import { ORCHESTRATION_HANDLERS } from '../orchestration-handlers' describe('orchestration check identity', () => { beforeEach(() => { diff --git a/src/cli/handlers/orchestration/question-handler.ts b/src/cli/orchestration/messages/question-handler.ts similarity index 88% rename from src/cli/handlers/orchestration/question-handler.ts rename to src/cli/orchestration/messages/question-handler.ts index 3c7e92f98bb..b85024eec51 100644 --- a/src/cli/handlers/orchestration/question-handler.ts +++ b/src/cli/orchestration/messages/question-handler.ts @@ -1,28 +1,29 @@ -import type { CommandHandler } from '../../dispatch' -import { getOptionalStringFlag } from '../../flags' -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' +import type { CommandHandler } from '../../dispatch/dispatch' +import { getOptionalStringFlag } from '../../arguments/flags' +import { printResult } from '../../output/command-result-output' +import { renderCommand } from '../recovery/orchestration-mutation-recovery' +import { RuntimeClientError } from '../../runtime/types' +import type { RuntimeClient } from '../../runtime/client' +import type { RuntimeStatus } from '../../../shared/runtime-session-contracts' import { ORCHESTRATION_ASK_RETURNS_AT_ONCE_RUNTIME_CAPABILITY } from '../../../shared/orchestration/orchestration-runtime-capabilities' -import { resolveOrchestrationCliExecutable } from '../../runtime/orchestration-recovery-command' +import { resolveOrchestrationCliExecutable } from '../recovery/orchestration-recovery-command' import { clampOrchestrationAskTimeoutMs, ORCHESTRATION_ASK_MAX_TIMEOUT_MS, resolveOrchestrationAskClientTimeoutMs } from '../../../shared/orchestration/mailbox/orchestration-ask-timeout' import type { LegacyCompatibilityResult } from '../../../shared/orchestration/mailbox/orchestration-check-output' -import { callOrchestrationMutation } from './mutation-request' -import { withReceiptNext } from './receipt-next-text' +import { callOrchestrationMutation } from '../recovery/mutation-request' +import { withReceiptNext } from '../receipt-next-text' import { askView, type AskResult } from './ask-agent-view' -import { printOrchestrationResult } from './agent-view' -import { getOptionalPositiveIntegerValueFlag } from './numeric-flags' +import { printOrchestrationResult } from '../agent-view' +import { getOptionalPositiveIntegerValueFlag } from '../numeric-flags' import { flushOrchestrationStdout, resolveCompatibilityCliCommand, resolvePackagedWindowsCompatibilityCommand -} from './runtime-compatibility' -import { resolveOrchestrationTerminalHandle } from './terminal-identity' +} from '../recovery/runtime-compatibility' +import { resolveOrchestrationTerminalHandle } from '../identity/terminal-identity' async function runtimeLacksAskAtOnce(client: RuntimeClient): Promise { const status = await client.call('status.get') diff --git a/src/cli/handlers/orchestration/numeric-flags.ts b/src/cli/orchestration/numeric-flags.ts similarity index 81% rename from src/cli/handlers/orchestration/numeric-flags.ts rename to src/cli/orchestration/numeric-flags.ts index 9d3a142150c..1eff6ff442e 100644 --- a/src/cli/handlers/orchestration/numeric-flags.ts +++ b/src/cli/orchestration/numeric-flags.ts @@ -1,5 +1,5 @@ -import { parsePositiveSafeIntegerText } from '../../../shared/timer-delay' -import { RuntimeClientError } from '../../runtime-client' +import { parsePositiveSafeIntegerText } from '../../shared/timer-delay' +import { RuntimeClientError } from '../runtime/types' export function getOptionalPositiveIntegerValueFlag( flags: Map, diff --git a/src/cli/index-orchestration.test.ts b/src/cli/orchestration/orchestration-entry.test.ts similarity index 72% rename from src/cli/index-orchestration.test.ts rename to src/cli/orchestration/orchestration-entry.test.ts index b7bf7989851..10bf9104cfc 100644 --- a/src/cli/index-orchestration.test.ts +++ b/src/cli/orchestration/orchestration-entry.test.ts @@ -18,8 +18,8 @@ const { spawnMock: vi.fn() })) -vi.mock('./runtime-client', async () => { - const { createRuntimeClientModuleMock } = await import('./index-test-harness.js') +vi.mock('../runtime/client', async () => { + const { createRuntimeClientModuleMock } = await import('../index-test-harness.js') return createRuntimeClientModuleMock({ callMock, runtimeClientConstructorMock, @@ -28,23 +28,33 @@ vi.mock('./runtime-client', async () => { }) }) -vi.mock('./runtime/environments', () => ({ +vi.mock('../runtime/launch', async (importOriginal) => ({ + ...(await importOriginal>()), + serveOrcaApp: serveOrcaAppMock +})) + +vi.mock('../runtime/metadata', async (importOriginal) => ({ + ...(await importOriginal>()), + getDefaultUserDataPath: getDefaultUserDataPathMock +})) + +vi.mock('../runtime/environments', () => ({ addEnvironmentFromPairingCode: addEnvironmentFromPairingCodeMock, removeEnvironment: vi.fn(), resolveEnvironment: vi.fn() })) -vi.mock('../shared/remote-runtime/host-store/runtime-environment-store', () => ({ +vi.mock('../../shared/remote-runtime/host-store/runtime-environment-store', () => ({ listEnvironments: listEnvironmentsMock })) vi.mock('child_process', async () => { - const { createChildProcessModuleMock } = await import('./index-test-harness.js') + const { createChildProcessModuleMock } = await import('../index-test-harness.js') return createChildProcessModuleMock(spawnMock) }) -import { main } from './index' -import { useWorktreeAwarenessEnvironment } from './index-test-harness' +import { main } from '../index' +import { useWorktreeAwarenessEnvironment } from '../index-test-harness' describe('orca cli worktree awareness', () => { const priorExitCode = process.exitCode diff --git a/src/cli/handlers/orchestration-handler-test-context.ts b/src/cli/orchestration/orchestration-handler-test-context.ts similarity index 81% rename from src/cli/handlers/orchestration-handler-test-context.ts rename to src/cli/orchestration/orchestration-handler-test-context.ts index 5bb06bcdce7..72b16bd66ad 100644 --- a/src/cli/handlers/orchestration-handler-test-context.ts +++ b/src/cli/orchestration/orchestration-handler-test-context.ts @@ -1,6 +1,6 @@ import { vi, type Mock } from 'vitest' -import type { HandlerContext } from '../dispatch' -import { RuntimeClient } from '../runtime-client' +import type { HandlerContext } from '../dispatch/dispatch' +import { RuntimeClient } from '../runtime/client' /** A handler context whose runtime calls go to `call`, to drive one command in a unit test. */ export function orchestrationTestContext( diff --git a/src/cli/orchestration/orchestration-handlers.ts b/src/cli/orchestration/orchestration-handlers.ts new file mode 100644 index 00000000000..c0d97589218 --- /dev/null +++ b/src/cli/orchestration/orchestration-handlers.ts @@ -0,0 +1,34 @@ +import type { CommandHandler } from '../dispatch/dispatch' +import { ORCHESTRATION_CHECK_HANDLER } from './messages/message-check-handler' +import { + ORCHESTRATION_DISPATCH_HANDLER, + ORCHESTRATION_DISPATCH_INSPECTION_HANDLERS +} from './dispatches/dispatch-handlers' +import { ORCHESTRATION_GATE_HANDLERS } from './gates/gate-handlers' +import { ORCHESTRATION_INBOX_HANDLERS } from './messages/message-inbox-handlers' +import { ORCHESTRATION_QUESTION_HANDLER } from './messages/question-handler' +import { ORCHESTRATION_REQUEST_SHOW_HANDLER } from './recovery/mutation-request-show-handler' +import { ORCHESTRATION_RESET_HANDLER } from './runs/reset-handler' +import { ORCHESTRATION_RUN_HANDLERS } from './runs/run-handlers' +import { ORCHESTRATION_SEND_HANDLER } from './messages/message-send-handler' +import { ORCHESTRATION_TASK_HANDLERS } from './tasks/task-handlers' +import { ORCHESTRATION_WORKER_LAUNCH_HANDLER } from './workers/worker-launch-handler' +import { ORCHESTRATION_WORKER_OBSERVATION_HANDLERS } from './workers/worker-observation-handlers' +import { ORCHESTRATION_WORKER_TERMINAL_HANDLERS } from './workers/worker-terminal-handlers' + +export const ORCHESTRATION_HANDLERS: Record = { + ...ORCHESTRATION_RUN_HANDLERS, + ...ORCHESTRATION_SEND_HANDLER, + ...ORCHESTRATION_CHECK_HANDLER, + ...ORCHESTRATION_INBOX_HANDLERS, + ...ORCHESTRATION_TASK_HANDLERS, + ...ORCHESTRATION_WORKER_LAUNCH_HANDLER, + ...ORCHESTRATION_WORKER_OBSERVATION_HANDLERS, + ...ORCHESTRATION_WORKER_TERMINAL_HANDLERS, + ...ORCHESTRATION_DISPATCH_HANDLER, + ...ORCHESTRATION_QUESTION_HANDLER, + ...ORCHESTRATION_DISPATCH_INSPECTION_HANDLERS, + ...ORCHESTRATION_REQUEST_SHOW_HANDLER, + ...ORCHESTRATION_GATE_HANDLERS, + ...ORCHESTRATION_RESET_HANDLER +} diff --git a/src/cli/handlers/orchestration.test.ts b/src/cli/orchestration/orchestration.test.ts similarity index 91% rename from src/cli/handlers/orchestration.test.ts rename to src/cli/orchestration/orchestration.test.ts index 65a622758db..1054b597146 100644 --- a/src/cli/handlers/orchestration.test.ts +++ b/src/cli/orchestration/orchestration.test.ts @@ -4,13 +4,13 @@ const callMock = vi.fn() const getTerminalHandleMock = vi.hoisted(() => vi.fn()) const originalExitCode = process.exitCode -vi.mock('../command-result-output', () => ({ printResult: vi.fn() })) +vi.mock('../output/command-result-output', () => ({ printResult: vi.fn() })) vi.mock('../terminals/terminal-selector', () => ({ getTerminalHandle: getTerminalHandleMock })) -import { ORCHESTRATION_HANDLERS } from './orchestration' +import { ORCHESTRATION_HANDLERS } from './orchestration-handlers' -import { printResult } from '../command-result-output' -import { okFixture } from '../test-fixtures' +import { printResult } from '../output/command-result-output' +import { okFixture } from '../runtime/fixtures/runtime-rpc-fixtures' beforeEach(() => { callMock.mockReset() diff --git a/src/cli/handlers/orchestration/receipt-next-text.ts b/src/cli/orchestration/receipt-next-text.ts similarity index 100% rename from src/cli/handlers/orchestration/receipt-next-text.ts rename to src/cli/orchestration/receipt-next-text.ts diff --git a/src/cli/handlers/orchestration/mutation-request-show-handler.ts b/src/cli/orchestration/recovery/mutation-request-show-handler.ts similarity index 86% rename from src/cli/handlers/orchestration/mutation-request-show-handler.ts rename to src/cli/orchestration/recovery/mutation-request-show-handler.ts index 5438fc70500..fa08b7db7cf 100644 --- a/src/cli/handlers/orchestration/mutation-request-show-handler.ts +++ b/src/cli/orchestration/recovery/mutation-request-show-handler.ts @@ -1,7 +1,7 @@ -import type { CommandHandler } from '../../dispatch' -import { printOrchestrationReceipt } from './agent-view' -import { getOptionalStringFlag, getRequiredStringFlag } from '../../flags' -import { RuntimeClientError } from '../../runtime-client' +import type { CommandHandler } from '../../dispatch/dispatch' +import { printOrchestrationReceipt } from '../agent-view' +import { getOptionalStringFlag, getRequiredStringFlag } from '../../arguments/flags' +import { RuntimeClientError } from '../../runtime/types' import type { OrchestrationMutationRequestShowResult } from '../../../shared/orchestration/orchestration-mutation-request' export const ORCHESTRATION_REQUEST_SHOW_HANDLER: Record = { diff --git a/src/cli/handlers/orchestration/mutation-request.ts b/src/cli/orchestration/recovery/mutation-request.ts similarity index 89% rename from src/cli/handlers/orchestration/mutation-request.ts rename to src/cli/orchestration/recovery/mutation-request.ts index e45176b3fb9..e1e4fe27a78 100644 --- a/src/cli/handlers/orchestration/mutation-request.ts +++ b/src/cli/orchestration/recovery/mutation-request.ts @@ -1,7 +1,8 @@ import { randomUUID } from 'node:crypto' -import { RuntimeClientError, type RuntimeClient } from '../../runtime-client' -import { readRetryRequestFlag } from '../../retry-request-flag' -import { orchestrationMutationRecoveryError } from '../../orchestration-mutation-recovery' +import { RuntimeClientError } from '../../runtime/types' +import type { RuntimeClient } from '../../runtime/client' +import { readRetryRequestFlag } from './retry-request-flag' +import { orchestrationMutationRecoveryError } from './orchestration-mutation-recovery' import { isRequestUnsent } from '../../runtime/client-error-recovery' const MAX_UNAVAILABLE_RETRY_DELAY_MS = 15_000 diff --git a/src/cli/handlers/orchestration/older-runtime-run-binding.test.ts b/src/cli/orchestration/recovery/older-runtime-run-binding.test.ts similarity index 86% rename from src/cli/handlers/orchestration/older-runtime-run-binding.test.ts rename to src/cli/orchestration/recovery/older-runtime-run-binding.test.ts index bcee11ef995..ca975dc258f 100644 --- a/src/cli/handlers/orchestration/older-runtime-run-binding.test.ts +++ b/src/cli/orchestration/recovery/older-runtime-run-binding.test.ts @@ -1,7 +1,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { ORCHESTRATION_HANDLERS } from '../orchestration' -import { RuntimeClient, RuntimeClientError } from '../../runtime-client' -import { okFixture } from '../../test-fixtures' +import { ORCHESTRATION_HANDLERS } from '../orchestration-handlers' +import { RuntimeClient } from '../../runtime/client' +import { RuntimeClientError } from '../../runtime/types' +import { okFixture } from '../../runtime/fixtures/runtime-rpc-fixtures' const client = new RuntimeClient('/tmp/orca-older-runtime-run', 60_000, null, null) diff --git a/src/cli/handlers/orchestration/older-runtime-run-binding.ts b/src/cli/orchestration/recovery/older-runtime-run-binding.ts similarity index 87% rename from src/cli/handlers/orchestration/older-runtime-run-binding.ts rename to src/cli/orchestration/recovery/older-runtime-run-binding.ts index d9a719e0204..c136396f449 100644 --- a/src/cli/handlers/orchestration/older-runtime-run-binding.ts +++ b/src/cli/orchestration/recovery/older-runtime-run-binding.ts @@ -1,10 +1,11 @@ -import { RuntimeClientError, type RuntimeClient } from '../../runtime-client' -import type { RuntimeStatus } from '../../../shared/runtime-types' +import { RuntimeClientError } from '../../runtime/types' +import type { RuntimeClient } from '../../runtime/client' +import type { RuntimeStatus } from '../../../shared/runtime-session-contracts' import { ORCHESTRATION_RETAINED_RUN_BINDINGS_RUNTIME_CAPABILITY, ORCHESTRATION_WORKER_START_IMPLICIT_RUN_RUNTIME_CAPABILITY } from '../../../shared/orchestration/orchestration-runtime-capabilities' -import { resolveOrchestrationCliExecutable } from '../../runtime/orchestration-recovery-command' +import { resolveOrchestrationCliExecutable } from './orchestration-recovery-command' async function runtimeLacks(client: RuntimeClient, capability: string): Promise { const status = await client.call('status.get') diff --git a/src/cli/handlers/orchestration-legacy-read-only.test.ts b/src/cli/orchestration/recovery/orchestration-legacy-read-only.test.ts similarity index 93% rename from src/cli/handlers/orchestration-legacy-read-only.test.ts rename to src/cli/orchestration/recovery/orchestration-legacy-read-only.test.ts index bf2d528ecd5..8c2bd979a82 100644 --- a/src/cli/handlers/orchestration-legacy-read-only.test.ts +++ b/src/cli/orchestration/recovery/orchestration-legacy-read-only.test.ts @@ -2,12 +2,12 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' const callMock = vi.fn() -vi.mock('../command-result-output', () => ({ printResult: vi.fn() })) -vi.mock('../terminals/terminal-selector', () => ({ getTerminalHandle: vi.fn() })) +vi.mock('../../output/command-result-output', () => ({ printResult: vi.fn() })) +vi.mock('../../terminals/terminal-selector', () => ({ getTerminalHandle: vi.fn() })) -import { printResult } from '../command-result-output' -import { ORCHESTRATION_HANDLERS } from './orchestration' -import { orchestrationTestContext } from './orchestration-handler-test-context' +import { printResult } from '../../output/command-result-output' +import { ORCHESTRATION_HANDLERS } from '../orchestration-handlers' +import { orchestrationTestContext } from '../orchestration-handler-test-context' beforeEach(() => { callMock.mockReset() diff --git a/src/cli/handlers/orchestration-lifecycle-rejection.test.ts b/src/cli/orchestration/recovery/orchestration-lifecycle-rejection.test.ts similarity index 69% rename from src/cli/handlers/orchestration-lifecycle-rejection.test.ts rename to src/cli/orchestration/recovery/orchestration-lifecycle-rejection.test.ts index d9e54eada37..eca8515ad63 100644 --- a/src/cli/handlers/orchestration-lifecycle-rejection.test.ts +++ b/src/cli/orchestration/recovery/orchestration-lifecycle-rejection.test.ts @@ -2,11 +2,10 @@ import { afterEach, expect, it, vi } from 'vitest' const callMock = vi.fn() const originalExitCode = process.exitCode -vi.mock('../command-result-output', () => ({ printResult: vi.fn() })) -vi.mock('../terminals/terminal-selector', () => ({ getTerminalHandle: vi.fn() })) +vi.mock('../../output/command-result-output', () => ({ printResult: vi.fn() })) +vi.mock('../../terminals/terminal-selector', () => ({ getTerminalHandle: vi.fn() })) -import { printResult } from '../command-result-output' -import { ORCHESTRATION_HANDLERS } from './orchestration' +import { ORCHESTRATION_HANDLERS } from '../orchestration-handlers' afterEach(() => { process.exitCode = originalExitCode @@ -14,76 +13,6 @@ afterEach(() => { callMock.mockReset() }) -it('raises a lifecycle rejection for the CLI error boundary', async () => { - const response = { - result: { - message: { id: 'msg_rejected' }, - lifecycle: { - action: 'rejected' as const, - code: 'sender_not_assignee', - reason: 'dispatch ctx_1 expected the assigned pane' - } - } - } - callMock.mockResolvedValueOnce(response) - - await expect( - ORCHESTRATION_HANDLERS['orchestration send']({ - flags: new Map([ - ['from', 'term_foreign'], - ['to', 'term_coord'], - ['subject', 'done'], - ['type', 'worker_done'], - ['outcome', 'succeeded'] - ]), - client: { call: callMock }, - cwd: '/tmp/repo', - json: false - } as never) - ).rejects.toMatchObject({ - code: 'sender_not_assignee', - message: 'dispatch ctx_1 expected the assigned pane' - }) - expect(printResult).not.toHaveBeenCalled() -}) - -it('raises a Run-home relay rejection for the CLI error boundary', async () => { - callMock.mockResolvedValueOnce({ - result: { - relay: { - messageId: 'relay_rejected', - sequence: 1, - dispatchId: 'ctx_1', - destination: 'run_home', - accepted: true - }, - lifecycle: { - action: 'rejected', - code: 'task_dispatch_mismatch', - reason: 'wrong task', - authority: 'run_home' - } - } - }) - - await expect( - ORCHESTRATION_HANDLERS['orchestration send']({ - flags: new Map([ - ['from', 'term_worker'], - ['subject', 'done'], - ['type', 'worker_done'], - ['task-id', 'task_wrong'], - ['dispatch-id', 'ctx_1'], - ['outcome', 'succeeded'] - ]), - client: { call: callMock }, - cwd: '/tmp/repo', - json: true - } as never) - ).rejects.toMatchObject({ code: 'task_dispatch_mismatch', message: 'wrong task' }) - expect(printResult).not.toHaveBeenCalled() -}) - it('fails closed when an older runtime leaves worker_done dispatched without a verdict', async () => { callMock .mockResolvedValueOnce({ diff --git a/src/cli/orchestration-mutation-recovery.test.ts b/src/cli/orchestration/recovery/orchestration-mutation-recovery.test.ts similarity index 97% rename from src/cli/orchestration-mutation-recovery.test.ts rename to src/cli/orchestration/recovery/orchestration-mutation-recovery.test.ts index 4d417506c90..187e6e0c77c 100644 --- a/src/cli/orchestration-mutation-recovery.test.ts +++ b/src/cli/orchestration/recovery/orchestration-mutation-recovery.test.ts @@ -4,7 +4,7 @@ import { orchestrationMutationRecoveryError, renderCommand } from './orchestration-mutation-recovery' -import { RuntimeClientError } from './runtime-client' +import { RuntimeClientError } from '../../runtime/types' describe('orchestration mutation recovery', () => { it.runIf(process.platform !== 'win32')( diff --git a/src/cli/orchestration-mutation-recovery.ts b/src/cli/orchestration/recovery/orchestration-mutation-recovery.ts similarity index 94% rename from src/cli/orchestration-mutation-recovery.ts rename to src/cli/orchestration/recovery/orchestration-mutation-recovery.ts index 9003b025fbf..4a799e7f03e 100644 --- a/src/cli/orchestration-mutation-recovery.ts +++ b/src/cli/orchestration/recovery/orchestration-mutation-recovery.ts @@ -1,13 +1,13 @@ -import { quotePosixShellDoubleQuotedApostrophe } from '../shared/shell/launch/shell-argument-quoting' -import { RuntimeClientError, RuntimeRpcFailureError } from './runtime-client' +import { quotePosixShellDoubleQuotedApostrophe } from '../../../shared/shell/launch/shell-argument-quoting' +import { RuntimeClientError, RuntimeRpcFailureError } from '../../runtime/types' import { recoverableOrchestrationArgs, resolveOrchestrationCliExecutable -} from './runtime/orchestration-recovery-command' +} from './orchestration-recovery-command' import { quoteWindowsCmdArgument } from '@orca/process-host/windows-command-line' -import { quotePowerShellNativeArgument } from '../shared/powershell-native-argument' -import { resolveWindowsShellStartupFamily } from '../shared/windows-terminal-shell' -import type { AgentStartupShell } from '../shared/agent-launch/startup/tui-agent-startup-shell' +import { quotePowerShellNativeArgument } from '../../../shared/powershell-native-argument' +import { resolveWindowsShellStartupFamily } from '../../../shared/windows-terminal-shell' +import type { AgentStartupShell } from '../../../shared/agent-launch/startup/tui-agent-startup-shell' export function orchestrationMutationRecoveryError( error: unknown, diff --git a/src/cli/runtime/orchestration-recovery-command.test.ts b/src/cli/orchestration/recovery/orchestration-recovery-command.test.ts similarity index 100% rename from src/cli/runtime/orchestration-recovery-command.test.ts rename to src/cli/orchestration/recovery/orchestration-recovery-command.test.ts diff --git a/src/cli/runtime/orchestration-recovery-command.ts b/src/cli/orchestration/recovery/orchestration-recovery-command.ts similarity index 100% rename from src/cli/runtime/orchestration-recovery-command.ts rename to src/cli/orchestration/recovery/orchestration-recovery-command.ts diff --git a/src/cli/retry-request-flag.ts b/src/cli/orchestration/recovery/retry-request-flag.ts similarity index 75% rename from src/cli/retry-request-flag.ts rename to src/cli/orchestration/recovery/retry-request-flag.ts index acbc2982b2e..a8a59a849f7 100644 --- a/src/cli/retry-request-flag.ts +++ b/src/cli/orchestration/recovery/retry-request-flag.ts @@ -1,9 +1,9 @@ -import { rejectValuelessFlag } from './flags' -import { RuntimeClientError } from './runtime/types' +import { rejectValuelessFlag } from '../../arguments/flags' +import { RuntimeClientError } from '../../runtime/types' import { isOrchestrationRetryRequestId, RETRY_REQUEST_ID_GUIDANCE -} from '../shared/orchestration/orchestration-retry-request-id' +} from '../../../shared/orchestration/orchestration-retry-request-id' /** Reject damaged identities: falling back to a fresh id could replay an already-applied mutation. */ export function readRetryRequestFlag(flags: Map): string | undefined { diff --git a/src/cli/handlers/orchestration/runtime-compatibility.ts b/src/cli/orchestration/recovery/runtime-compatibility.ts similarity index 95% rename from src/cli/handlers/orchestration/runtime-compatibility.ts rename to src/cli/orchestration/recovery/runtime-compatibility.ts index e4076534daa..3ccfadc8208 100644 --- a/src/cli/handlers/orchestration/runtime-compatibility.ts +++ b/src/cli/orchestration/recovery/runtime-compatibility.ts @@ -1,4 +1,4 @@ -import { RuntimeClientError } from '../../runtime-client' +import { RuntimeClientError } from '../../runtime/types' export function resolveCompatibilityCliCommand(): 'orca' | 'orca-ide' | 'orca-dev' { const configured = process.env.ORCA_CLI_COMMAND diff --git a/src/cli/handlers/orchestration/removed-work-format.ts b/src/cli/orchestration/runs/removed-work-format.ts similarity index 100% rename from src/cli/handlers/orchestration/removed-work-format.ts rename to src/cli/orchestration/runs/removed-work-format.ts diff --git a/src/cli/handlers/orchestration/reset-handler.ts b/src/cli/orchestration/runs/reset-handler.ts similarity index 80% rename from src/cli/handlers/orchestration/reset-handler.ts rename to src/cli/orchestration/runs/reset-handler.ts index d0a38bbf7dc..681b2cd86f5 100644 --- a/src/cli/handlers/orchestration/reset-handler.ts +++ b/src/cli/orchestration/runs/reset-handler.ts @@ -1,8 +1,8 @@ -import type { CommandHandler } from '../../dispatch' -import { printOrchestrationReceipt } from './agent-view' -import { RuntimeClientError } from '../../runtime-client' +import type { CommandHandler } from '../../dispatch/dispatch' +import { printOrchestrationReceipt } from '../agent-view' +import { RuntimeClientError } from '../../runtime/types' import type { ResetRemovedWork } from '../../../shared/orchestration/orchestration-removed-work' -import { callOrchestrationMutation } from './mutation-request' +import { callOrchestrationMutation } from '../recovery/mutation-request' import { formatResetResult } from './removed-work-format' export const ORCHESTRATION_RESET_HANDLER: Record = { diff --git a/src/cli/handlers/orchestration/run-handlers.ts b/src/cli/orchestration/runs/run-handlers.ts similarity index 92% rename from src/cli/handlers/orchestration/run-handlers.ts rename to src/cli/orchestration/runs/run-handlers.ts index 0f39760b493..c7815cb44e6 100644 --- a/src/cli/handlers/orchestration/run-handlers.ts +++ b/src/cli/orchestration/runs/run-handlers.ts @@ -1,22 +1,22 @@ import { abbreviateOrchestrationText } from '../../../shared/orchestration/orchestration-task-summary' -import type { CommandHandler } from '../../dispatch' -import { printResult } from '../../command-result-output' -import { printOrchestrationResult } from './agent-view' +import type { CommandHandler } from '../../dispatch/dispatch' +import { printResult } from '../../output/command-result-output' +import { printOrchestrationResult } from '../agent-view' import { getOptionalPositiveIntegerFlag, getOptionalStringFlag, getRequiredStringFlag -} from '../../flags' +} from '../../arguments/flags' import { ORCHESTRATION_RUN_PAGE_LIMIT } from '../../../shared/orchestration/orchestration-run-pagination' import type { RunRemovedWork } from '../../../shared/orchestration/orchestration-removed-work' -import { callOrchestrationMutation } from './mutation-request' +import { callOrchestrationMutation } from '../recovery/mutation-request' import { formatRemovedWorkListing, formatRunRemovedWorkLine } from './removed-work-format' -import { resolveCoordinatorTerminalHandle } from './terminal-identity' -import { withReceiptNext } from './receipt-next-text' +import { resolveCoordinatorTerminalHandle } from '../identity/terminal-identity' +import { withReceiptNext } from '../receipt-next-text' import { findRunOlderRuntimeWillUnbind, olderRuntimeUnboundRunNext -} from './older-runtime-run-binding' +} from '../recovery/older-runtime-run-binding' const RUN_LIST_DEFAULT_LIMIT = 10 diff --git a/src/cli/handlers/orchestration-task-list-brief.test.ts b/src/cli/orchestration/tasks/orchestration-task-list-brief.test.ts similarity index 83% rename from src/cli/handlers/orchestration-task-list-brief.test.ts rename to src/cli/orchestration/tasks/orchestration-task-list-brief.test.ts index e727e250588..88f2193331e 100644 --- a/src/cli/handlers/orchestration-task-list-brief.test.ts +++ b/src/cli/orchestration/tasks/orchestration-task-list-brief.test.ts @@ -2,12 +2,12 @@ import { afterEach, describe, expect, it, vi } from 'vitest' const callMock = vi.fn() -vi.mock('../command-result-output', () => ({ printResult: vi.fn() })) +vi.mock('../../output/command-result-output', () => ({ printResult: vi.fn() })) -import { ORCHESTRATION_HANDLERS } from './orchestration' -import { printResult } from '../command-result-output' -import { okFixture } from '../test-fixtures' -import { RuntimeClient } from '../runtime-client' +import { ORCHESTRATION_HANDLERS } from '../orchestration-handlers' +import { printResult } from '../../output/command-result-output' +import { okFixture } from '../../runtime/fixtures/runtime-rpc-fixtures' +import { RuntimeClient } from '../../runtime/client' const client = new RuntimeClient('/tmp/orca-task-brief', 60_000, null, null) afterEach(() => vi.restoreAllMocks()) diff --git a/src/cli/handlers/orchestration/task-agent-views.ts b/src/cli/orchestration/tasks/task-agent-views.ts similarity index 95% rename from src/cli/handlers/orchestration/task-agent-views.ts rename to src/cli/orchestration/tasks/task-agent-views.ts index 1b2d86eb75f..cd9545770ff 100644 --- a/src/cli/handlers/orchestration/task-agent-views.ts +++ b/src/cli/orchestration/tasks/task-agent-views.ts @@ -1,4 +1,4 @@ -import type { OrchestrationAgentView } from './agent-view' +import type { OrchestrationAgentView } from '../agent-view' export type TaskListResult = { tasks: { diff --git a/src/cli/handlers/orchestration/task-handlers.ts b/src/cli/orchestration/tasks/task-handlers.ts similarity index 88% rename from src/cli/handlers/orchestration/task-handlers.ts rename to src/cli/orchestration/tasks/task-handlers.ts index 708d0ce6da1..a10920b3b0a 100644 --- a/src/cli/handlers/orchestration/task-handlers.ts +++ b/src/cli/orchestration/tasks/task-handlers.ts @@ -1,13 +1,16 @@ -import type { CommandHandler } from '../../dispatch' -import { printResult } from '../../command-result-output' -import { printOrchestrationResult } from './agent-view' +import type { CommandHandler } from '../../dispatch/dispatch' +import { printResult } from '../../output/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' -import { RuntimeClientError } from '../../runtime-client' +import { getOptionalStringFlag, getRequiredStringFlag } from '../../arguments/flags' +import { RuntimeClientError } from '../../runtime/types' import { abbreviateOrchestrationTasks } from '../../../shared/orchestration/orchestration-task-summary' -import { callOrchestrationMutation } from './mutation-request' -import { readTextOrFileFlag } from '../../command-body-input' -import { resolveCoordinatorTerminalHandle, runScopedSessionCaller } from './terminal-identity' +import { callOrchestrationMutation } from '../recovery/mutation-request' +import { readTextOrFileFlag } from '../../arguments/command-body-input' +import { + resolveCoordinatorTerminalHandle, + runScopedSessionCaller +} from '../identity/terminal-identity' const TASK_STATUS_VALUES = [ 'pending', diff --git a/src/cli/handlers/orchestration-federated-legacy-settlement.test.ts b/src/cli/orchestration/workers/orchestration-federated-legacy-settlement.test.ts similarity index 77% rename from src/cli/handlers/orchestration-federated-legacy-settlement.test.ts rename to src/cli/orchestration/workers/orchestration-federated-legacy-settlement.test.ts index b386ccb1691..973fa528409 100644 --- a/src/cli/handlers/orchestration-federated-legacy-settlement.test.ts +++ b/src/cli/orchestration/workers/orchestration-federated-legacy-settlement.test.ts @@ -2,11 +2,11 @@ import { afterEach, expect, it, vi } from 'vitest' const callMock = vi.fn() const printResultMock = vi.hoisted(() => vi.fn()) -vi.mock('../command-result-output', () => ({ printResult: printResultMock })) -vi.mock('../terminals/terminal-selector', () => ({ getTerminalHandle: vi.fn() })) +vi.mock('../../output/command-result-output', () => ({ printResult: printResultMock })) +vi.mock('../../terminals/terminal-selector', () => ({ getTerminalHandle: vi.fn() })) -import { ORCHESTRATION_HANDLERS } from './orchestration' -import { orchestrationTestContext } from './orchestration-handler-test-context' +import { ORCHESTRATION_HANDLERS } from '../orchestration-handlers' +import { orchestrationTestContext } from '../orchestration-handler-test-context' afterEach(() => { callMock.mockReset() diff --git a/src/cli/handlers/orchestration-worker-cli.test.ts b/src/cli/orchestration/workers/orchestration-worker-cli.test.ts similarity index 83% rename from src/cli/handlers/orchestration-worker-cli.test.ts rename to src/cli/orchestration/workers/orchestration-worker-cli.test.ts index f44ce4bc8cf..da129809833 100644 --- a/src/cli/handlers/orchestration-worker-cli.test.ts +++ b/src/cli/orchestration/workers/orchestration-worker-cli.test.ts @@ -2,16 +2,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const callMock = vi.fn() const originalExitCode = process.exitCode -vi.mock('../command-result-output', async (importOriginal) => { +vi.mock('../../output/command-result-output', async (importOriginal) => { const original = await importOriginal<{ printResult: typeof printResult }>() return { printResult: vi.fn(original.printResult) } }) -vi.mock('../terminals/terminal-selector', () => ({ getTerminalHandle: vi.fn() })) +vi.mock('../../terminals/terminal-selector', () => ({ getTerminalHandle: vi.fn() })) -import { ORCHESTRATION_HANDLERS } from './orchestration' -import { printResult } from '../command-result-output' +import { ORCHESTRATION_HANDLERS } from '../orchestration-handlers' +import { printResult } from '../../output/command-result-output' -import { RuntimeClient } from '../runtime-client' +import { RuntimeClient } from '../../runtime/client' const client = new RuntimeClient('/tmp/orca-worker-cli', 60_000, null, null) diff --git a/src/cli/handlers/orchestration-worker-settlement.ts b/src/cli/orchestration/workers/orchestration-worker-settlement.ts similarity index 97% rename from src/cli/handlers/orchestration-worker-settlement.ts rename to src/cli/orchestration/workers/orchestration-worker-settlement.ts index 4a71d88e7b7..928cb7e2d1b 100644 --- a/src/cli/handlers/orchestration-worker-settlement.ts +++ b/src/cli/orchestration/workers/orchestration-worker-settlement.ts @@ -1,5 +1,5 @@ -import type { RuntimeClient } from '../runtime-client' -import { RuntimeClientError } from '../runtime-client' +import type { RuntimeClient } from '../../runtime/client' +import { RuntimeClientError } from '../../runtime/types' export async function requireWorkerDoneSettlement( client: RuntimeClient, diff --git a/src/cli/handlers/orchestration/worker-agent-views.ts b/src/cli/orchestration/workers/worker-agent-views.ts similarity index 99% rename from src/cli/handlers/orchestration/worker-agent-views.ts rename to src/cli/orchestration/workers/worker-agent-views.ts index dd6bbb65804..ca014a131f8 100644 --- a/src/cli/handlers/orchestration/worker-agent-views.ts +++ b/src/cli/orchestration/workers/worker-agent-views.ts @@ -1,4 +1,4 @@ -import { renderOrchestrationArgv, type OrchestrationAgentView } from './agent-view' +import { renderOrchestrationArgv, type OrchestrationAgentView } from '../agent-view' import type { WorkerListRunScope } from './worker-list-run-scope' import { isActionableOrchestrationFleetAttention } from '../../../shared/orchestration/fleet/orchestration-fleet-attention' import { formatPrCommentRelativeTime } from '../../../shared/source-control/review-comments/pr-comment-time' diff --git a/src/cli/handlers/orchestration/worker-launch-handler.ts b/src/cli/orchestration/workers/worker-launch-handler.ts similarity index 84% rename from src/cli/handlers/orchestration/worker-launch-handler.ts rename to src/cli/orchestration/workers/worker-launch-handler.ts index f81c1bbdf63..9190b8be9f4 100644 --- a/src/cli/handlers/orchestration/worker-launch-handler.ts +++ b/src/cli/orchestration/workers/worker-launch-handler.ts @@ -1,25 +1,26 @@ -import type { CommandHandler } from '../../dispatch' -import { printResult } from '../../command-result-output' -import { withReceiptNext } from './receipt-next-text' -import { getOptionalStringFlag, getPresentStringFlag } from '../../flags' -import { RuntimeClientError, type RuntimeClient } from '../../runtime-client' -import type { RuntimeStatus } from '../../../shared/runtime-types' +import type { CommandHandler } from '../../dispatch/dispatch' +import { printResult } from '../../output/command-result-output' +import { withReceiptNext } from '../receipt-next-text' +import { getOptionalStringFlag, getPresentStringFlag } from '../../arguments/flags' +import { RuntimeClientError } from '../../runtime/types' +import type { RuntimeClient } from '../../runtime/client' +import type { RuntimeStatus } from '../../../shared/runtime-session-contracts' import { ORCHESTRATION_WORKER_LAUNCH_PREFERENCES_RUNTIME_CAPABILITY } from '../../../shared/orchestration/orchestration-runtime-capabilities' -import { callOrchestrationMutation } from './mutation-request' -import { getOptionalPositiveIntegerValueFlag } from './numeric-flags' -import { isDevCliInvocation } from './runtime-compatibility' -import { resolveCoordinatorTerminalHandle } from './terminal-identity' +import { callOrchestrationMutation } from '../recovery/mutation-request' +import { getOptionalPositiveIntegerValueFlag } from '../numeric-flags' +import { isDevCliInvocation } from '../recovery/runtime-compatibility' +import { resolveCoordinatorTerminalHandle } from '../identity/terminal-identity' import { formatWorkerStart, type WorkerReleaseReceipt } from './worker-output' import { isUnobservedTurnStart, WORKER_START_VIEW } from './worker-start-agent-view' import { printOrchestrationResult, renderOrchestrationArgv, reportOrchestrationFailure -} from './agent-view' -import { explainOlderRuntimeRunRequired } from './older-runtime-run-binding' -import { withResolvedNextCommands } from '../../orchestration-mutation-recovery' -import { readTextOrFileFlag } from '../../command-body-input' -import { refuseAgentServerRoute } from './agent-server-route' +} from '../agent-view' +import { explainOlderRuntimeRunRequired } from '../recovery/older-runtime-run-binding' +import { withResolvedNextCommands } from '../recovery/orchestration-mutation-recovery' +import { readTextOrFileFlag } from '../../arguments/command-body-input' +import { refuseAgentServerRoute } from '../identity/agent-server-route' export const ORCHESTRATION_WORKER_LAUNCH_HANDLER: Record = { 'orchestration worker-start': async (ctx) => { diff --git a/src/cli/handlers/orchestration/worker-list-run-scope.ts b/src/cli/orchestration/workers/worker-list-run-scope.ts similarity index 85% rename from src/cli/handlers/orchestration/worker-list-run-scope.ts rename to src/cli/orchestration/workers/worker-list-run-scope.ts index 39eeb8e1b7c..957a2327a61 100644 --- a/src/cli/handlers/orchestration/worker-list-run-scope.ts +++ b/src/cli/orchestration/workers/worker-list-run-scope.ts @@ -1,6 +1,6 @@ -import { getOptionalStringFlag } from '../../flags' -import type { RuntimeClient } from '../../runtime-client' -import { resolveOrchestrationTerminalHandle } from './terminal-identity' +import { getOptionalStringFlag } from '../../arguments/flags' +import type { RuntimeClient } from '../../runtime/client' +import { resolveOrchestrationTerminalHandle } from '../identity/terminal-identity' export type WorkerListRunScope = { run?: string; source: 'flag' | 'bound' | 'all' } diff --git a/src/cli/handlers/orchestration/worker-observation-handlers.ts b/src/cli/orchestration/workers/worker-observation-handlers.ts similarity index 94% rename from src/cli/handlers/orchestration/worker-observation-handlers.ts rename to src/cli/orchestration/workers/worker-observation-handlers.ts index e2a5c40c8a0..ab48b939dd1 100644 --- a/src/cli/handlers/orchestration/worker-observation-handlers.ts +++ b/src/cli/orchestration/workers/worker-observation-handlers.ts @@ -1,13 +1,13 @@ -import type { CommandHandler } from '../../dispatch' -import { printResult } from '../../command-result-output' -import { printOrchestrationReceipt, printOrchestrationResult } from './agent-view' +import type { CommandHandler } from '../../dispatch/dispatch' +import { printResult } from '../../output/command-result-output' +import { printOrchestrationReceipt, printOrchestrationResult } from '../agent-view' import { WORKER_SHOW_VIEW, type WorkerShowResult } from './worker-agent-views' import { getOptionalPositiveIntegerFlag, getOptionalStringFlag, getRequiredStringFlag -} from '../../flags' -import { RuntimeClientError } from '../../runtime-client' +} from '../../arguments/flags' +import { RuntimeClientError } from '../../runtime/types' import type { OrchestrationWorkerReadResult, OrchestrationWorkerReadSource diff --git a/src/cli/handlers/orchestration/worker-output.ts b/src/cli/orchestration/workers/worker-output.ts similarity index 99% rename from src/cli/handlers/orchestration/worker-output.ts rename to src/cli/orchestration/workers/worker-output.ts index 4b78308a579..27c5be5a63d 100644 --- a/src/cli/handlers/orchestration/worker-output.ts +++ b/src/cli/orchestration/workers/worker-output.ts @@ -1,4 +1,4 @@ -import type { RuntimeTerminalRead } from '../../../shared/runtime-types' +import type { RuntimeTerminalRead } from '../../../shared/runtime-terminal-contracts' import type { OrchestrationWorkerReadResult } from '../../../shared/orchestration/workers/orchestration-worker-output' import { formatWorkerTranscriptMessage } from '../../../shared/worker-transcript-text' diff --git a/src/cli/handlers/orchestration/worker-release-agent-view.ts b/src/cli/orchestration/workers/worker-release-agent-view.ts similarity index 99% rename from src/cli/handlers/orchestration/worker-release-agent-view.ts rename to src/cli/orchestration/workers/worker-release-agent-view.ts index 098d09a291d..737dd66ad03 100644 --- a/src/cli/handlers/orchestration/worker-release-agent-view.ts +++ b/src/cli/orchestration/workers/worker-release-agent-view.ts @@ -1,4 +1,4 @@ -import type { OrchestrationAgentView, OrchestrationFailure } from './agent-view' +import type { OrchestrationAgentView, OrchestrationFailure } from '../agent-view' import type { WorkerReleaseReceipt } from './worker-output' import type { HelperStopOutcome, diff --git a/src/cli/handlers/orchestration/worker-start-agent-view.ts b/src/cli/orchestration/workers/worker-start-agent-view.ts similarity index 99% rename from src/cli/handlers/orchestration/worker-start-agent-view.ts rename to src/cli/orchestration/workers/worker-start-agent-view.ts index e9155322da0..1ef17434ac2 100644 --- a/src/cli/handlers/orchestration/worker-start-agent-view.ts +++ b/src/cli/orchestration/workers/worker-start-agent-view.ts @@ -1,4 +1,4 @@ -import { renderOrchestrationArgv, type OrchestrationAgentView } from './agent-view' +import { renderOrchestrationArgv, type OrchestrationAgentView } from '../agent-view' import type { WorkerStartReceipt } from './worker-output' type LaunchChoice = { diff --git a/src/cli/handlers/orchestration/worker-terminal-handlers.ts b/src/cli/orchestration/workers/worker-terminal-handlers.ts similarity index 95% rename from src/cli/handlers/orchestration/worker-terminal-handlers.ts rename to src/cli/orchestration/workers/worker-terminal-handlers.ts index 6f0101e88eb..1fe04c5d417 100644 --- a/src/cli/handlers/orchestration/worker-terminal-handlers.ts +++ b/src/cli/orchestration/workers/worker-terminal-handlers.ts @@ -1,6 +1,6 @@ -import type { CommandHandler } from '../../dispatch' -import { printResult } from '../../command-result-output' -import { printOrchestrationResult } from './agent-view' +import type { CommandHandler } from '../../dispatch/dispatch' +import { printResult } from '../../output/command-result-output' +import { printOrchestrationResult } from '../agent-view' import { remoteHost, WORKER_LIST_VIEW, type WorkerListResult } from './worker-agent-views' import { formatHelperStops, @@ -12,10 +12,10 @@ import { getOptionalPositiveIntegerFlag, getOptionalStringFlag, getRequiredStringFlag -} from '../../flags' -import { RuntimeClientError } from '../../runtime-client' -import { callOrchestrationMutation } from './mutation-request' -import { resolveOrchestrationTerminalHandle } from './terminal-identity' +} from '../../arguments/flags' +import { RuntimeClientError } from '../../runtime/types' +import { callOrchestrationMutation } from '../recovery/mutation-request' +import { resolveOrchestrationTerminalHandle } from '../identity/terminal-identity' import { formatWorkerRelease, type WorkerReleaseReceipt } from './worker-output' import { formatWorkerListScope, resolveWorkerListRunScope } from './worker-list-run-scope' diff --git a/src/cli/output/cli-error-context.ts b/src/cli/output/cli-error-context.ts new file mode 100644 index 00000000000..65cdc699ed1 --- /dev/null +++ b/src/cli/output/cli-error-context.ts @@ -0,0 +1,11 @@ +export type CliErrorContext = { + commandPath?: readonly string[] + /** The `--worktree` value this invocation sent; the runtime's error never echoes it. */ + worktreeSelector?: string + /** The runtime error omits the original --repo selector. */ + repoSelector?: string + /** True when --environment, --pairing-code, --host runtime:, or their env vars chose a server. */ + remoteServerSelected?: boolean + /** Concise orchestration failures: compact JSON plus one `error: : ` stderr line. */ + conciseOrchestration?: boolean +} diff --git a/src/cli/cli-error.ts b/src/cli/output/cli-error.ts similarity index 89% rename from src/cli/cli-error.ts rename to src/cli/output/cli-error.ts index be20b39a02f..94dacbcb88c 100644 --- a/src/cli/cli-error.ts +++ b/src/cli/output/cli-error.ts @@ -1,26 +1,18 @@ -import { computerUseErrorRecoveryData } from '../shared/computer-use-error-recovery' +import type { CliErrorContext } from './cli-error-context' +import { computerUseErrorRecoveryData } from '../../shared/computer-use-error-recovery' import { matchAutomationOwnerConflict, stripAutomationOwnerConflictCode -} from '../shared/automations/ownership/automation-owner-conflict' -import { automationOwnerConflictRecovery } from './automations/automation-owner-conflict-recovery' -import { worktreeSelectorRecovery } from './workspaces/worktree-selector-recovery' -import { ambiguousWorkspaceChoices, selectorAmbiguityRecovery } from './selector-ambiguity-recovery' -import type { RuntimeRpcFailure } from './runtime-client' -import { RuntimeClientError, RuntimeRpcFailureError } from './runtime/types' -import { readableWslDistroCliRefusal } from './wsl-distro-cli-refusal' - -export type CliErrorContext = { - commandPath?: readonly string[] - /** The `--worktree` value this invocation sent; the runtime's error never echoes it. */ - worktreeSelector?: string - /** The runtime error omits the original --repo selector. */ - repoSelector?: string - /** True when --environment, --pairing-code, --host runtime:, or their env vars chose a server. */ - remoteServerSelected?: boolean - /** Concise orchestration failures: compact JSON plus one `error: : ` stderr line. */ - conciseOrchestration?: boolean -} +} from '../../shared/automations/ownership/automation-owner-conflict' +import { automationOwnerConflictRecovery } from '../automations/automation-owner-conflict-recovery' +import { worktreeSelectorRecovery } from '../workspaces/worktree-selector-recovery' +import { + ambiguousWorkspaceChoices, + selectorAmbiguityRecovery +} from '../workspace-selection/selector-ambiguity-recovery' +import type { RuntimeRpcFailure } from '../../shared/runtime-rpc-envelope' +import { RuntimeClientError, RuntimeRpcFailureError } from '../runtime/types' +import { readableWslDistroCliRefusal } from '../hosts/wsl-distro-cli-refusal' type ContextRecovery = { nextSteps: readonly string[] } & Record diff --git a/src/cli/cli-exit-code.ts b/src/cli/output/cli-exit-code.ts similarity index 100% rename from src/cli/cli-exit-code.ts rename to src/cli/output/cli-exit-code.ts diff --git a/src/cli/command-result-output.test.ts b/src/cli/output/command-result-output.test.ts similarity index 100% rename from src/cli/command-result-output.test.ts rename to src/cli/output/command-result-output.test.ts diff --git a/src/cli/command-result-output.ts b/src/cli/output/command-result-output.ts similarity index 61% rename from src/cli/command-result-output.ts rename to src/cli/output/command-result-output.ts index d70a2689c55..1bc7c74e6eb 100644 --- a/src/cli/command-result-output.ts +++ b/src/cli/output/command-result-output.ts @@ -1,6 +1,6 @@ -import { formatBrowserActionEffects } from './browser/browser-format' -import { prepareComputerCliJsonResult } from './computer/computer-format' -import type { RuntimeRpcSuccess } from '../shared/runtime-rpc-envelope' +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, diff --git a/src/cli/stdout-line.ts b/src/cli/output/stdout-line.ts similarity index 100% rename from src/cli/stdout-line.ts rename to src/cli/output/stdout-line.ts diff --git a/src/cli/plugins/authoring/plugin-authoring.ts b/src/cli/plugins/authoring/plugin-authoring.ts index 95338ce0679..d907e76d534 100644 --- a/src/cli/plugins/authoring/plugin-authoring.ts +++ b/src/cli/plugins/authoring/plugin-authoring.ts @@ -1,4 +1,4 @@ -import type { CommandHandler } from '../../dispatch' +import type { CommandHandler } from '../../dispatch/dispatch' import { createPluginFromTemplate, PluginCreateError } from './plugin-create' import { inspectPluginFolder, diff --git a/src/cli/plugins/dev-watch/plugin-dev-watch.test.ts b/src/cli/plugins/dev-watch/plugin-dev-watch.test.ts index b15ef177a3b..bcb55499463 100644 --- a/src/cli/plugins/dev-watch/plugin-dev-watch.test.ts +++ b/src/cli/plugins/dev-watch/plugin-dev-watch.test.ts @@ -3,11 +3,11 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { describe, expect, it, vi } from 'vitest' import { COMMAND_SPECS } from '../../specs/index' -import { findCommandSpec, normalizeCommandPositionals, parseArgs } from '../../args' -import { specPaths } from '../../command-spec' -import type { HandlerContext } from '../../dispatch' -import { reportCliError } from '../../cli-error' +import { findCommandSpec, normalizeCommandPositionals, parseArgs } from '../../arguments/args' +import { specPaths } from '../../discovery/command-spec' +import type { HandlerContext } from '../../dispatch/dispatch' import type { RuntimeClient } from '../../runtime/client' + import { RuntimeClientError, RuntimeRpcFailureError } from '../../runtime/types' import { bindPluginDevWatchHost, PluginHostUnreachableError } from './plugin-dev-watch' @@ -83,26 +83,6 @@ describe('orca plugin dev watch', () => { }) }) -describe('plugin dev watch --json errors', () => { - it('prints a failed first load as one JSON line, unlike other commands', () => { - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - try { - const error = new RuntimeClientError('approval_required', 'acme.notes needs approval') - reportCliError(error, true, { commandPath: ['plugin', 'dev', 'watch'] }) - reportCliError(error, true, { commandPath: ['plugin', 'dev', 'load'] }) - const [watchLine, loadOutput] = log.mock.calls.map(([text]) => String(text)) - expect(watchLine).not.toContain('\n') - expect(JSON.parse(watchLine)).toMatchObject({ - ok: false, - error: { code: 'approval_required' } - }) - expect(loadOutput).toContain('\n') - } finally { - log.mockRestore() - } - }) -}) - describe('plugin dev watch --check', () => { it('needs a local folder, since it renders the plugin on this machine', () => { const remote = context(vi.fn()) diff --git a/src/cli/plugins/dev-watch/plugin-dev-watch.ts b/src/cli/plugins/dev-watch/plugin-dev-watch.ts index 94497fde6d1..1b7b4a6140f 100644 --- a/src/cli/plugins/dev-watch/plugin-dev-watch.ts +++ b/src/cli/plugins/dev-watch/plugin-dev-watch.ts @@ -1,10 +1,10 @@ -import type { CommandHandler, HandlerContext } from '../../dispatch' +import type { CommandHandler, HandlerContext } from '../../dispatch/dispatch' import { requirePluginPathArg } from '../plugin-cli-output' import { formatPluginDevWatchEvent, type PluginDevWatchApproval } from './plugin-dev-watch-events' import { runPluginDevWatch, type PluginDevWatchHost } from './plugin-dev-watch-loop' import { onPluginDevWatchInterrupt, waitUnlessAborted } from './plugin-dev-watch-process' import { RuntimeClientError, RuntimeRpcFailureError } from '../../runtime/types' -import { writeStdoutLine } from '../../stdout-line' +import { writeStdoutLine } from '../../output/stdout-line' import type { PluginHostListEntry } from '../../../shared/plugins/plugin-list-entry' import { CLI_BOOLEAN_FLAGS } from '../../../shared/cli-argument-boundary' import { checkPluginDevFolder } from './plugin-dev-watch-check' diff --git a/src/cli/plugins/plugin-approval-rerun.ts b/src/cli/plugins/plugin-approval-rerun.ts index 27e6422a4d8..032dbe0a9f0 100644 --- a/src/cli/plugins/plugin-approval-rerun.ts +++ b/src/cli/plugins/plugin-approval-rerun.ts @@ -1,5 +1,5 @@ -import type { HandlerContext } from '../dispatch' -import { quoteCliCommandArgument } from '../shell-command-quote' +import type { HandlerContext } from '../dispatch/dispatch' +import { quoteCliCommandArgument } from '../arguments/shell-command-quote' /** The caller's exact command with `--approve `, so nothing else changes on re-run. */ export function approvalRerunCommand(rawArgs: readonly string[], fingerprint: string): string { diff --git a/src/cli/plugins/plugin-cli-output.ts b/src/cli/plugins/plugin-cli-output.ts index 1fdf64eedb9..60c1289639b 100644 --- a/src/cli/plugins/plugin-cli-output.ts +++ b/src/cli/plugins/plugin-cli-output.ts @@ -1,8 +1,8 @@ import { isAbsolute, resolve } from 'node:path' -import type { HandlerContext } from '../dispatch' -import { rejectRemoteSelectionFlags } from '../remote-selection-flag-rejection' +import type { HandlerContext } from '../dispatch/dispatch' +import { rejectRemoteSelectionFlags } from '../dispatch/remote-selection-flag-rejection' import { RuntimeClientError } from '../runtime/types' -import { writeStdoutLine } from '../stdout-line' +import { writeStdoutLine } from '../output/stdout-line' /** One `{ ok, result }` object on stdout for --json; plain text otherwise. */ export function printPluginResult(ctx: HandlerContext, result: unknown, text: string): void { diff --git a/src/cli/plugins/plugin-dev-emit.ts b/src/cli/plugins/plugin-dev-emit.ts index f120b6123ee..2d4e82f390d 100644 --- a/src/cli/plugins/plugin-dev-emit.ts +++ b/src/cli/plugins/plugin-dev-emit.ts @@ -1,4 +1,4 @@ -import type { CommandHandler, HandlerContext } from '../dispatch' +import type { CommandHandler, HandlerContext } from '../dispatch/dispatch' import { printPluginResult, requirePluginPathArg } from './plugin-cli-output' import { RuntimeClientError } from '../runtime/types' import { callPlugins, devTargetParams, stringFlag } from './plugin-runtime' diff --git a/src/cli/plugins/plugin-dev-request.ts b/src/cli/plugins/plugin-dev-request.ts index 3bae2c6c616..0e5b25f4984 100644 --- a/src/cli/plugins/plugin-dev-request.ts +++ b/src/cli/plugins/plugin-dev-request.ts @@ -1,5 +1,5 @@ -import type { CommandHandler } from '../dispatch' -import { getOptionalPositiveIntegerFlag } from '../flags' +import type { CommandHandler } from '../dispatch/dispatch' +import { getOptionalPositiveIntegerFlag } from '../arguments/flags' import { printPluginResult, requirePluginPathArg } from './plugin-cli-output' import { parseDataFlag } from './plugin-dev-emit' import { callPlugins, devTargetParams, stringFlag } from './plugin-runtime' diff --git a/src/cli/plugins/plugin-handler-groups.ts b/src/cli/plugins/plugin-handler-groups.ts index 40ea805311b..ce35e28af9e 100644 --- a/src/cli/plugins/plugin-handler-groups.ts +++ b/src/cli/plugins/plugin-handler-groups.ts @@ -1,4 +1,4 @@ -import type { HandlerGroup } from '../handler-group-manifest' +import type { HandlerGroup } from '../dispatch/handler-group-manifest' // Authoring runs offline; runtime commands reach the Orca host. Split so authoring never loads the RPC graph. export const PLUGIN_HANDLER_GROUPS: readonly HandlerGroup[] = [ diff --git a/src/cli/plugins/plugin-install.ts b/src/cli/plugins/plugin-install.ts index 026ccab9f74..084cf69c500 100644 --- a/src/cli/plugins/plugin-install.ts +++ b/src/cli/plugins/plugin-install.ts @@ -1,6 +1,6 @@ import { existsSync } from 'node:fs' import { isAbsolute, join, resolve } from 'node:path' -import type { CommandHandler, HandlerContext } from '../dispatch' +import type { CommandHandler, HandlerContext } from '../dispatch/dispatch' import { printPluginResult, requirePluginPathArg } from './plugin-cli-output' import { RuntimeClientError } from '../runtime/types' import { isQualifiedPluginKey } from '../../shared/plugins/frames/plugin-tab-key' diff --git a/src/cli/plugins/plugin-runtime.ts b/src/cli/plugins/plugin-runtime.ts index 448f15b29e9..f9a3e3e3dfe 100644 --- a/src/cli/plugins/plugin-runtime.ts +++ b/src/cli/plugins/plugin-runtime.ts @@ -1,6 +1,6 @@ import { existsSync } from 'node:fs' import { isAbsolute, resolve } from 'node:path' -import type { CommandHandler, HandlerContext } from '../dispatch' +import type { CommandHandler, HandlerContext } from '../dispatch/dispatch' import { printPluginResult, requirePluginPathArg } from './plugin-cli-output' import { RuntimeClientError, RuntimeRpcFailureError } from '../runtime/types' import { diff --git a/src/cli/plugins/view/plugin-shot-chrome.test.ts b/src/cli/plugins/view/plugin-shot-chrome.test.ts index 1bfe370505c..8a6fb9eb5b3 100644 --- a/src/cli/plugins/view/plugin-shot-chrome.test.ts +++ b/src/cli/plugins/view/plugin-shot-chrome.test.ts @@ -3,9 +3,9 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { COMMAND_SPECS } from '../../specs/index' -import { normalizeCommandPositionals, parseArgs } from '../../args' -import { specPaths } from '../../command-spec' -import type { HandlerContext } from '../../dispatch' +import { normalizeCommandPositionals, parseArgs } from '../../arguments/args' +import { specPaths } from '../../discovery/command-spec' +import type { HandlerContext } from '../../dispatch/dispatch' import type { RuntimeClient } from '../../runtime/client' import { PLUGIN_VIEW_HANDLERS } from './plugin-view' diff --git a/src/cli/plugins/view/plugin-shot-chrome.ts b/src/cli/plugins/view/plugin-shot-chrome.ts index eec6d69df99..bac117ff070 100644 --- a/src/cli/plugins/view/plugin-shot-chrome.ts +++ b/src/cli/plugins/view/plugin-shot-chrome.ts @@ -1,6 +1,6 @@ import { mkdir, writeFile } from 'node:fs/promises' import { dirname, join } from 'node:path' -import type { HandlerContext } from '../../dispatch' +import type { HandlerContext } from '../../dispatch/dispatch' import { printPluginResult } from '../plugin-cli-output' import { RuntimeClientError } from '../../runtime/types' import { callPlugins } from '../plugin-runtime' diff --git a/src/cli/plugins/view/plugin-shot-editor.test.ts b/src/cli/plugins/view/plugin-shot-editor.test.ts index e61e0d7a8b5..7cd763d64ee 100644 --- a/src/cli/plugins/view/plugin-shot-editor.test.ts +++ b/src/cli/plugins/view/plugin-shot-editor.test.ts @@ -3,9 +3,9 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { COMMAND_SPECS } from '../../specs/index' -import { normalizeCommandPositionals, parseArgs } from '../../args' -import { specPaths } from '../../command-spec' -import type { HandlerContext } from '../../dispatch' +import { normalizeCommandPositionals, parseArgs } from '../../arguments/args' +import { specPaths } from '../../discovery/command-spec' +import type { HandlerContext } from '../../dispatch/dispatch' import type { RuntimeClient } from '../../runtime/client' import { PLUGIN_VIEW_HANDLERS } from './plugin-view' diff --git a/src/cli/plugins/view/plugin-shot-editor.ts b/src/cli/plugins/view/plugin-shot-editor.ts index 14494126a72..055aae27edf 100644 --- a/src/cli/plugins/view/plugin-shot-editor.ts +++ b/src/cli/plugins/view/plugin-shot-editor.ts @@ -1,8 +1,8 @@ import { existsSync } from 'node:fs' import { mkdir, writeFile } from 'node:fs/promises' import { dirname, isAbsolute, join, resolve } from 'node:path' -import type { HandlerContext } from '../../dispatch' -import { getOptionalPositiveIntegerFlag } from '../../flags' +import type { HandlerContext } from '../../dispatch/dispatch' +import { getOptionalPositiveIntegerFlag } from '../../arguments/flags' import { printPluginResult } from '../plugin-cli-output' import { RuntimeClientError } from '../../runtime/types' import { isQualifiedPluginKey } from '../../../shared/plugins/frames/plugin-tab-key' diff --git a/src/cli/plugins/view/plugin-shot-scenario.test.ts b/src/cli/plugins/view/plugin-shot-scenario.test.ts index 32121e75882..04082273e31 100644 --- a/src/cli/plugins/view/plugin-shot-scenario.test.ts +++ b/src/cli/plugins/view/plugin-shot-scenario.test.ts @@ -3,9 +3,9 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { COMMAND_SPECS } from '../../specs/index' -import { normalizeCommandPositionals, parseArgs } from '../../args' -import { specPaths } from '../../command-spec' -import type { HandlerContext } from '../../dispatch' +import { normalizeCommandPositionals, parseArgs } from '../../arguments/args' +import { specPaths } from '../../discovery/command-spec' +import type { HandlerContext } from '../../dispatch/dispatch' import type { RuntimeClient } from '../../runtime/client' import { RuntimeRpcFailureError } from '../../runtime/types' import { createPluginFromTemplate } from '../authoring/plugin-create' diff --git a/src/cli/plugins/view/plugin-shot-scenario.ts b/src/cli/plugins/view/plugin-shot-scenario.ts index ac95cba7fe6..a3425131a4f 100644 --- a/src/cli/plugins/view/plugin-shot-scenario.ts +++ b/src/cli/plugins/view/plugin-shot-scenario.ts @@ -1,7 +1,7 @@ import { existsSync } from 'node:fs' import { mkdir, readFile, writeFile } from 'node:fs/promises' import { dirname, isAbsolute, join, resolve } from 'node:path' -import type { HandlerContext } from '../../dispatch' +import type { HandlerContext } from '../../dispatch/dispatch' import { RuntimeClientError } from '../../runtime/types' import type { PluginHostListEntry } from '../../../shared/plugins/plugin-list-entry' import { isQualifiedPluginKey } from '../../../shared/plugins/frames/plugin-tab-key' diff --git a/src/cli/plugins/view/plugin-view.test.ts b/src/cli/plugins/view/plugin-view.test.ts index d235abefcf8..d9281ac897c 100644 --- a/src/cli/plugins/view/plugin-view.test.ts +++ b/src/cli/plugins/view/plugin-view.test.ts @@ -1,11 +1,11 @@ -import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { mkdtemp, readFile, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { COMMAND_SPECS } from '../../specs/index' -import { normalizeCommandPositionals, parseArgs } from '../../args' -import { specPaths } from '../../command-spec' -import type { HandlerContext } from '../../dispatch' +import { normalizeCommandPositionals, parseArgs } from '../../arguments/args' +import { specPaths } from '../../discovery/command-spec' +import type { HandlerContext } from '../../dispatch/dispatch' import type { RuntimeClient } from '../../runtime/client' import type { PluginShotActResult } from '../../../shared/plugins/view/plugin-shot-acts' import { PLUGIN_VIEW_HANDLERS, type PluginShotReply } from './plugin-view' @@ -134,20 +134,6 @@ describe('orca plugin shot', () => { ).rejects.toMatchObject({ code: 'invalid_environment' }) }) - it('writes beside the plugin when run inside its folder', async () => { - const plugin = join(cwd, 'todos') - await mkdir(join(plugin, 'src'), { recursive: true }) - await writeFile(join(plugin, 'orca-plugin.json'), '{}') - await PLUGIN_VIEW_HANDLERS['plugin shot']( - context(['plugin', 'shot', 'acme.todos'], vi.fn().mockResolvedValue(shotReply()), { - cwd: join(plugin, 'src') - }) - ) - expect(JSON.parse(stdout.join('')).result.path).toBe( - join(plugin, '.orca', 'shots', 'acme.todos-todos.png') - ) - }) - it('sends --act, reports each act, and exits 1 when one failed', async () => { const actions: PluginShotActResult[] = [ { ok: true }, diff --git a/src/cli/plugins/view/plugin-view.ts b/src/cli/plugins/view/plugin-view.ts index 693cbd5483b..fc9ec87c2c5 100644 --- a/src/cli/plugins/view/plugin-view.ts +++ b/src/cli/plugins/view/plugin-view.ts @@ -1,7 +1,7 @@ import { mkdir, writeFile } from 'node:fs/promises' import { dirname, isAbsolute, join, resolve } from 'node:path' -import type { CommandHandler, HandlerContext } from '../../dispatch' -import { getOptionalPositiveIntegerFlag } from '../../flags' +import type { CommandHandler, HandlerContext } from '../../dispatch/dispatch' +import { getOptionalPositiveIntegerFlag } from '../../arguments/flags' import { printPluginResult } from '../plugin-cli-output' import { RuntimeClientError } from '../../runtime/types' import { diff --git a/src/cli/profile-state-location.ts b/src/cli/profiles/profile-state-location.ts similarity index 62% rename from src/cli/profile-state-location.ts rename to src/cli/profiles/profile-state-location.ts index 701069445cc..c8a8057c5ef 100644 --- a/src/cli/profile-state-location.ts +++ b/src/cli/profiles/profile-state-location.ts @@ -1,5 +1,6 @@ -import { getActiveProfileStateLocation as resolveActiveProfileStateLocation } from '../main/persistence/profile-state/offline-access/profile-state-active-location' -import { RuntimeClientError, getDefaultUserDataPath } from './runtime-client' +import { getActiveProfileStateLocation as resolveActiveProfileStateLocation } from '../../main/persistence/profile-state/offline-access/profile-state-active-location' +import { RuntimeClientError } from '../runtime/types' +import { getDefaultUserDataPath } from '../runtime/metadata' export function getActiveProfileStateLocation(userDataPath = getDefaultUserDataPath()) { try { diff --git a/src/cli/handlers/profile-state-recovery-admission.test.ts b/src/cli/profiles/profile-state-recovery-admission.test.ts similarity index 95% rename from src/cli/handlers/profile-state-recovery-admission.test.ts rename to src/cli/profiles/profile-state-recovery-admission.test.ts index 5bada7e8664..3f137ae79d1 100644 --- a/src/cli/handlers/profile-state-recovery-admission.test.ts +++ b/src/cli/profiles/profile-state-recovery-admission.test.ts @@ -32,31 +32,29 @@ import { assertNoRetainedProfileStateExports, ProfileStateRecoveryRequiredError } from '../../main/persistence/profile-state/recovery/profile-state-recovery-required' -import { RuntimeClient } from '../runtime-client' +import { RuntimeClient } from '../runtime/client' import { PROFILE_STATE_HANDLERS } from './profile-state' import { profileStateJsonExportPath } from '../../main/persistence/profile-state/legacy-json/profile-state-export-path' const mocks = vi.hoisted(() => ({ root: vi.fn(), status: vi.fn() })) -vi.mock('../runtime-client', () => ({ - getDefaultUserDataPath: mocks.root, - RuntimeClient: class { - async getOfflineRuntimeAdmission() { - const status = await mocks.status() - return { - reachable: status.result.runtime.reachable, - legacyPidRunning: status.result.app.running, - pid: status.result.app.pid ?? null +vi.mock('../runtime/client', () => { + return { + RuntimeClient: class { + async getOfflineRuntimeAdmission() { + const status = await mocks.status() + return { + reachable: status.result.runtime.reachable, + legacyPidRunning: status.result.app.running, + pid: status.result.app.pid ?? null + } } } - }, - RuntimeClientError: class extends Error { - constructor( - readonly code: string, - message: string - ) { - super(message) - } } +}) + +vi.mock('../runtime/metadata', async (importOriginal) => ({ + ...(await importOriginal>()), + getDefaultUserDataPath: mocks.root })) const roots: string[] = [] diff --git a/src/cli/handlers/profile-state.test.ts b/src/cli/profiles/profile-state.test.ts similarity index 94% rename from src/cli/handlers/profile-state.test.ts rename to src/cli/profiles/profile-state.test.ts index 609aa0da557..ab130d033ca 100644 --- a/src/cli/handlers/profile-state.test.ts +++ b/src/cli/profiles/profile-state.test.ts @@ -35,18 +35,7 @@ vi.mock('@orca/process-host', async (importOriginal) => { return { ...actual, runProcess: runProcessMock } }) -vi.mock('../runtime-client', () => { - class RuntimeClientError extends Error { - readonly code: string - readonly data: unknown - - constructor(code: string, message: string, data?: unknown) { - super(message) - this.code = code - this.data = data - } - } - +vi.mock('../runtime/client', () => { class RuntimeClient { async getOfflineRuntimeAdmission() { const status = await getCliStatusMock() @@ -66,14 +55,14 @@ vi.mock('../runtime-client', () => { runtimeClientConstructorMock(remotePairingCode, environmentSelector) } } - - return { - RuntimeClient, - RuntimeClientError, - getDefaultUserDataPath: getDefaultUserDataPathMock - } + return { RuntimeClient } }) +vi.mock('../runtime/metadata', async (importOriginal) => ({ + ...(await importOriginal>()), + getDefaultUserDataPath: getDefaultUserDataPathMock +})) + const temporaryDirectories: string[] = [] let previousExitCode: typeof process.exitCode diff --git a/src/cli/handlers/profile-state.ts b/src/cli/profiles/profile-state.ts similarity index 93% rename from src/cli/handlers/profile-state.ts rename to src/cli/profiles/profile-state.ts index 59281ae4dbd..4b1b8cb7a2d 100644 --- a/src/cli/handlers/profile-state.ts +++ b/src/cli/profiles/profile-state.ts @@ -1,13 +1,11 @@ import { z } from 'zod' -import type { CommandHandler } from '../dispatch' -import { printResult } from '../command-result-output' -import { rejectRemoteSelectionFlags } from '../remote-selection-flag-rejection' -import { - getDefaultUserDataPath, - RuntimeClientError, - type RuntimeClient, - type RuntimeRpcSuccess -} from '../runtime-client' +import type { CommandHandler } from '../dispatch/dispatch' +import { printResult } from '../output/command-result-output' +import { rejectRemoteSelectionFlags } from '../dispatch/remote-selection-flag-rejection' +import { getDefaultUserDataPath } from '../runtime/metadata' +import { RuntimeClientError } from '../runtime/types' +import type { RuntimeClient } from '../runtime/client' +import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope' import { getProfileStateExports, rollbackProfileState diff --git a/src/cli/projects/project.ts b/src/cli/projects/project.ts index d54fe415c84..0abcfcc18d0 100644 --- a/src/cli/projects/project.ts +++ b/src/cli/projects/project.ts @@ -13,7 +13,7 @@ import type { import { getSshTargetIdForExecutionHost, type ExecutionHostId } from '../../shared/execution-host' import type { RuntimeStatus } from '../../shared/runtime-session-contracts' import { PROJECT_HOST_SETUP_HOST_TARGET_RUNTIME_CAPABILITY } from '../../shared/worktree-runtime-capabilities' -import type { CommandHandler, HandlerContext } from '../dispatch' +import type { CommandHandler, HandlerContext } from '../dispatch/dispatch' import { formatProjectHostSetupCreateResult, formatProjectHostSetupDeleteResult, @@ -22,13 +22,17 @@ import { formatProjectHostSetupUpdateResult, formatProjectList } from './project-format' -import { printResult } from '../command-result-output' +import { printResult } from '../output/command-result-output' import { hostFilterMatchesHostId, parseHostFlag, resolveHostFlagTarget } from '../hosts/execution-host-flag' -import { getOptionalRepoKind, getOptionalStringFlag, getRequiredStringFlag } from '../flags' +import { + getOptionalRepoKind, + getOptionalStringFlag, + getRequiredStringFlag +} from '../arguments/flags' import { findProjectSetups, resolveProjectIdSelector } from './project-selector' import { resolveRepoPathArgument } from './repo-path-arguments' import { RuntimeClientError } from '../runtime/types' diff --git a/src/cli/projects/repo.ts b/src/cli/projects/repo.ts index a61dd778ee7..9527aab8cea 100644 --- a/src/cli/projects/repo.ts +++ b/src/cli/projects/repo.ts @@ -2,14 +2,14 @@ import type { RuntimeRepoList, RuntimeRepoSearchRefs } from '../../shared/runtime-worktree-contracts' -import type { CommandHandler, HandlerContext } from '../dispatch' +import type { CommandHandler, HandlerContext } from '../dispatch/dispatch' import { formatRepoList, formatRepoRefs, formatRepoShow } from './repo-format' -import { printResult } from '../command-result-output' +import { printResult } from '../output/command-result-output' import { getOptionalPositiveIntegerFlag, getOptionalRepoKind, getRequiredStringFlag -} from '../flags' +} from '../arguments/flags' import { resolveRepoPathArgument } from './repo-path-arguments' import { RuntimeClientError } from '../runtime/types' import { attachCliErrorData } from '../workspaces/worktree-setup-decision-recovery' diff --git a/src/cli/reference-command-arguments.test.ts b/src/cli/references/reference-command-arguments.test.ts similarity index 85% rename from src/cli/reference-command-arguments.test.ts rename to src/cli/references/reference-command-arguments.test.ts index 3cfbdf6eead..1ef53d7094f 100644 --- a/src/cli/reference-command-arguments.test.ts +++ b/src/cli/references/reference-command-arguments.test.ts @@ -1,7 +1,8 @@ import { describe, expect, it } from 'vitest' -import { normalizeCommandPositionals, parseArgs, specPaths, validateCommandAndFlags } from './args' -import { getRepeatedStringFlag } from './flags' -import { COMMAND_SPECS } from './specs' +import { normalizeCommandPositionals, parseArgs, validateCommandAndFlags } from '../arguments/args' +import { specPaths } from '../discovery/command-spec' +import { getRepeatedStringFlag } from '../arguments/flags' +import { COMMAND_SPECS } from '../specs/index' function parse(argv: string[]) { return normalizeCommandPositionals( diff --git a/src/cli/reference-handler-group.ts b/src/cli/references/reference-handler-group.ts similarity index 53% rename from src/cli/reference-handler-group.ts rename to src/cli/references/reference-handler-group.ts index 6cc50d4167f..ec8295bf4c5 100644 --- a/src/cli/reference-handler-group.ts +++ b/src/cli/references/reference-handler-group.ts @@ -1,7 +1,7 @@ -import type { HandlerGroup } from './handler-group-manifest' +import type { HandlerGroup } from '../dispatch/handler-group-manifest' export const REFERENCE_HANDLER_GROUP: HandlerGroup = { name: 'reference', keys: ['reference list', 'reference add', 'reference remove', 'reference find'], - load: async () => (await import('./handlers/reference.js')).REFERENCE_HANDLERS + load: async () => (await import('./reference.js')).REFERENCE_HANDLERS } diff --git a/src/cli/reference-input.ts b/src/cli/references/reference-input.ts similarity index 85% rename from src/cli/reference-input.ts rename to src/cli/references/reference-input.ts index 94a7d823c13..5afd689ce6f 100644 --- a/src/cli/reference-input.ts +++ b/src/cli/references/reference-input.ts @@ -1,21 +1,22 @@ -import type { WorkspaceAttachment } from '../shared/worktree/types' -import type { RuntimeStatus } from '../shared/runtime-types' -import type { JiraIssue } from '../shared/jira/jira-types' +import type { WorkspaceAttachment } from '../../shared/worktree/types' +import type { RuntimeStatus } from '../../shared/runtime-session-contracts' +import type { JiraIssue } from '../../shared/jira/jira-types' import { isResolvedJiraIssueMatch, JIRA_ISSUE_KEY_PATTERN, parseJiraIssueUrl -} from '../shared/jira/jira-issue-url' -import { WORKTREE_LINKED_ITEMS_DELTA_RUNTIME_CAPABILITY } from '../shared/workspace-attachments/workspace-attachment-capabilities' +} from '../../shared/jira/jira-issue-url' +import { WORKTREE_LINKED_ITEMS_DELTA_RUNTIME_CAPABILITY } from '../../shared/workspace-attachments/workspace-attachment-capabilities' import { getWorkspaceReferenceIdentity, parseWorkspaceReferenceUrl -} from '../shared/workspace-attachments/workspace-reference-identity' +} from '../../shared/workspace-attachments/workspace-reference-identity' -import type { HandlerContext } from './dispatch' -import { type RuntimeClient, RuntimeClientError } from './runtime-client' -import { getOptionalStringFlag, getRepeatedStringFlag } from './flags' -import { resolveJiraTarget } from './jira/jira-target' +import type { HandlerContext } from '../dispatch/dispatch' +import type { RuntimeClient } from '../runtime/client' +import { RuntimeClientError } from '../runtime/types' +import { getOptionalStringFlag, getRepeatedStringFlag } from '../arguments/flags' +import { resolveJiraTarget } from '../jira/jira-target' type ReferenceInput = { key: string } | { item: WorkspaceAttachment } diff --git a/src/cli/handlers/reference.ts b/src/cli/references/reference.ts similarity index 96% rename from src/cli/handlers/reference.ts rename to src/cli/references/reference.ts index 675c4c996a7..e78ccb08715 100644 --- a/src/cli/handlers/reference.ts +++ b/src/cli/references/reference.ts @@ -8,21 +8,22 @@ import { getWorkspaceReferenceIdentity, parseWorkspaceReferenceQuery } from '../../shared/workspace-attachments/workspace-reference-identity' -import type { CommandHandler, HandlerContext } from '../dispatch' +import type { CommandHandler, HandlerContext } from '../dispatch/dispatch' import { getOptionalPositiveIntegerFlag, getOptionalStringFlag, getRepeatedStringFlag, getRequiredStringFlag -} from '../flags' -import { printResult } from '../command-result-output' +} from '../arguments/flags' +import { printResult } from '../output/command-result-output' import { assertReferenceWritesSupported, parseReferenceInputs, parseReferenceUrls, resolveReferenceInputs -} from '../reference-input' -import { RuntimeClientError, type RuntimeRpcSuccess } from '../runtime-client' +} from './reference-input' +import { RuntimeClientError } from '../runtime/types' +import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope' // Older hosts may advertise linked-item deltas without supporting reference.*. async function callReference( diff --git a/src/cli/runtime-client.ts b/src/cli/runtime-client.ts deleted file mode 100644 index 08d774955bf..00000000000 --- a/src/cli/runtime-client.ts +++ /dev/null @@ -1,10 +0,0 @@ -export { RuntimeClient } from './runtime/client' -export { serveOrcaApp } from './runtime/launch' -export { getDefaultUserDataPath } from './runtime/metadata' -export { - RuntimeClientError, - RuntimeRpcFailureError, - type RuntimeRpcFailure, - type RuntimeRpcResponse, - type RuntimeRpcSuccess -} from './runtime/types' diff --git a/src/cli/runtime/cli-lifecycle-handlers.test.ts b/src/cli/runtime/cli-lifecycle-handlers.test.ts new file mode 100644 index 00000000000..52e606ee3e7 --- /dev/null +++ b/src/cli/runtime/cli-lifecycle-handlers.test.ts @@ -0,0 +1,98 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const { spawnMock, reclaimStaleLockMock, printReclaimResultMock } = vi.hoisted(() => ({ + spawnMock: vi.fn(), + reclaimStaleLockMock: vi.fn(), + printReclaimResultMock: vi.fn() +})) + +vi.mock('node:child_process', () => ({ spawn: spawnMock })) +vi.mock('../../main/orcad/orcad-stale-lock-reclaim.js', () => ({ + reclaimStaleOrcadInstanceLock: reclaimStaleLockMock, + printOrcadStaleLockReclaimResult: printReclaimResultMock +})) + +// Exclude the socket runtime graph; this handler needs only errors and serveOrcaApp. +vi.mock('./launch', () => ({ serveOrcaApp: vi.fn() })) + +import { CORE_HANDLERS } from './cli-lifecycle-handlers' +import type { HandlerContext } from '../dispatch/dispatch' +import type { RuntimeClient } from './client' + +// Emit exit on the next microtask so the spawned-process promise settles deterministically. +function mockClaudeChild(): { once: (event: string, cb: (...args: unknown[]) => void) => unknown } { + const child = { + once(event: string, cb: (...args: unknown[]) => void) { + if (event === 'exit') { + queueMicrotask(() => cb(0, null)) + } + return child + } + } + return child +} + +describe('orca claude-teams CLI handler', () => { + let previousRunAsNode: string | undefined + let previousPaneKey: string | undefined + let previousExitCode: typeof process.exitCode + + const callMock = vi.fn() + const client = { call: callMock } as unknown as RuntimeClient + + beforeEach(() => { + reclaimStaleLockMock.mockReset() + reclaimStaleLockMock.mockRejectedValue(new Error('Unexpected stale-lock reclaim')) + printReclaimResultMock.mockReset() + spawnMock.mockReset() + spawnMock.mockImplementation(() => mockClaudeChild()) + callMock.mockReset() + callMock.mockResolvedValue({ + result: { + launch: { env: { CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS: '1', PATH: '/shim:/usr/bin' } } + } + }) + previousRunAsNode = process.env.ELECTRON_RUN_AS_NODE + previousPaneKey = process.env.ORCA_PANE_KEY + previousExitCode = process.exitCode + // Reproduce the Electron-as-Node flag inherited from the orca launcher. + process.env.ELECTRON_RUN_AS_NODE = '1' + process.env.ORCA_PANE_KEY = 'tab-1:leaf-1' + }) + + afterEach(() => { + if (previousRunAsNode === undefined) { + delete process.env.ELECTRON_RUN_AS_NODE + } else { + process.env.ELECTRON_RUN_AS_NODE = previousRunAsNode + } + if (previousPaneKey === undefined) { + delete process.env.ORCA_PANE_KEY + } else { + process.env.ORCA_PANE_KEY = previousPaneKey + } + process.exitCode = previousExitCode + }) + + // #32177: an empty --data-root must never fall back to the default profile's lock. + it('refuses `orca serve --reclaim-stale-lock` with a --data-root that names no directory', async () => { + const ctx: HandlerContext = { + flags: new Map([ + ['reclaim-stale-lock', true], + ['data-root', true], + ['yes', true] + ]), + client, + cwd: '/tmp', + json: true, + rawArgs: [] + } + await expect(CORE_HANDLERS.serve(ctx)).rejects.toMatchObject({ + code: 'invalid_argument', + message: + '--data-root expects a directory. Usage: orca serve --reclaim-stale-lock [--data-root ] [--yes] [--json]' + }) + expect(reclaimStaleLockMock).not.toHaveBeenCalled() + expect(printReclaimResultMock).not.toHaveBeenCalled() + }) +}) diff --git a/src/cli/handlers/core.ts b/src/cli/runtime/cli-lifecycle-handlers.ts similarity index 90% rename from src/cli/handlers/core.ts rename to src/cli/runtime/cli-lifecycle-handlers.ts index 4eba110c8c2..e4262f51ec9 100644 --- a/src/cli/handlers/core.ts +++ b/src/cli/runtime/cli-lifecycle-handlers.ts @@ -1,15 +1,16 @@ import { spawn } from 'node:child_process' import { resolve } from 'node:path' -import type { CommandHandler } from '../dispatch' -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' -import { resolveCliStatusCaller } from '../runtime/status-caller' -import { getServeSuperviseValidationError } from '../runtime/serve-supervised-service' -import { getOptionalServePort } from '../runtime/serve-port-flag' -import { resolveLaunchUserDataPath } from '../runtime/launch-user-data-path' +import type { CommandHandler } from '../dispatch/dispatch' +import { formatCliStatus, formatCliStatus as formatStatus } from './cli-status-format' +import { printResult } from '../output/command-result-output' +import { RuntimeClientError } from './types' +import { serveOrcaApp } from './launch' +import { getOptionalServeBind } from './serve-bind-flag' +import { stripElectronRunAsNode } from './orca-app-executable' +import { resolveCliStatusCaller } from './status-caller' +import { getServeSuperviseValidationError } from './serve-supervised-service' +import { getOptionalServePort } from './serve-port-flag' +import { resolveLaunchUserDataPath } from './launch-user-data-path' import { getServeOptionValidationError } from '../../shared/serve-option-validation' function envRecord(): Record { diff --git a/src/cli/runtime/client-recovery.test.ts b/src/cli/runtime/client-recovery.test.ts index f285a2a04e6..5451b53463f 100644 --- a/src/cli/runtime/client-recovery.test.ts +++ b/src/cli/runtime/client-recovery.test.ts @@ -4,9 +4,10 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' import '../../shared/protocol-version' -import '../orchestration-mutation-recovery' -import { reportCliError } from '../cli-error' -import { RuntimeClient, RuntimeClientError, RuntimeRpcFailureError } from '../runtime-client' +import '../orchestration/recovery/orchestration-mutation-recovery' +import { reportCliError } from '../output/cli-error' +import { RuntimeClient } from './client' +import { RuntimeClientError, RuntimeRpcFailureError } from './types' const servers = new Set() diff --git a/src/cli/runtime-client.test.ts b/src/cli/runtime/client.test.ts similarity index 96% rename from src/cli/runtime-client.test.ts rename to src/cli/runtime/client.test.ts index d3aef2a0cfa..452381691cc 100644 --- a/src/cli/runtime-client.test.ts +++ b/src/cli/runtime/client.test.ts @@ -3,12 +3,12 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { createServer, type Socket } from 'node:net' import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' -import '../shared/protocol-version' -import { RuntimeClient } from './runtime-client' -import { launchOrcaApp } from './runtime/launch' -import './cli-error' +import '../../shared/protocol-version' +import { RuntimeClient } from './client' +import { launchOrcaApp } from './launch' +import '../output/cli-error' -vi.mock('./runtime/launch', () => ({ +vi.mock('./launch', () => ({ launchOrcaApp: vi.fn() })) diff --git a/src/cli/runtime/client.ts b/src/cli/runtime/client.ts index 40b8c360b35..04f2cdad1b4 100644 --- a/src/cli/runtime/client.ts +++ b/src/cli/runtime/client.ts @@ -38,7 +38,7 @@ import { ORCHESTRATION_CONTRACT_VERSION } from '../../shared/orchestration/orchestration-runtime-capabilities' import { RemoteRuntimeCompatGate } from './remote-runtime-compat-gate' -import { OrchestrationRequestEvidence } from './orchestration-compatibility-envelope' +import { OrchestrationRequestEvidence } from '../orchestration/identity/orchestration-compatibility-envelope' import { getTimeoutMsParam, isWaitingCheck } from './runtime-request-timeout' import { isWorkerStartTimeoutWithinTimerLimit, @@ -49,7 +49,7 @@ import { MAX_TIMER_DELAY_MS } from '../../shared/timer-delay' import { buildOrchestrationRecoveryCommand, resolveOrchestrationCliExecutable -} from './orchestration-recovery-command' +} from '../orchestration/recovery/orchestration-recovery-command' const LONG_POLL_CLIENT_GRACE_MS = 10_000 // The host records the launched agent in the caller's chat; older hosts ignore the evidence. diff --git a/src/cli/test-fixtures.ts b/src/cli/runtime/fixtures/runtime-rpc-fixtures.ts similarity index 95% rename from src/cli/test-fixtures.ts rename to src/cli/runtime/fixtures/runtime-rpc-fixtures.ts index adeceeea6f3..0366061b681 100644 --- a/src/cli/test-fixtures.ts +++ b/src/cli/runtime/fixtures/runtime-rpc-fixtures.ts @@ -1,6 +1,6 @@ import type { Mock } from 'vitest' -import type { ExecutionHostId } from '../shared/execution-host' -import { RuntimeRpcFailureError } from './runtime/types' +import type { ExecutionHostId } from '../../../shared/execution-host' +import { RuntimeRpcFailureError } from '../types' type OkFixture = { id: string diff --git a/src/cli/runtime/runtime-source-fence.test.ts b/src/cli/runtime/runtime-source-fence.test.ts index a3841e63290..95667fa8c8e 100644 --- a/src/cli/runtime/runtime-source-fence.test.ts +++ b/src/cli/runtime/runtime-source-fence.test.ts @@ -9,7 +9,8 @@ import { RUNTIME_SOURCE_INCARNATION_ENV, RUNTIME_SOURCE_PROFILE_PATH_ENV } from '../../shared/runtime-source-env' -import { RuntimeClient, RuntimeClientError } from '../runtime-client' +import { RuntimeClient } from './client' +import { RuntimeClientError } from './types' import { resolveFencedRuntimeSource } from './runtime-source-fence' const SOURCE_A = '11111111-1111-4111-8111-111111111111' diff --git a/src/cli/runtime/serve-bind-flag.ts b/src/cli/runtime/serve-bind-flag.ts index 168015bf678..89a6b12939a 100644 --- a/src/cli/runtime/serve-bind-flag.ts +++ b/src/cli/runtime/serve-bind-flag.ts @@ -1,5 +1,5 @@ import { resolveOrcadBindHost } from '../../shared/orcad-bind-address' -import { getPresentStringFlag } from '../flags' +import { getPresentStringFlag } from '../arguments/flags' import { RuntimeClientError } from './types' /** Convert a CLI bind value into the normalized literal address used by serve. */ diff --git a/src/cli/runtime/status-caller.test.ts b/src/cli/runtime/status-caller.test.ts index 0f37f2c58ba..338d1429cb3 100644 --- a/src/cli/runtime/status-caller.test.ts +++ b/src/cli/runtime/status-caller.test.ts @@ -5,7 +5,7 @@ import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { getRuntimeMetadataPath } from '../../shared/runtime-bootstrap' import type { RuntimeOrchestrationEnvelope } from '../../shared/runtime-rpc-envelope' -import { CORE_HANDLERS } from '../handlers/core' +import { CORE_HANDLERS } from './cli-lifecycle-handlers' import { RuntimeClient } from './client' const SESSION = '4a1f6c2e-8b3d-4e7a-9c15-0d2b6e8f1a37' diff --git a/src/cli/runtime/transport.test.ts b/src/cli/runtime/transport.test.ts index 72b84cfe1e6..567982cd0e9 100644 --- a/src/cli/runtime/transport.test.ts +++ b/src/cli/runtime/transport.test.ts @@ -8,7 +8,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import type { RuntimeMetadata } from '../../shared/runtime-bootstrap' import { MAX_TIMER_DELAY_MS } from '../../shared/timer-delay' import { sendRequest } from './transport' -import { formatCliError } from '../cli-error' +import { formatCliError } from '../output/cli-error' import { RuntimeClient } from './client' import { getRuntimeMetadataPath } from '../../shared/runtime-bootstrap' import { requestWorktreeRemoval } from '../workspaces/worktree-removal-request' diff --git a/src/cli/base64-payload-byte-count.ts b/src/cli/screenshots/base64-payload-byte-count.ts similarity index 100% rename from src/cli/base64-payload-byte-count.ts rename to src/cli/screenshots/base64-payload-byte-count.ts diff --git a/src/cli/cli-screenshot-temp-file.ts b/src/cli/screenshots/cli-screenshot-temp-file.ts similarity index 100% rename from src/cli/cli-screenshot-temp-file.ts rename to src/cli/screenshots/cli-screenshot-temp-file.ts diff --git a/src/cli/serve-electron-flag-parity.test.ts b/src/cli/serve-electron-flag-parity.test.ts deleted file mode 100644 index 77040924d7f..00000000000 --- a/src/cli/serve-electron-flag-parity.test.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { normalizeServeModeArgv } from '../main/startup/serve-mode-argv' -import { BOOLEAN_FLAGS } from './args' -import { SERVE_COMMAND_SPECS } from './specs/serve' - -// The main tsconfig cannot import CLI specs, so test the duplicated serve flag lists from here. - -// Help is refused; pairing selectors pass through; force, supervise and the stale-lock -// reclaim flags apply only to the CLI parent, which starts no runtime for a reclaim. -const UNTRANSLATED_GLOBAL_FLAGS = new Set([ - 'help', - 'pairing-code', - 'environment', - 'force', - 'supervise', - 'reclaim-stale-lock', - 'data-root', - 'yes' -]) - -const serveSpec = SERVE_COMMAND_SPECS.find((spec) => spec.path.join(' ') === 'serve') -const translatedFlags = [...new Set(serveSpec?.allowedFlags ?? [])].filter( - (flag) => !UNTRANSLATED_GLOBAL_FLAGS.has(flag) -) - -describe('serve flag parity between the CLI spec and the Electron argv rewrite', () => { - it('has a serve spec to compare against', () => { - expect(translatedFlags.length).toBeGreaterThan(0) - }) - - it.each(translatedFlags)('rewrites CLI-form --%s into the --serve-* form', (flag) => { - const takesValue = !BOOLEAN_FLAGS.has(flag) - const argv = takesValue - ? ['/AppRun', 'serve', `--${flag}`, 'value'] - : ['/AppRun', 'serve', `--${flag}`] - const expected = takesValue - ? ['/AppRun', '--serve', `--serve-${flag}`, 'value'] - : ['/AppRun', '--serve', `--serve-${flag}`] - - expect(normalizeServeModeArgv(argv)).toEqual(expected) - if (takesValue) { - expect(normalizeServeModeArgv(['/AppRun', 'serve', `--${flag}=value`])).toEqual(expected) - } else { - // Keep attached boolean values literal, as the CLI does for flags such as --no-pairing. - expect(normalizeServeModeArgv(['/AppRun', 'serve', `--${flag}=false`])).toEqual([ - '/AppRun', - '--serve', - `--${flag}=false` - ]) - } - // The app also normalizes argv already rewritten by the CLI launcher. - expect(normalizeServeModeArgv(expected)).toEqual(expected) - }) -}) diff --git a/src/cli/server/pair.ts b/src/cli/server/pair.ts index e29590af09f..99551b1f822 100644 --- a/src/cli/server/pair.ts +++ b/src/cli/server/pair.ts @@ -1,6 +1,6 @@ -import type { CommandHandler } from '../dispatch' -import { getOptionalStringFlag } from '../flags' -import { printResult } from '../command-result-output' +import type { CommandHandler } from '../dispatch/dispatch' +import { getOptionalStringFlag } from '../arguments/flags' +import { printResult } from '../output/command-result-output' import { RuntimeClientError } from '../runtime/types' import { PAIRING_CREATE_OFFER_METHOD, diff --git a/src/cli/server/serve-pairing-handler-groups.ts b/src/cli/server/serve-pairing-handler-groups.ts index f580c9a0313..e13bc85ccee 100644 --- a/src/cli/server/serve-pairing-handler-groups.ts +++ b/src/cli/server/serve-pairing-handler-groups.ts @@ -1,4 +1,4 @@ -import type { HandlerGroup } from '../handler-group-manifest' +import type { HandlerGroup } from '../dispatch/handler-group-manifest' // Split from handler-group-manifest.ts to keep it under the max-lines limit. export const SERVE_PAIRING_HANDLER_GROUPS: readonly HandlerGroup[] = [ diff --git a/src/cli/server/serve-reset-identity.ts b/src/cli/server/serve-reset-identity.ts index 15d17f5d8bc..8e15c0f97bc 100644 --- a/src/cli/server/serve-reset-identity.ts +++ b/src/cli/server/serve-reset-identity.ts @@ -1,4 +1,4 @@ -import type { CommandHandler } from '../dispatch' +import type { CommandHandler } from '../dispatch/dispatch' import { RuntimeClientError } from '../runtime/types' import { resolveLaunchUserDataPath } from '../runtime/launch-user-data-path' import { pluginDevWatchConfirmFor } from '../plugins/dev-watch/plugin-dev-watch-approval' diff --git a/src/cli/server/serve-restore.ts b/src/cli/server/serve-restore.ts index a0e16775d37..c65f499a7fb 100644 --- a/src/cli/server/serve-restore.ts +++ b/src/cli/server/serve-restore.ts @@ -1,5 +1,5 @@ -import type { CommandHandler } from '../dispatch' -import { printResult } from '../command-result-output' +import type { CommandHandler } from '../dispatch/dispatch' +import { printResult } from '../output/command-result-output' import type { AutomaticWorkMode, AutomaticWorkResumeResult, diff --git a/src/cli/server/serve-service.ts b/src/cli/server/serve-service.ts index f30df7566c7..d1052fe34a0 100644 --- a/src/cli/server/serve-service.ts +++ b/src/cli/server/serve-service.ts @@ -2,7 +2,7 @@ import { existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs' import { homedir } from 'node:os' import { dirname } from 'node:path' import { runProcess } from '@orca/process-host' -import type { CommandHandler } from '../dispatch' +import type { CommandHandler } from '../dispatch/dispatch' import { RuntimeClientError } from '../runtime/types' import { getOptionalServePort } from '../runtime/serve-port-flag' import { getOptionalServeBind, resolveServeBindValue } from '../runtime/serve-bind-flag' diff --git a/src/cli/session-search/search-command-arguments.test.ts b/src/cli/session-search/search-command-arguments.test.ts index 2a99b482fa3..82ecd693da7 100644 --- a/src/cli/session-search/search-command-arguments.test.ts +++ b/src/cli/session-search/search-command-arguments.test.ts @@ -4,8 +4,8 @@ import { parseArgs, validateCommandAndFlags, type ParsedArgs -} from '../args' -import { specPaths } from '../command-spec' +} from '../arguments/args' +import { specPaths } from '../discovery/command-spec' import { parseSearchCommand } from './search-command-arguments' import { COMMAND_SPECS } from '../specs/index' diff --git a/src/cli/session-search/search-command-arguments.ts b/src/cli/session-search/search-command-arguments.ts index 085c6d8474c..931278629ca 100644 --- a/src/cli/session-search/search-command-arguments.ts +++ b/src/cli/session-search/search-command-arguments.ts @@ -9,7 +9,7 @@ import { getOptionalPositiveIntegerFlag, getOptionalStringFlag, getRepeatedStringFlag -} from '../flags' +} from '../arguments/flags' import { RuntimeClientError } from '../runtime/types' export type SearchCommand = diff --git a/src/cli/session-search/search.ts b/src/cli/session-search/search.ts index ea87784486e..d4f8b67964e 100644 --- a/src/cli/session-search/search.ts +++ b/src/cli/session-search/search.ts @@ -4,8 +4,8 @@ import { formatSessionSearchResponse, formatSessionSearchStatus } from './agent-session-search-format' -import type { CommandHandler } from '../dispatch' -import { printResult } from '../command-result-output' +import type { CommandHandler } from '../dispatch/dispatch' +import { printResult } from '../output/command-result-output' import type { RuntimeClient } from '../runtime/client' import { RuntimeClientError } from '../runtime/types' import { parseSearchCommand } from './search-command-arguments' diff --git a/src/cli/skills/bundled-skill-install-command.ts b/src/cli/skills/bundled-skill-install-command.ts index 0692c948401..1f1449cc024 100644 --- a/src/cli/skills/bundled-skill-install-command.ts +++ b/src/cli/skills/bundled-skill-install-command.ts @@ -1,10 +1,10 @@ import { homedir } from 'node:os' import { realpath } from 'node:fs/promises' -import type { CommandHandler } from '../dispatch' +import type { CommandHandler } from '../dispatch/dispatch' import { RuntimeClientError } from '../runtime/types' import { getDefaultUserDataPath } from '../runtime/metadata' -import { getRepeatedStringFlag } from '../flags' -import { writeStdoutLine } from '../stdout-line' +import { getRepeatedStringFlag } from '../arguments/flags' +import { writeStdoutLine } from '../output/stdout-line' import { skillsCliAgentAliases } from './skills-cli-agent-aliases' import { loadCanonicalGuides, type BundledSkillGuide } from './bundled-skill-guide-table' import type { diff --git a/src/cli/skills/skill-guide-get.ts b/src/cli/skills/skill-guide-get.ts index 98c4b3e79ce..dfc1a35a5f8 100644 --- a/src/cli/skills/skill-guide-get.ts +++ b/src/cli/skills/skill-guide-get.ts @@ -1,6 +1,6 @@ -import type { CommandHandler, HandlerContext } from '../dispatch' +import type { CommandHandler, HandlerContext } from '../dispatch/dispatch' import { RuntimeClientError } from '../runtime/types' -import { writeStdoutLine } from '../stdout-line' +import { writeStdoutLine } from '../output/stdout-line' import { loadCanonicalGuides, requireTopic, diff --git a/src/cli/skills/skill-guide-host-gate.test.ts b/src/cli/skills/skill-guide-host-gate.test.ts deleted file mode 100644 index ae9ab6fff5a..00000000000 --- a/src/cli/skills/skill-guide-host-gate.test.ts +++ /dev/null @@ -1,138 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -type Settings = { artifactSharingEnabled?: boolean; agentSkillSharingEnabled?: boolean } -type Host = { settings: Settings | Error; isRemote?: boolean } | 'no-access' - -const { hostState } = vi.hoisted(() => { - const state: { host: Host; calls: number } = { host: 'no-access', calls: 0 } - return { hostState: state } -}) - -vi.mock('../runtime-client', async () => { - // Error formatting uses instanceof, so the mock must preserve the production classes. - const { RuntimeClientError, RuntimeRpcFailureError } = await import('../runtime/types.js') - - class RuntimeClient { - readonly isRemote: boolean - constructor() { - if (hostState.host === 'no-access') { - throw new Error('skills get contacted the host') - } - this.isRemote = hostState.host.isRemote ?? false - } - async call(method: string): Promise<{ result: { settings: Settings } }> { - hostState.calls += 1 - if (hostState.host === 'no-access' || method !== 'settings.get') { - throw new Error(`unexpected ${method}`) - } - if (hostState.host.settings instanceof Error) { - throw hostState.host.settings - } - return { result: { settings: hostState.host.settings } } - } - } - - return { - RuntimeClient, - RuntimeClientError, - RuntimeRpcFailureError, - serveOrcaApp: vi.fn(), - getDefaultUserDataPath: vi.fn(() => '/tmp/orca-user-data') - } -}) - -import { main } from '../index' - -const PUBLISHING_TEXT = /artifacts share|skills share|## Artifacts|## Skill Sharing/ - -async function skillsGet(args: string[], host: Host): Promise<{ stdout: string; stderr: string }> { - hostState.host = host - let stdout = '' - let stderr = '' - vi.spyOn(process.stdout, 'write').mockImplementation((chunk) => { - stdout += String(chunk) - return true - }) - vi.spyOn(console, 'error').mockImplementation((message) => { - stderr += String(message) - }) - await main(['skills', 'get', 'orca-cli', ...args], '/tmp/repo') - vi.restoreAllMocks() - return { stdout, stderr } -} - -describe('skills get host-capability gating', () => { - beforeEach(() => { - hostState.calls = 0 - process.exitCode = undefined - }) - - afterEach(() => { - vi.restoreAllMocks() - vi.unstubAllEnvs() - process.exitCode = undefined - }) - - it.each<[string, Host]>([ - ['publishing is off', { settings: { artifactSharingEnabled: false } }], - ['the host omits the settings (headless or older)', { settings: {} }], - ['the host is unreachable', { settings: new Error('Orca is not running') }] - ])('withholds publishing from every guide shape when %s', async (_label, host) => { - const guide = await skillsGet([], host) - const full = await skillsGet(['--full'], host) - const listed = await skillsGet(['--references'], host) - const withheld = await skillsGet(['--reference', 'references/artifacts.md'], host) - - expect(guide.stdout).not.toMatch(PUBLISHING_TEXT) - expect(full.stdout).not.toMatch(PUBLISHING_TEXT) - expect(full.stdout).not.toContain('host-capability') - expect(listed.stdout.trim().split('\n')).toEqual(['automations', 'browser', 'plugins']) - expect(withheld.stdout).toBe('') - expect(withheld.stderr).toContain('turned off on this host') - }) - - it('serves publishing guidance when the host has it on, asking the host once', async () => { - const host: Host = { - settings: { artifactSharingEnabled: true, agentSkillSharingEnabled: true } - } - const full = await skillsGet(['--full'], host) - expect(hostState.calls).toBe(1) - const listed = await skillsGet(['--references'], host) - - expect(full.stdout).toContain('## Artifacts') - expect(full.stdout).toContain('ORCA artifacts share --json') - expect(full.stdout).toContain('ORCA skills share --skill') - expect(full.stdout).not.toContain('host-capability') - expect(listed.stdout.trim().split('\n')).toEqual([ - 'artifacts', - 'automations', - 'browser', - 'plugins', - 'skill-sharing' - ]) - }) - - it.each<[string, Host, Record]>([ - [ - 'a remote runtime', - { - settings: { artifactSharingEnabled: true, agentSkillSharingEnabled: true }, - isRemote: true - }, - {} - ], - [ - 'a forwarded invocation', - { settings: { artifactSharingEnabled: true, agentSkillSharingEnabled: true } }, - { ORCA_CLI_CWD: '/remote/repo' } - ] - ])('withholds skill sharing from %s, where skills share refuses', async (_label, host, env) => { - for (const [name, value] of Object.entries(env)) { - vi.stubEnv(name, value) - } - const guide = await skillsGet([], host) - - expect(guide.stdout).toContain('## Artifacts') - expect(guide.stdout).not.toContain('## Skill Sharing') - }) -}) diff --git a/src/cli/skills/skill-guide-host-gate.ts b/src/cli/skills/skill-guide-host-gate.ts index 26a4ec95ceb..29fc311de2d 100644 --- a/src/cli/skills/skill-guide-host-gate.ts +++ b/src/cli/skills/skill-guide-host-gate.ts @@ -1,4 +1,4 @@ -import type { HandlerContext } from '../dispatch' +import type { HandlerContext } from '../dispatch/dispatch' // Guides wrap feature-specific text in these blocks so agents only learn features the host has on. export const GUIDE_HOST_CAPABILITIES = ['artifact-publishing', 'skill-publishing'] as const diff --git a/src/cli/skills/skill-sharing.test.ts b/src/cli/skills/skill-sharing.test.ts index 47118221f00..f5e278a8171 100644 --- a/src/cli/skills/skill-sharing.test.ts +++ b/src/cli/skills/skill-sharing.test.ts @@ -1,7 +1,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { RuntimeClient } from '../runtime/client' import { RuntimeRpcFailureError } from '../runtime/types' -import type { HandlerContext } from '../dispatch' +import type { HandlerContext } from '../dispatch/dispatch' import { SKILL_SHARING_HANDLERS } from './skill-sharing' const successMeta = { runtimeId: 'runtime-1' } diff --git a/src/cli/skills/skill-sharing.ts b/src/cli/skills/skill-sharing.ts index 17f2d7b9030..23ef622d718 100644 --- a/src/cli/skills/skill-sharing.ts +++ b/src/cli/skills/skill-sharing.ts @@ -10,9 +10,9 @@ import { import { normalizeSkillBundleName } from '../../shared/skill-bundle-name' 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 '../command-result-output' +import type { CommandHandler, HandlerContext } from '../dispatch/dispatch' +import { getRepeatedStringFlag } from '../arguments/flags' +import { printResult } from '../output/command-result-output' import { RuntimeClientError, RuntimeRpcFailureError } from '../runtime/types' import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope' diff --git a/src/cli/skills/skills-reference-selector.test.ts b/src/cli/skills/skills-reference-selector.test.ts index f98696917ce..4c3eef7ac50 100644 --- a/src/cli/skills/skills-reference-selector.test.ts +++ b/src/cli/skills/skills-reference-selector.test.ts @@ -22,27 +22,26 @@ vi.mock('./bundled-skill-guides.js', () => ({ ] })) -vi.mock('../runtime-client', async () => { - const { RuntimeClientError, RuntimeRpcFailureError } = await import('../runtime/types.js') +vi.mock('../runtime/client', () => { class RuntimeClient { constructor() { throw new Error('skills get constructed a RuntimeClient') } } - return { - RuntimeClient, - RuntimeClientError, - RuntimeRpcFailureError, - serveOrcaApp: vi.fn(), - getDefaultUserDataPath: vi.fn(() => '/tmp/orca-user-data') - } + return { RuntimeClient } }) -import { main } from '../index' +vi.mock('../runtime/launch', async (importOriginal) => ({ + ...(await importOriginal>()), + serveOrcaApp: vi.fn() +})) -function stdoutText(spy: ReturnType): string { - return spy.mock.calls.map((call) => String(call[0])).join('') -} +vi.mock('../runtime/metadata', async (importOriginal) => ({ + ...(await importOriginal>()), + getDefaultUserDataPath: vi.fn(() => '/tmp/orca-user-data') +})) + +import { main } from '../index' describe('orca skills get --reference', () => { beforeEach(() => { @@ -50,22 +49,6 @@ describe('orca skills get --reference', () => { process.exitCode = undefined }) - it('accepts the references/.md spelling the gate table prints', async () => { - const stdoutSpy = vi.spyOn(process.stdout, 'write').mockImplementation(() => true) - - await main(['skills', 'get', 'alpha', '--reference', 'references/first-gate.md'], '/tmp/repo') - - expect(stdoutText(stdoutSpy)).toBe('# First gate\n\nDo the first thing.\n') - }) - - it('resolves a reference through a topic alias', async () => { - const stdoutSpy = vi.spyOn(process.stdout, 'write').mockImplementation(() => true) - - await main(['skills', 'get', 'legacy-alpha', '--reference', 'first-gate.md'], '/tmp/repo') - - expect(stdoutText(stdoutSpy)).toBe('# First gate\n\nDo the first thing.\n') - }) - it('reports a topic that ships no references', async () => { const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) diff --git a/src/cli/skills/skills.ts b/src/cli/skills/skills.ts index 6ee52f43c1e..f361bb9bfdd 100644 --- a/src/cli/skills/skills.ts +++ b/src/cli/skills/skills.ts @@ -1,5 +1,5 @@ -import type { CommandHandler } from '../dispatch' -import { writeStdoutLine } from '../stdout-line' +import type { CommandHandler } from '../dispatch/dispatch' +import { writeStdoutLine } from '../output/stdout-line' import { loadCanonicalGuides } from './bundled-skill-guide-table' import { SKILL_GUIDE_GET_HANDLER } from './skill-guide-get' import { createSkillMutationHandler } from './bundled-skill-install-command' diff --git a/src/cli/specs/account.ts b/src/cli/specs/account.ts index 1b93df78f2f..cb0938f129c 100644 --- a/src/cli/specs/account.ts +++ b/src/cli/specs/account.ts @@ -1,4 +1,5 @@ -import { LOCAL_COMMAND_FLAGS, type CommandSpec } from '../args' +import { LOCAL_COMMAND_FLAGS } from '../arguments/args' +import type { CommandSpec } from '../discovery/command-spec' // Terminal login lets headless hosts manage accounts without the desktop login UI. export const ACCOUNT_COMMAND_SPECS: CommandSpec[] = [ diff --git a/src/cli/specs/agent-hooks.ts b/src/cli/specs/agent-hooks.ts index 926bc397dba..d98913ad63a 100644 --- a/src/cli/specs/agent-hooks.ts +++ b/src/cli/specs/agent-hooks.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { LOCAL_COMMAND_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { LOCAL_COMMAND_FLAGS } from '../arguments/args' export const AGENT_HOOK_COMMAND_SPECS: CommandSpec[] = [ { diff --git a/src/cli/specs/agent-launch.ts b/src/cli/specs/agent-launch.ts index ac1ef1870ff..fb8928a5a8a 100644 --- a/src/cli/specs/agent-launch.ts +++ b/src/cli/specs/agent-launch.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { GLOBAL_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary' export const AGENT_LAUNCH_COMMAND_SPECS: CommandSpec[] = [ { diff --git a/src/cli/specs/artifacts.ts b/src/cli/specs/artifacts.ts index 5caa5bfd610..06cc845f118 100644 --- a/src/cli/specs/artifacts.ts +++ b/src/cli/specs/artifacts.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { LOCAL_COMMAND_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { LOCAL_COMMAND_FLAGS } from '../arguments/args' const CLOUD_FLAGS = ['api-url'] diff --git a/src/cli/specs/automations.ts b/src/cli/specs/automations.ts index a7597c8f0e0..7eaffd671d6 100644 --- a/src/cli/specs/automations.ts +++ b/src/cli/specs/automations.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { GLOBAL_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary' const AUTOMATION_TARGET_FLAGS = [ 'repo', diff --git a/src/cli/specs/browser-advanced.ts b/src/cli/specs/browser-advanced.ts index 39cbcee9105..63d3dd66dba 100644 --- a/src/cli/specs/browser-advanced.ts +++ b/src/cli/specs/browser-advanced.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { GLOBAL_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary' import { withBrowserPageTarget } from './browser-page-target' export const BROWSER_ADVANCED_COMMAND_SPECS: CommandSpec[] = withBrowserPageTarget([ diff --git a/src/cli/specs/browser-basic.ts b/src/cli/specs/browser-basic.ts index b25628d9e4a..314c2ba418d 100644 --- a/src/cli/specs/browser-basic.ts +++ b/src/cli/specs/browser-basic.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { GLOBAL_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary' import { withBrowserPageTarget } from './browser-page-target' import { BROWSER_WAIT_DEFAULT_TIMEOUT_MS } from '../../shared/browser-wait-timeout' diff --git a/src/cli/specs/browser-page-target.ts b/src/cli/specs/browser-page-target.ts index ab303ca29f7..a99bc86fe6c 100644 --- a/src/cli/specs/browser-page-target.ts +++ b/src/cli/specs/browser-page-target.ts @@ -1,4 +1,4 @@ -import type { CommandSpec } from '../args' +import type { CommandSpec } from '../discovery/command-spec' // These open, list or configure pages, so there is no one page to target. const NOT_PAGE_TARGETED = new Set([ diff --git a/src/cli/specs/chat.ts b/src/cli/specs/chat.ts index 28fb41556dd..6793d785e59 100644 --- a/src/cli/specs/chat.ts +++ b/src/cli/specs/chat.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { GLOBAL_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary' export const CHAT_COMMAND_SPECS: CommandSpec[] = [ { diff --git a/src/cli/specs/computer.ts b/src/cli/specs/computer.ts index 333904e0b0a..6ddc43e110a 100644 --- a/src/cli/specs/computer.ts +++ b/src/cli/specs/computer.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { GLOBAL_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary' const COMPUTER_FLAGS = [...GLOBAL_FLAGS, 'worktree', 'session', 'app'] const COMPUTER_WINDOW_TARGET_FLAGS = ['window-id', 'window-index'] diff --git a/src/cli/specs/connector.ts b/src/cli/specs/connector.ts index d974079d687..66c8c11fd3e 100644 --- a/src/cli/specs/connector.ts +++ b/src/cli/specs/connector.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { GLOBAL_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary' const CONNECTOR_NOTES = [ 'Development only: drives the connector seam as a `dev` conversation, without Orca Cloud. The host refuses it unless its experimentalConnectors setting is on.', diff --git a/src/cli/specs/core.ts b/src/cli/specs/core.ts index 120b61001d3..67b5462b565 100644 --- a/src/cli/specs/core.ts +++ b/src/cli/specs/core.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { GLOBAL_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary' import { WORKTREE_LISTING_SCOPE_NOTES } from './worktree-listing-scope-notes' import { WORKTREE_CREATE_COMMAND_SPEC } from './worktree-create' import { WORKTREE_SET_COMMAND_SPEC } from './worktree-set' diff --git a/src/cli/specs/diagnostics.ts b/src/cli/specs/diagnostics.ts index 24bfc3fd146..810538e0832 100644 --- a/src/cli/specs/diagnostics.ts +++ b/src/cli/specs/diagnostics.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { GLOBAL_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary' export const DIAGNOSTICS_COMMAND_SPECS: CommandSpec[] = [ { diff --git a/src/cli/specs/emulator.ts b/src/cli/specs/emulator.ts index 8612fddef8a..a08c1a0e3bc 100644 --- a/src/cli/specs/emulator.ts +++ b/src/cli/specs/emulator.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { GLOBAL_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary' export const EMULATOR_COMMAND_SPECS: CommandSpec[] = [ { diff --git a/src/cli/specs/environment.ts b/src/cli/specs/environment.ts index f44a0fa5e56..b2db0124550 100644 --- a/src/cli/specs/environment.ts +++ b/src/cli/specs/environment.ts @@ -1,5 +1,6 @@ -import type { CommandSpec } from '../args' -import { GLOBAL_FLAGS, LOCAL_COMMAND_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary' +import { LOCAL_COMMAND_FLAGS } from '../arguments/args' export const ENVIRONMENT_COMMAND_SPECS: CommandSpec[] = [ { diff --git a/src/cli/specs/file.ts b/src/cli/specs/file.ts index fc3d4ee86a8..8e264e58b64 100644 --- a/src/cli/specs/file.ts +++ b/src/cli/specs/file.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { GLOBAL_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary' export const FILE_COMMAND_SPECS: CommandSpec[] = [ { diff --git a/src/cli/specs/index.ts b/src/cli/specs/index.ts index 7b76d41acdf..33b953cfcba 100644 --- a/src/cli/specs/index.ts +++ b/src/cli/specs/index.ts @@ -1,4 +1,4 @@ -import type { CommandSpec } from '../args' +import type { CommandSpec } from '../discovery/command-spec' import { ACCOUNT_COMMAND_SPECS } from './account' import { BROWSER_ADVANCED_COMMAND_SPECS } from './browser-advanced' import { BROWSER_BASIC_COMMAND_SPECS } from './browser-basic' diff --git a/src/cli/specs/introspection.ts b/src/cli/specs/introspection.ts index be0269a5773..24a9ec61e17 100644 --- a/src/cli/specs/introspection.ts +++ b/src/cli/specs/introspection.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { LOCAL_COMMAND_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { LOCAL_COMMAND_FLAGS } from '../arguments/args' export const INTROSPECTION_COMMAND_SPECS: CommandSpec[] = [ { diff --git a/src/cli/specs/jira.ts b/src/cli/specs/jira.ts index e9bf51cfe6f..c2ee60615d4 100644 --- a/src/cli/specs/jira.ts +++ b/src/cli/specs/jira.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { GLOBAL_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary' const SITE_FLAGS = [...GLOBAL_FLAGS, 'site'] diff --git a/src/cli/specs/linear-mcp.ts b/src/cli/specs/linear-mcp.ts index 531a4181378..2940277c41a 100644 --- a/src/cli/specs/linear-mcp.ts +++ b/src/cli/specs/linear-mcp.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { GLOBAL_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary' export const LINEAR_MCP_COMMAND_SPECS: CommandSpec[] = [ { diff --git a/src/cli/specs/linear.ts b/src/cli/specs/linear.ts index 05bb0225747..536e9e89cd6 100644 --- a/src/cli/specs/linear.ts +++ b/src/cli/specs/linear.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { GLOBAL_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary' import { LINEAR_MCP_COMMAND_SPECS } from './linear-mcp' export const LINEAR_COMMAND_SPECS: CommandSpec[] = [ diff --git a/src/cli/specs/managed-server.ts b/src/cli/specs/managed-server.ts index 160c42c77bd..33b1ffd87ad 100644 --- a/src/cli/specs/managed-server.ts +++ b/src/cli/specs/managed-server.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { LOCAL_COMMAND_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { LOCAL_COMMAND_FLAGS } from '../arguments/args' const SELECTOR_NOTE = '--environment names a managed Orca server this machine deployed over SSH (see `orca environment list`); it is a selector here, not a routing flag.' diff --git a/src/cli/specs/orchestration-full-record-flag.ts b/src/cli/specs/orchestration-full-record-flag.ts index 193ccd7b426..fb096380113 100644 --- a/src/cli/specs/orchestration-full-record-flag.ts +++ b/src/cli/specs/orchestration-full-record-flag.ts @@ -1,4 +1,4 @@ -import type { CommandSpec } from '../args' +import type { CommandSpec } from '../discovery/command-spec' // Output is the concise agent view by default; --full prints the whole record Orca returned. export function withFullRecordFlag(spec: CommandSpec): CommandSpec { diff --git a/src/cli/specs/orchestration-gate-specs.ts b/src/cli/specs/orchestration-gate-specs.ts index 57ee98d0cb9..9dd0927ad1d 100644 --- a/src/cli/specs/orchestration-gate-specs.ts +++ b/src/cli/specs/orchestration-gate-specs.ts @@ -1,4 +1,5 @@ -import { GLOBAL_FLAGS, type CommandSpec } from '../args' +import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary' +import type { CommandSpec } from '../discovery/command-spec' export const ORCHESTRATION_GATE_COMMAND_SPECS: CommandSpec[] = [ { diff --git a/src/cli/specs/orchestration-worker-specs.ts b/src/cli/specs/orchestration-worker-specs.ts index f0af62ce302..87d826d2e29 100644 --- a/src/cli/specs/orchestration-worker-specs.ts +++ b/src/cli/specs/orchestration-worker-specs.ts @@ -1,4 +1,5 @@ -import { GLOBAL_FLAGS, type CommandSpec } from '../args' +import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary' +import type { CommandSpec } from '../discovery/command-spec' export const ORCHESTRATION_WORKER_COMMAND_SPECS: CommandSpec[] = [ { diff --git a/src/cli/specs/orchestration.ts b/src/cli/specs/orchestration.ts index bbb9e89c261..135b194a114 100644 --- a/src/cli/specs/orchestration.ts +++ b/src/cli/specs/orchestration.ts @@ -1,4 +1,5 @@ -import { GLOBAL_FLAGS, type CommandSpec } from '../args' +import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary' +import type { CommandSpec } from '../discovery/command-spec' import { ORCHESTRATION_GATE_COMMAND_SPECS } from './orchestration-gate-specs' import { ORCHESTRATION_WORKER_COMMAND_SPECS } from './orchestration-worker-specs' diff --git a/src/cli/specs/pair.ts b/src/cli/specs/pair.ts index 83fb43fe6ec..11ece28965a 100644 --- a/src/cli/specs/pair.ts +++ b/src/cli/specs/pair.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { GLOBAL_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary' export const PAIR_COMMAND_SPECS: CommandSpec[] = [ { diff --git a/src/cli/specs/plugin-dev-request.ts b/src/cli/specs/plugin-dev-request.ts index b09b5e4c670..85baeaaa395 100644 --- a/src/cli/specs/plugin-dev-request.ts +++ b/src/cli/specs/plugin-dev-request.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { GLOBAL_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary' /** `orca plugin dev hook`; listed in PLUGIN_RUNTIME_COMMAND_SPECS. */ export const PLUGIN_DEV_HOOK_COMMAND_SPEC: CommandSpec = { diff --git a/src/cli/specs/plugin-install.ts b/src/cli/specs/plugin-install.ts index 20303089b80..6c950b6df36 100644 --- a/src/cli/specs/plugin-install.ts +++ b/src/cli/specs/plugin-install.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { GLOBAL_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary' const EXIT_CODES_NOTE = 'Exit codes: 0 ok, 1 error, 3 approval is needed (approval_required or approval_stale).' diff --git a/src/cli/specs/plugin-view.ts b/src/cli/specs/plugin-view.ts index ce6c2f8c54c..f045197c2a6 100644 --- a/src/cli/specs/plugin-view.ts +++ b/src/cli/specs/plugin-view.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { GLOBAL_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary' /** Showing and capturing a plugin's UI in the Orca desktop app, so an agent can see what it built. */ export const PLUGIN_VIEW_COMMAND_SPECS: CommandSpec[] = [ diff --git a/src/cli/specs/plugin.ts b/src/cli/specs/plugin.ts index 3dd02f75db5..111943048b5 100644 --- a/src/cli/specs/plugin.ts +++ b/src/cli/specs/plugin.ts @@ -1,5 +1,6 @@ -import type { CommandSpec } from '../args' -import { GLOBAL_FLAGS, LOCAL_COMMAND_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary' +import { LOCAL_COMMAND_FLAGS } from '../arguments/args' import { PLUGIN_TEMPLATE_NAMES } from '../plugins/authoring/plugin-template-names' import { PLUGIN_DEV_HOOK_COMMAND_SPEC, PLUGIN_DEV_REQUEST_COMMAND_SPEC } from './plugin-dev-request' diff --git a/src/cli/specs/ports.ts b/src/cli/specs/ports.ts index e153fe5db1b..6f9037f365b 100644 --- a/src/cli/specs/ports.ts +++ b/src/cli/specs/ports.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { GLOBAL_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary' export const PORTS_COMMAND_SPECS: CommandSpec[] = [ { diff --git a/src/cli/specs/profile-state.ts b/src/cli/specs/profile-state.ts index 50743f3740b..b12530f2692 100644 --- a/src/cli/specs/profile-state.ts +++ b/src/cli/specs/profile-state.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { LOCAL_COMMAND_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { LOCAL_COMMAND_FLAGS } from '../arguments/args' export const PROFILE_STATE_COMMAND_SPECS: CommandSpec[] = [ { diff --git a/src/cli/specs/project.ts b/src/cli/specs/project.ts index 1f7d989b8ba..de1a1b1491c 100644 --- a/src/cli/specs/project.ts +++ b/src/cli/specs/project.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { GLOBAL_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary' export const PROJECT_COMMAND_SPECS: CommandSpec[] = [ { diff --git a/src/cli/specs/reference.ts b/src/cli/specs/reference.ts index 2185ca17000..034521f254a 100644 --- a/src/cli/specs/reference.ts +++ b/src/cli/specs/reference.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { GLOBAL_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary' export const REFERENCE_COMMAND_SPECS: CommandSpec[] = [ { diff --git a/src/cli/specs/repo.ts b/src/cli/specs/repo.ts index 2f1732d58f8..0aae0cf234f 100644 --- a/src/cli/specs/repo.ts +++ b/src/cli/specs/repo.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { GLOBAL_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary' export const REPO_COMMAND_SPECS: CommandSpec[] = [ { diff --git a/src/cli/specs/search.ts b/src/cli/specs/search.ts index 36d8a3a0e5d..77ff5676c0f 100644 --- a/src/cli/specs/search.ts +++ b/src/cli/specs/search.ts @@ -1,4 +1,5 @@ -import { GLOBAL_FLAGS, type CommandSpec } from '../args' +import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary' +import type { CommandSpec } from '../discovery/command-spec' // Status is a flag because a subcommand would collide with searching for the word "status". export const SEARCH_COMMAND_SPECS: CommandSpec[] = [ diff --git a/src/cli/specs/serve.ts b/src/cli/specs/serve.ts index 3bc6b770259..255dd3d13ab 100644 --- a/src/cli/specs/serve.ts +++ b/src/cli/specs/serve.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { LOCAL_COMMAND_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { LOCAL_COMMAND_FLAGS } from '../arguments/args' export const SERVE_COMMAND_SPECS: CommandSpec[] = [ { diff --git a/src/cli/specs/skills.ts b/src/cli/specs/skills.ts index b9afef401f2..6ee1cd4e2b4 100644 --- a/src/cli/specs/skills.ts +++ b/src/cli/specs/skills.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { GLOBAL_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary' export const SKILL_COMMAND_SPECS: CommandSpec[] = [ { diff --git a/src/cli/specs/speech.ts b/src/cli/specs/speech.ts index 98915568458..ed0054f06b9 100644 --- a/src/cli/specs/speech.ts +++ b/src/cli/specs/speech.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { GLOBAL_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary' export const SPEECH_COMMAND_SPECS: CommandSpec[] = [ { diff --git a/src/cli/specs/terminal-close.ts b/src/cli/specs/terminal-close.ts index 6e1f80a007c..bbb9bdfbbd5 100644 --- a/src/cli/specs/terminal-close.ts +++ b/src/cli/specs/terminal-close.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { GLOBAL_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary' export const TERMINAL_CLOSE_COMMAND_SPEC: CommandSpec = { path: ['terminal', 'close'], diff --git a/src/cli/specs/terminal-daemon.ts b/src/cli/specs/terminal-daemon.ts index cea526b9d87..2db6eeb1bab 100644 --- a/src/cli/specs/terminal-daemon.ts +++ b/src/cli/specs/terminal-daemon.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { GLOBAL_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary' export const TERMINAL_DAEMON_COMMAND_SPECS: CommandSpec[] = [ { diff --git a/src/cli/specs/terminal-send.ts b/src/cli/specs/terminal-send.ts index dfddfe29a0c..4d49d2c2d00 100644 --- a/src/cli/specs/terminal-send.ts +++ b/src/cli/specs/terminal-send.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { GLOBAL_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary' export const TERMINAL_SEND_COMMAND_SPEC: CommandSpec = { path: ['terminal', 'send'], diff --git a/src/cli/specs/terminal-set-pane-title.ts b/src/cli/specs/terminal-set-pane-title.ts index 76603f8d681..de429d036fd 100644 --- a/src/cli/specs/terminal-set-pane-title.ts +++ b/src/cli/specs/terminal-set-pane-title.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { GLOBAL_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary' export const TERMINAL_SET_PANE_TITLE_COMMAND_SPEC: CommandSpec = { path: ['terminal', 'set-pane-title'], diff --git a/src/cli/specs/vm-env.ts b/src/cli/specs/vm-env.ts index ee0ea135a8e..c12d2d135cc 100644 --- a/src/cli/specs/vm-env.ts +++ b/src/cli/specs/vm-env.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { LOCAL_COMMAND_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { LOCAL_COMMAND_FLAGS } from '../arguments/args' export const VM_ENV_COMMAND_SPECS: CommandSpec[] = [ { diff --git a/src/cli/specs/vm.ts b/src/cli/specs/vm.ts index fb98c7d7674..68f0b9ad6f5 100644 --- a/src/cli/specs/vm.ts +++ b/src/cli/specs/vm.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { LOCAL_COMMAND_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { LOCAL_COMMAND_FLAGS } from '../arguments/args' export const VM_COMMAND_SPECS: CommandSpec[] = [ { diff --git a/src/cli/specs/worktree-create.ts b/src/cli/specs/worktree-create.ts index 743f4b68504..0abc6caac0b 100644 --- a/src/cli/specs/worktree-create.ts +++ b/src/cli/specs/worktree-create.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { GLOBAL_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary' export const WORKTREE_CREATE_COMMAND_SPEC: CommandSpec = { path: ['worktree', 'create'], diff --git a/src/cli/specs/worktree-set.ts b/src/cli/specs/worktree-set.ts index 3203a9cb2a2..1722cc4c0e0 100644 --- a/src/cli/specs/worktree-set.ts +++ b/src/cli/specs/worktree-set.ts @@ -1,5 +1,5 @@ -import type { CommandSpec } from '../args' -import { GLOBAL_FLAGS } from '../args' +import type { CommandSpec } from '../discovery/command-spec' +import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary' export const WORKTREE_SET_COMMAND_SPEC: CommandSpec = { path: ['worktree', 'set'], diff --git a/src/cli/handlers/speech.test.ts b/src/cli/speech/speech.test.ts similarity index 100% rename from src/cli/handlers/speech.test.ts rename to src/cli/speech/speech.test.ts diff --git a/src/cli/handlers/speech.ts b/src/cli/speech/speech.ts similarity index 93% rename from src/cli/handlers/speech.ts rename to src/cli/speech/speech.ts index d0d7717c06e..e1870ed9797 100644 --- a/src/cli/handlers/speech.ts +++ b/src/cli/speech/speech.ts @@ -1,6 +1,7 @@ -import type { CommandHandler, HandlerContext } from '../dispatch' -import { printResult } from '../command-result-output' -import { RuntimeClientError, type RuntimeRpcSuccess } from '../runtime-client' +import type { CommandHandler, HandlerContext } from '../dispatch/dispatch' +import { printResult } from '../output/command-result-output' +import { RuntimeClientError } from '../runtime/types' +import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope' import { OPENAI_SPEECH_KEY_MAX_LENGTH } from '../../shared/rpc-contract/speech-params' type OpenAiSpeechKeyStatus = { configured: boolean; protection: string | null } diff --git a/src/cli/terminals/terminal-close.ts b/src/cli/terminals/terminal-close.ts index 0ef3a486843..73ad6b9bb73 100644 --- a/src/cli/terminals/terminal-close.ts +++ b/src/cli/terminals/terminal-close.ts @@ -2,10 +2,10 @@ import type { RuntimeTerminalClose, RuntimeWorktreeTerminalCloseResult } from '../../shared/runtime-terminal-contracts' -import type { CommandHandler } from '../dispatch' +import type { CommandHandler } from '../dispatch/dispatch' import { formatTerminalClose } from './terminal-format' -import { reportCliError } from '../cli-error' -import { printResult } from '../command-result-output' +import { reportCliError } from '../output/cli-error' +import { printResult } from '../output/command-result-output' import { RuntimeClientError } from '../runtime/types' import { getRequiredWorktreeSelector } from '../workspace-selection/workspace-selector' import { getTerminalHandle } from './terminal-selector' diff --git a/src/cli/terminals/terminal-daemon.ts b/src/cli/terminals/terminal-daemon.ts index 49c5dca4158..67a4f4298ea 100644 --- a/src/cli/terminals/terminal-daemon.ts +++ b/src/cli/terminals/terminal-daemon.ts @@ -1,9 +1,9 @@ -import type { CommandHandler } from '../dispatch' +import type { CommandHandler } from '../dispatch/dispatch' import { describePtyProcessCeiling, type PtyProcessCeilingState } from '../../shared/terminal/pty/native-process/pty-process-ceiling-state' -import { printResult } from '../command-result-output' +import { printResult } from '../output/command-result-output' import { RuntimeClientError } from '../runtime/types' type SeveredDaemonStatus = { diff --git a/src/cli/terminals/terminal-selector.ts b/src/cli/terminals/terminal-selector.ts index 3b7fa8617b5..f698e8ae000 100644 --- a/src/cli/terminals/terminal-selector.ts +++ b/src/cli/terminals/terminal-selector.ts @@ -1,5 +1,5 @@ import type { RuntimeClient } from '../runtime/client' -import { getPresentStringFlag } from '../flags' +import { getPresentStringFlag } from '../arguments/flags' import type { WorkspaceSelectionPurpose } from '../workspace-selection/caller-host-worktree-selection' import { getBrowserWorktreeSelector } from '../workspace-selection/workspace-selector' diff --git a/src/cli/terminals/terminal-send.ts b/src/cli/terminals/terminal-send.ts index b082802b5ea..e7b749197df 100644 --- a/src/cli/terminals/terminal-send.ts +++ b/src/cli/terminals/terminal-send.ts @@ -1,11 +1,11 @@ import type { RuntimeTerminalSend } from '../../shared/runtime-terminal-send-contract' import '../../shared/protocol-version' import { TERMINAL_PROMPT_DELIVERY_RUNTIME_CAPABILITY } from '../../shared/terminal/runtime-policy/terminal-runtime-capabilities' -import type { CommandHandler } from '../dispatch' +import type { CommandHandler } from '../dispatch/dispatch' import { formatTerminalSend, terminalSendWarnings } from './terminal-format' -import { printResult } from '../command-result-output' -import { getOptionalPositiveIntegerFlag, getOptionalStringFlag } from '../flags' -import { readRetryRequestFlag } from '../retry-request-flag' +import { printResult } from '../output/command-result-output' +import { getOptionalPositiveIntegerFlag, getOptionalStringFlag } from '../arguments/flags' +import { readRetryRequestFlag } from '../orchestration/recovery/retry-request-flag' import { RuntimeClientError } from '../runtime/types' import { attachUnverifiedTerminalPromptRecovery } from '../runtime/terminal-prompt-mutation-recovery' import { getTerminalHandle } from './terminal-selector' diff --git a/src/cli/terminals/terminal.ts b/src/cli/terminals/terminal.ts index 09367ab9dcb..0474b05b0f4 100644 --- a/src/cli/terminals/terminal.ts +++ b/src/cli/terminals/terminal.ts @@ -9,7 +9,7 @@ import type { RuntimeTerminalSplit, RuntimeTerminalWait } from '../../shared/runtime-terminal-contracts' -import type { CommandHandler } from '../dispatch' +import type { CommandHandler } from '../dispatch/dispatch' import { shouldUseRendererBackedInteractiveTerminal } from './codex-command-classification' import { formatTerminalCreate, @@ -22,13 +22,13 @@ import { formatTerminalSplit, formatTerminalWait } from './terminal-format' -import { printResult } from '../command-result-output' +import { printResult } from '../output/command-result-output' import { getOptionalPositiveIntegerFlag, getOptionalStringFlag, getRequiredStringFlag, getRequiredStringFlagAllowingEmpty -} from '../flags' +} from '../arguments/flags' import { annotateOmittedHostScope, type WithAnnotatedHostScope diff --git a/src/cli/workspace-ports/ports.ts b/src/cli/workspace-ports/ports.ts index 21f99099f3e..4e1b05c2e42 100644 --- a/src/cli/workspace-ports/ports.ts +++ b/src/cli/workspace-ports/ports.ts @@ -5,9 +5,9 @@ import type { RuntimeWorktreeRecord } from '../../shared/runtime-worktree-contra 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 '../command-result-output' +import type { CommandHandler, HandlerContext } from '../dispatch/dispatch' +import { getOptionalStringFlag } from '../arguments/flags' +import { printResult } from '../output/command-result-output' import { formatPortsScan } from './ports-format' import { RuntimeClientError, RuntimeRpcFailureError } from '../runtime/types' import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope' diff --git a/src/cli/workspace-selection/caller-folder-workspace.ts b/src/cli/workspace-selection/caller-folder-workspace.ts index 0f4efa80738..0d69543e1d4 100644 --- a/src/cli/workspace-selection/caller-folder-workspace.ts +++ b/src/cli/workspace-selection/caller-folder-workspace.ts @@ -7,7 +7,7 @@ import { parseWorkspaceKey, type WorkspaceKey } from '../../shared/workspace-scope' -import { getOptionalStringFlag } from '../flags' +import { getOptionalStringFlag } from '../arguments/flags' import { RuntimeClientError } from '../runtime/types' import type { RuntimeClient } from '../runtime/client' import { getOptionalWorktreeSelector } from './workspace-selector' diff --git a/src/cli/workspace-selection/enclosing-workspace-rule.test.ts b/src/cli/workspace-selection/enclosing-workspace-rule.test.ts index 9ea900ad6b1..a9981f414e2 100644 --- a/src/cli/workspace-selection/enclosing-workspace-rule.test.ts +++ b/src/cli/workspace-selection/enclosing-workspace-rule.test.ts @@ -6,7 +6,7 @@ import { selectEnclosingWorktreeSelectionOnHost } from './caller-host-worktree-s import type { CatalogRow } from './workspace-catalog-row' import { readEnclosingWorkspaceCatalog } from './enclosing-workspace-catalog' import { RuntimeClient } from '../runtime/client' -import { okFixture } from '../test-fixtures' +import { okFixture } from '../runtime/fixtures/runtime-rpc-fixtures' function select(rows: CatalogRow[], cwd: string, caller?: string[]) { return selectEnclosingWorktreeSelectionOnHost(rows, cwd, 'local', caller)?.selector diff --git a/src/cli/selector-ambiguity-recovery.ts b/src/cli/workspace-selection/selector-ambiguity-recovery.ts similarity index 100% rename from src/cli/selector-ambiguity-recovery.ts rename to src/cli/workspace-selection/selector-ambiguity-recovery.ts diff --git a/src/cli/workspace-selection/workspace-selector.ts b/src/cli/workspace-selection/workspace-selector.ts index ce65d1b5152..ca9e356f972 100644 --- a/src/cli/workspace-selection/workspace-selector.ts +++ b/src/cli/workspace-selection/workspace-selector.ts @@ -5,7 +5,7 @@ import type { RuntimeClient } from '../runtime/client' import { RuntimeClientError } from '../runtime/types' import { assertLocalCwdWorktreeSelector } from '../hosts/local-environment-selector' import { isLaunchedByAnotherRuntime } from '../runtime/runtime-source-fence' -import { getOptionalStringFlag, getRequiredStringFlag } from '../flags' +import { getOptionalStringFlag, getRequiredStringFlag } from '../arguments/flags' import { readEnclosingWorkspaceCatalog } from './enclosing-workspace-catalog' import { getCallerExecutionHostId, diff --git a/src/cli/workspaces/folder-workspace-mutations.ts b/src/cli/workspaces/folder-workspace-mutations.ts index 3d85440f550..2e0dcc6e44b 100644 --- a/src/cli/workspaces/folder-workspace-mutations.ts +++ b/src/cli/workspaces/folder-workspace-mutations.ts @@ -8,8 +8,8 @@ import type { FolderWorkspace } from '../../shared/folder-workspaces/folder-work import { FOLDER_WORKSPACE_UNIQUE_ID_MUTATION_RUNTIME_CAPABILITY } from '../../shared/worktree-runtime-capabilities' import { folderIdOfSelector, folderWorkspaceKey } from '../../shared/workspace-scope' import { formatWorktreeShow } from './workspace-format' -import { printResult } from '../command-result-output' -import { getOptionalStringFlag, getOptionalStringFlagAllowingEmpty } from '../flags' +import { printResult } from '../output/command-result-output' +import { getOptionalStringFlag, getOptionalStringFlagAllowingEmpty } from '../arguments/flags' import { RuntimeClientError } from '../runtime/types' import type { RuntimeClient } from '../runtime/client' import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope' diff --git a/src/cli/workspaces/index-worktree-wsl-selection.test.ts b/src/cli/workspaces/index-worktree-wsl-selection.test.ts index bb38042d4e8..e625195d85d 100644 --- a/src/cli/workspaces/index-worktree-wsl-selection.test.ts +++ b/src/cli/workspaces/index-worktree-wsl-selection.test.ts @@ -12,7 +12,7 @@ import { selectEnclosingRepoOnHost, selectEnclosingWorktreeSelectionOnHost } from '../workspace-selection/caller-host-worktree-selection' -import { buildWorktree } from '../test-fixtures' +import { buildWorktree } from '../runtime/fixtures/runtime-rpc-fixtures' import { toSshExecutionHostId } from '../../shared/execution-host' const UPPER = String.raw`\\wsl.localhost\Ubuntu\home\Alice\App` diff --git a/src/cli/workspaces/workspace-address.ts b/src/cli/workspaces/workspace-address.ts index f97c0f74c68..d79092699fc 100644 --- a/src/cli/workspaces/workspace-address.ts +++ b/src/cli/workspaces/workspace-address.ts @@ -4,7 +4,7 @@ import { parseWorkspaceKey } from '../../shared/workspace-scope' import type { CrossStoreParentRef } from '../../shared/worktree/lineage-types' import { LOCAL_ENVIRONMENT } from '../hosts/local-environment-selector' import type { RuntimeClient } from '../runtime/client' -import { quoteCliCommandArgument } from '../shell-command-quote' +import { quoteCliCommandArgument } from '../arguments/shell-command-quote' /** Which Orca answered: `local`, a saved environment, or a one-off pairing-code connection (id null). */ export type WorkspaceEnvironment = { id: string | null; name: string | null } diff --git a/src/cli/workspaces/worktree-activate.ts b/src/cli/workspaces/worktree-activate.ts index 42b414b151c..aedea03abaa 100644 --- a/src/cli/workspaces/worktree-activate.ts +++ b/src/cli/workspaces/worktree-activate.ts @@ -1,5 +1,5 @@ -import type { CommandHandler } from '../dispatch' -import { printResult } from '../command-result-output' +import type { CommandHandler } from '../dispatch/dispatch' +import { printResult } from '../output/command-result-output' import { getRequiredWorktreeSelector } from '../workspace-selection/workspace-selector' import { folderIdOfSelector } from '../../shared/workspace-scope' import { refuseFolderWorkspaceActivation } from './folder-workspace-mutations' diff --git a/src/cli/workspaces/worktree-create-agent-launch.ts b/src/cli/workspaces/worktree-create-agent-launch.ts index ceedefca77d..60012f9e448 100644 --- a/src/cli/workspaces/worktree-create-agent-launch.ts +++ b/src/cli/workspaces/worktree-create-agent-launch.ts @@ -22,7 +22,7 @@ import { SURFACE_UNSUPPORTED_MESSAGE } from '../agents/agent-launch-request' import { formatWorktreeShow } from './workspace-format' -import { printResult } from '../command-result-output' +import { printResult } from '../output/command-result-output' import { RuntimeClientError } from '../runtime/types' import type { RuntimeClient } from '../runtime/client' import { printLineageSummary } from './worktree-lineage-summary' diff --git a/src/cli/workspaces/worktree-create-parent-selector.ts b/src/cli/workspaces/worktree-create-parent-selector.ts index b171c6f2597..6315c492756 100644 --- a/src/cli/workspaces/worktree-create-parent-selector.ts +++ b/src/cli/workspaces/worktree-create-parent-selector.ts @@ -1,5 +1,5 @@ import { isWorkspaceKey, worktreeWorkspaceKey } from '../../shared/workspace-scope' -import { getOptionalStringFlag } from '../flags' +import { getOptionalStringFlag } from '../arguments/flags' import { RuntimeClientError } from '../runtime/types' import type { RuntimeClient } from '../runtime/client' import { getOptionalParentSelector } from '../workspace-selection/caller-folder-workspace' diff --git a/src/cli/workspaces/worktree-handler-groups.ts b/src/cli/workspaces/worktree-handler-groups.ts index d9a699e4dee..b45f5ded6e3 100644 --- a/src/cli/workspaces/worktree-handler-groups.ts +++ b/src/cli/workspaces/worktree-handler-groups.ts @@ -1,4 +1,4 @@ -import type { HandlerGroup } from '../handler-group-manifest' +import type { HandlerGroup } from '../dispatch/handler-group-manifest' export const WORKTREE_HANDLER_GROUPS: readonly HandlerGroup[] = [ { diff --git a/src/cli/workspaces/worktree-parent-environment.ts b/src/cli/workspaces/worktree-parent-environment.ts index 8c10ad71d1d..e526653b3cf 100644 --- a/src/cli/workspaces/worktree-parent-environment.ts +++ b/src/cli/workspaces/worktree-parent-environment.ts @@ -9,13 +9,13 @@ import { WORKTREE_CROSS_STORE_LINEAGE_RUNTIME_CAPABILITY } from '../../shared/worktree-runtime-capabilities' import { getOptionalParentSelector } from '../workspace-selection/caller-folder-workspace' -import { getOptionalStringFlag } from '../flags' +import { getOptionalStringFlag } from '../arguments/flags' import { mayNameFolderWorkspace } from '../workspace-selection/folder-workspace-selector' import { isLocalEnvironmentSelector, LOCAL_ENVIRONMENT } from '../hosts/local-environment-selector' import { RuntimeClient } from '../runtime/client' import { RuntimeClientError } from '../runtime/types' import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope' -import { quoteCliCommandArgument } from '../shell-command-quote' +import { quoteCliCommandArgument } from '../arguments/shell-command-quote' import { describeClientEnvironment, environmentLabel } from './workspace-address' import { attachCliErrorData } from './worktree-setup-decision-recovery' diff --git a/src/cli/workspaces/worktree-parent-fields.ts b/src/cli/workspaces/worktree-parent-fields.ts index 94cf3f39aa3..383df34dd04 100644 --- a/src/cli/workspaces/worktree-parent-fields.ts +++ b/src/cli/workspaces/worktree-parent-fields.ts @@ -8,7 +8,7 @@ import { assertFolderParentSetSupported, supportsCrossStoreLineage } from '../../shared/worktree-runtime-capabilities' -import { getOptionalStringFlag } from '../flags' +import { getOptionalStringFlag } from '../arguments/flags' import { RuntimeClient } from '../runtime/client' import { RuntimeClientError } from '../runtime/types' import { resolveWorktreeCreateCwdContext } from '../workspace-selection/workspace-selector' diff --git a/src/cli/workspaces/worktree-project-target.ts b/src/cli/workspaces/worktree-project-target.ts index c48e28bcc79..0b56fada624 100644 --- a/src/cli/workspaces/worktree-project-target.ts +++ b/src/cli/workspaces/worktree-project-target.ts @@ -4,7 +4,7 @@ import { hostFilterMatchesHostId, resolveHostFlagTarget } from '../hosts/executi import { findProjectSetups, setupHostId } from '../projects/project-selector' import type { RuntimeClient } from '../runtime/client' import { RuntimeClientError } from '../runtime/types' -import { getPresentStringFlag } from '../flags' +import { getPresentStringFlag } from '../arguments/flags' import { getFolderWorkspaceMissingRepoError } from '../workspace-selection/caller-folder-workspace' export type ProjectCreateTarget = { diff --git a/src/cli/workspaces/worktree-removal-current-refusal.ts b/src/cli/workspaces/worktree-removal-current-refusal.ts index a1ecc882d78..b3a0d091767 100644 --- a/src/cli/workspaces/worktree-removal-current-refusal.ts +++ b/src/cli/workspaces/worktree-removal-current-refusal.ts @@ -1,9 +1,9 @@ -import { getOptionalStringFlag } from '../flags' +import { getOptionalStringFlag } from '../arguments/flags' import { assertLocalCwdWorktreeSelector } from '../hosts/local-environment-selector' import { RuntimeClientError } from '../runtime/types' import type { RuntimeClient } from '../runtime/client' import { resolveCurrentWorktreeSelector } from '../workspace-selection/workspace-selector' -import { quoteCliCommandArgument } from '../shell-command-quote' +import { quoteCliCommandArgument } from '../arguments/shell-command-quote' /** What current/active names right now: one selector, the ambiguous choices, or nothing. */ async function describeCurrent( diff --git a/src/cli/workspaces/worktree-review-link-flags.ts b/src/cli/workspaces/worktree-review-link-flags.ts index 8f3da03a244..251fcd1b49e 100644 --- a/src/cli/workspaces/worktree-review-link-flags.ts +++ b/src/cli/workspaces/worktree-review-link-flags.ts @@ -1,4 +1,4 @@ -import { getOptionalNullableNumberFlag, getOptionalNumberFlag } from '../flags' +import { getOptionalNullableNumberFlag, getOptionalNumberFlag } from '../arguments/flags' import { RuntimeClientError } from '../runtime/types' import { getOptionalWorktreeLinkFlagValue } from './worktree-link-flag-value' import { getOptionalGitLabLinkFlag } from './worktree-gitlab-link' diff --git a/src/cli/workspaces/worktree-setup-decision-recovery.ts b/src/cli/workspaces/worktree-setup-decision-recovery.ts index 924f48d5e67..f7ff1b55d33 100644 --- a/src/cli/workspaces/worktree-setup-decision-recovery.ts +++ b/src/cli/workspaces/worktree-setup-decision-recovery.ts @@ -1,4 +1,4 @@ -import { getPresentStringFlag } from '../flags' +import { getPresentStringFlag } from '../arguments/flags' import { RuntimeClientError, RuntimeRpcFailureError } from '../runtime/types' // Hosts use generic runtime_error here; this message is the stable discriminator. diff --git a/src/cli/workspaces/worktree.ts b/src/cli/workspaces/worktree.ts index 18947b019b6..921552567ab 100644 --- a/src/cli/workspaces/worktree.ts +++ b/src/cli/workspaces/worktree.ts @@ -7,12 +7,12 @@ import type { RuntimeWorktreeSetResult, RuntimeWorktreeCreateResult } from '../../shared/runtime-worktree-contracts' -import type { CommandHandler } from '../dispatch' +import type { CommandHandler } from '../dispatch/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 } from './workspace-format' -import { printResult } from '../command-result-output' +import { printResult } from '../output/command-result-output' import { annotateOmittedHostScope, type WithAnnotatedHostScope @@ -24,7 +24,7 @@ import { getOptionalStringFlagAllowingEmpty, getPresentStringFlag, getRequiredStringFlag -} from '../flags' +} from '../arguments/flags' import { getRequiredWorktreeSelector, resolveWorktreeCreateCwdContext, @@ -62,7 +62,7 @@ import { assertReferenceWritesSupported, getCreateReferenceInputs, resolveReferenceInputs -} from '../reference-input' +} from '../references/reference-input' function getOptionalStartupAgent(flags: Map): TuiAgent | undefined { const agent = getPresentStringFlag(flags, 'agent') diff --git a/src/main/runtime/rpc/methods/agent-launch/agent-launch-cwd-cli.test-fixture.ts b/src/main/runtime/rpc/methods/agent-launch/agent-launch-cwd-cli.test-fixture.ts index cc642b119ee..391c0662043 100644 --- a/src/main/runtime/rpc/methods/agent-launch/agent-launch-cwd-cli.test-fixture.ts +++ b/src/main/runtime/rpc/methods/agent-launch/agent-launch-cwd-cli.test-fixture.ts @@ -66,7 +66,7 @@ const cliPath = '../../../../../cli/index' await import(cliPath) const harnessPath = '../../../../../cli/index-test-harness' await import(harnessPath) -const fixturesPath = '../../../../../cli/test-fixtures' +const fixturesPath = '../../../../../cli/runtime/fixtures/runtime-rpc-fixtures' await import(fixturesPath) const agentFixturesPath = '../../../../../cli/agent-launch-test-fixtures' await import(agentFixturesPath) 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 13af55d4888..e0a58382ac5 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,8 +26,7 @@ describe('orchestration CLI/runtime boundary', () => { afterEach(() => { h.cleanup() restoreTerminalHandle() - vi.doUnmock('../../../../../cli/command-result-output') - vi.doUnmock('../../../../../cli/runtime-client') + vi.doUnmock('../../../../../cli/output/command-result-output') vi.unstubAllEnvs() vi.restoreAllMocks() vi.resetModules() @@ -104,8 +103,8 @@ 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/command-result-output', () => ({ printResult: vi.fn() })) - const cliModulePath = '../../../../../cli/handlers/orchestration' + vi.doMock('../../../../../cli/output/command-result-output', () => ({ printResult: vi.fn() })) + const cliModulePath = '../../../../../cli/orchestration/orchestration-handlers' 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 23782ef3aba..90a3065ae95 100644 --- a/tests/e2e/agent-launch-cli.unit.test.ts +++ b/tests/e2e/agent-launch-cli.unit.test.ts @@ -6,9 +6,10 @@ import { AGENT_LAUNCH_RUNTIME_CAPABILITIES } from '../../src/shared/agent-launch import type { StructuredAgentSessionFirstMessage } from '../../src/shared/agent-session/structured-agent-session-create' 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 { RuntimeClient } from '../../src/cli/runtime/client' +import { RuntimeClientError } from '../../src/cli/runtime/types' import { callAgentLaunch, readCliAgentLaunch } from '../../src/cli/agents/agent-launch-request' -import { parseArgs } from '../../src/cli/args' +import { parseArgs } from '../../src/cli/arguments/args' import { AGENT_LAUNCH_HANDLERS } from '../../src/cli/agents/agent-launch' import { createWorktreeWithAgent } from '../../src/cli/workspaces/worktree-create-agent-launch' import { diff --git a/tests/e2e/cli-agent-unopened-workspace-resume.spec.ts b/tests/e2e/cli-agent-unopened-workspace-resume.spec.ts index de15a6b44c2..09e26642d14 100644 --- a/tests/e2e/cli-agent-unopened-workspace-resume.spec.ts +++ b/tests/e2e/cli-agent-unopened-workspace-resume.spec.ts @@ -1,7 +1,7 @@ // Persist a CLI-started agent the window never opened, then cold-resume it after relaunch with the daemon gone. import { chmodSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import path from 'node:path' -import { RuntimeClient } from '../../src/cli/runtime-client' +import { RuntimeClient } from '../../src/cli/runtime/client' import { makePaneKey } from '../../src/shared/workspace-layout/stable-pane-id' import { PROTOCOL_VERSION } from '../../src/main/daemon/protocol/daemon-protocol-version' import { expect, test } from './helpers/orca-app' diff --git a/tests/e2e/completed-worker-retirement-resume.spec.ts b/tests/e2e/completed-worker-retirement-resume.spec.ts index ff055c2cd24..d5536cb0584 100644 --- a/tests/e2e/completed-worker-retirement-resume.spec.ts +++ b/tests/e2e/completed-worker-retirement-resume.spec.ts @@ -19,7 +19,7 @@ import { seedCurrentCodexTranscript, terminalIdentity } from './helpers/completed-worker-retirement-fixture' -import { RuntimeClient } from '../../src/cli/runtime-client' +import { RuntimeClient } from '../../src/cli/runtime/client' import type { RuntimeTerminalRead, RuntimeTerminalSummary } from '../../src/shared/runtime-types' import { splitWorktreeIdForFilesystem } from '../../src/shared/worktree/id' diff --git a/tests/e2e/helpers/completed-worker-retirement-fixture.ts b/tests/e2e/helpers/completed-worker-retirement-fixture.ts index 0ee9bde18fc..887c8a5fea5 100644 --- a/tests/e2e/helpers/completed-worker-retirement-fixture.ts +++ b/tests/e2e/helpers/completed-worker-retirement-fixture.ts @@ -11,7 +11,7 @@ import { } from 'node:fs' import os from 'node:os' import path from 'node:path' -import type { RuntimeClient } from '../../../src/cli/runtime-client' +import type { RuntimeClient } from '../../../src/cli/runtime/client' import type { RuntimeTerminalListResult, RuntimeTerminalSummary diff --git a/tests/e2e/linear-cli-recovery.unit.test.ts b/tests/e2e/linear-cli-recovery.unit.test.ts index 6afc4dd9881..afb1497f2b3 100644 --- a/tests/e2e/linear-cli-recovery.unit.test.ts +++ b/tests/e2e/linear-cli-recovery.unit.test.ts @@ -34,10 +34,20 @@ const boundary = vi.hoisted(() => ({ email: 'proof@example.invalid' } })) -vi.mock('../../src/cli/runtime-client', async () => { +vi.mock('../../src/cli/runtime/client', async () => { const { createRuntimeClientModuleMock } = await import('../../src/cli/index-test-harness.js') return createRuntimeClientModuleMock(boundary) }) + +vi.mock('../../src/cli/runtime/launch', async (importOriginal) => ({ + ...(await importOriginal>()), + serveOrcaApp: boundary.serveOrcaAppMock +})) + +vi.mock('../../src/cli/runtime/metadata', async (importOriginal) => ({ + ...(await importOriginal>()), + getDefaultUserDataPath: boundary.getDefaultUserDataPathMock +})) vi.mock('../../src/main/linear/accounts/linear-token-store', () => ({ loadToken: () => 'local-proof-token', saveWorkspaceToken: boundary.save, diff --git a/tests/e2e/linear-write-lifetime.unit.test.ts b/tests/e2e/linear-write-lifetime.unit.test.ts index a1ee8915312..97bb6297297 100644 --- a/tests/e2e/linear-write-lifetime.unit.test.ts +++ b/tests/e2e/linear-write-lifetime.unit.test.ts @@ -4,7 +4,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { clearTimeout as clearRealTimeout, setTimeout as setRealTimeout } from 'node:timers' import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { RuntimeClient } from '../../src/cli/runtime-client' +import { RuntimeClient } from '../../src/cli/runtime/client' import * as mutations from '../../src/main/linear/issues/linear-issue-mutations' import * as comments from '../../src/main/linear/issues/linear-issue-comments' import * as relations from '../../src/main/linear/issues/issue-relation-write' diff --git a/tests/e2e/live-background-terminal-mount-authority.spec.ts b/tests/e2e/live-background-terminal-mount-authority.spec.ts index 9318b3b76a8..a87c457a0b7 100644 --- a/tests/e2e/live-background-terminal-mount-authority.spec.ts +++ b/tests/e2e/live-background-terminal-mount-authority.spec.ts @@ -13,7 +13,7 @@ import { installTerminalPtyWriteSpy, readTerminalPtyWriteEntries } from './helpers/terminal-pty-write-spy' -import { RuntimeClient } from '../../src/cli/runtime-client' +import { RuntimeClient } from '../../src/cli/runtime/client' import type { RuntimeStatus, RuntimeTerminalCreate, diff --git a/tests/e2e/local-cli-terminal-retention.spec.ts b/tests/e2e/local-cli-terminal-retention.spec.ts index 715c09a14ac..d964783695f 100644 --- a/tests/e2e/local-cli-terminal-retention.spec.ts +++ b/tests/e2e/local-cli-terminal-retention.spec.ts @@ -5,7 +5,7 @@ import { randomUUID } from 'node:crypto' import { existsSync, readFileSync, rmSync } from 'node:fs' import path from 'node:path' import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { RuntimeClient } from '../../src/cli/runtime-client' +import { RuntimeClient } from '../../src/cli/runtime/client' import { makePaneKey } from '../../src/shared/workspace-layout/stable-pane-id' import { expect, test } from './helpers/orca-app' import { TEST_REPO_PATH_FILE } from './global-setup' diff --git a/tests/e2e/local-worktree-visibility-runtime-active.spec.ts b/tests/e2e/local-worktree-visibility-runtime-active.spec.ts index bd0dc0262a6..9e6f07d5642 100644 --- a/tests/e2e/local-worktree-visibility-runtime-active.spec.ts +++ b/tests/e2e/local-worktree-visibility-runtime-active.spec.ts @@ -3,7 +3,7 @@ import { test, expect } from './helpers/orca-app' import { waitForSessionReady, waitForActiveWorktree } from './helpers/store' -import { RuntimeClient } from '../../src/cli/runtime-client' +import { RuntimeClient } from '../../src/cli/runtime/client' test.describe('worktree visibility with a remote runtime active', () => { test('a CLI-created worktree appears in the sidebar while a remote runtime is active', async ({ diff --git a/tests/e2e/orchestration-follows-terminal-across-remount.spec.ts b/tests/e2e/orchestration-follows-terminal-across-remount.spec.ts index d2790840503..4d97cd312d2 100644 --- a/tests/e2e/orchestration-follows-terminal-across-remount.spec.ts +++ b/tests/e2e/orchestration-follows-terminal-across-remount.spec.ts @@ -8,7 +8,7 @@ import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { RuntimeClient } from '../../src/cli/runtime-client' +import { RuntimeClient } from '../../src/cli/runtime/client' import type { RuntimeTerminalCreate, RuntimeTerminalListResult, diff --git a/tests/e2e/orchestration-idle-mail-delivery.spec.ts b/tests/e2e/orchestration-idle-mail-delivery.spec.ts index 9f76d5a13ee..72c8cb2bc30 100644 --- a/tests/e2e/orchestration-idle-mail-delivery.spec.ts +++ b/tests/e2e/orchestration-idle-mail-delivery.spec.ts @@ -17,7 +17,8 @@ import { waitForActiveTerminalManager, waitForPaneIdentitySnapshot } from './helpers/terminal' -import { RuntimeClient, type RuntimeRpcSuccess } from '../../src/cli/runtime-client' +import { RuntimeClient } from '../../src/cli/runtime/client' +import type { RuntimeRpcSuccess } from '../../src/shared/runtime-rpc-envelope' import type { RuntimeTerminalListResult } from '../../src/shared/runtime-types' import { CODEX_IDLE_TITLE, @@ -298,34 +299,6 @@ test.describe('orchestration push-on-idle mail delivery', () => { await expectSubmitted(pane) }) - // #19542: keep direct mail durable under the unbound Run without injecting an unsafe check pointer. - test('keeps unbound direct mail durable without pointing to an unsafe check', async ({ - orcaPage, - electronApp - }) => { - test.setTimeout(180_000) - const { client, userDataDir, openAgentPane } = await setUpMailFixture(orcaPage, electronApp) - const pane = await openAgentPane() - await driveToLiveIdle(client, pane) - - // Unbound terminals still need durable direct mail; reopen must not classify it as pre-Runs state. - const stdinBeforeScan = pane.agent.readStdin() - const messageId = await sendMail(client, pane.handle, { subject: 'Unbound direct mail' }) - pane.agent.setTitle(CODEX_WORKING_TITLE) - await waitForObservedTitle(client, pane.handle, CODEX_WORKING_TITLE) - pane.agent.setTitle(CODEX_IDLE_TITLE) - await waitForObservedTitle(client, pane.handle, CODEX_IDLE_TITLE) - - await orcaPage.waitForTimeout(NO_DELIVERY_SETTLE_MS) - expect(readMailRow(userDataDir, messageId)).toMatchObject({ - to_handle: pane.handle, - run_id: 'run_unbound', - read: 0, - delivered_at: null - }) - expect(pane.agent.readStdin()).toBe(stdinBeforeScan) - }) - test('leaves the mail to a live waiter instead of pushing it into the pane', async ({ orcaPage, electronApp diff --git a/tests/e2e/orchestration-idle-mail-restore.spec.ts b/tests/e2e/orchestration-idle-mail-restore.spec.ts index 18d9e4e0793..5baf875db75 100644 --- a/tests/e2e/orchestration-idle-mail-restore.spec.ts +++ b/tests/e2e/orchestration-idle-mail-restore.spec.ts @@ -11,7 +11,7 @@ import { waitForActivePaneHookDescriptor, waitForActivePanePtyId } from './helpers/terminal' -import { RuntimeClient } from '../../src/cli/runtime-client' +import { RuntimeClient } from '../../src/cli/runtime/client' import type { RuntimeTerminalListResult } from '../../src/shared/runtime-types' import { CODEX_IDLE_TITLE, diff --git a/tests/e2e/orchestration-legacy-worker-missing-terminal-recovery.spec.ts b/tests/e2e/orchestration-legacy-worker-missing-terminal-recovery.spec.ts index cdbb8a3857f..eb947761af7 100644 --- a/tests/e2e/orchestration-legacy-worker-missing-terminal-recovery.spec.ts +++ b/tests/e2e/orchestration-legacy-worker-missing-terminal-recovery.spec.ts @@ -13,7 +13,7 @@ import { waitForSessionReady } from './helpers/store' import { waitForActivePaneHookDescriptor, waitForActivePanePtyId } from './helpers/terminal' -import { RuntimeClient } from '../../src/cli/runtime-client' +import { RuntimeClient } from '../../src/cli/runtime/client' import { DaemonClient } from '../../src/main/daemon/transport/client/daemon-client' import { getDaemonSocketPath, diff --git a/tests/e2e/orchestration-low-level-dispatch-release.spec.ts b/tests/e2e/orchestration-low-level-dispatch-release.spec.ts index 6ffa4b57dc4..c3d5d6481c4 100644 --- a/tests/e2e/orchestration-low-level-dispatch-release.spec.ts +++ b/tests/e2e/orchestration-low-level-dispatch-release.spec.ts @@ -1,5 +1,5 @@ import { test, expect } from './helpers/orca-app' -import { RuntimeClient } from '../../src/cli/runtime-client' +import { RuntimeClient } from '../../src/cli/runtime/client' import type { RuntimeTerminalListResult } from '../../src/shared/runtime-types' import { waitForSessionReady, ensureTerminalVisible } from './helpers/store' import { diff --git a/tests/e2e/orchestration-worker-settlement-release-cli.spec.ts b/tests/e2e/orchestration-worker-settlement-release-cli.spec.ts index 40b18a16030..210d298e6b6 100644 --- a/tests/e2e/orchestration-worker-settlement-release-cli.spec.ts +++ b/tests/e2e/orchestration-worker-settlement-release-cli.spec.ts @@ -5,7 +5,7 @@ import path from 'node:path' import { test as base, expect } from './helpers/orca-app' import { waitForActivePaneHookDescriptor, waitForActivePanePtyId } from './helpers/terminal' import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { RuntimeClient } from '../../src/cli/runtime-client' +import { RuntimeClient } from '../../src/cli/runtime/client' import Database from '../../src/main/sqlite/sync-database' import type { RuntimeTerminalListResult, RuntimeTerminalRead } from '../../src/shared/runtime-types' import { diff --git a/tests/e2e/orchestration-worker-terminal-visibility.spec.ts b/tests/e2e/orchestration-worker-terminal-visibility.spec.ts index 3bdd709e72c..fe2f47a8ed6 100644 --- a/tests/e2e/orchestration-worker-terminal-visibility.spec.ts +++ b/tests/e2e/orchestration-worker-terminal-visibility.spec.ts @@ -15,7 +15,7 @@ import { waitForSessionReady } from './helpers/store' import { waitForActivePaneHookDescriptor, waitForActivePanePtyId } from './helpers/terminal' -import { RuntimeClient } from '../../src/cli/runtime-client' +import { RuntimeClient } from '../../src/cli/runtime/client' import type { RuntimeTerminalListResult, RuntimeTerminalRead } from '../../src/shared/runtime-types' import { FAKE_CODEX_LAUNCH_PROBES_SOURCE } from './helpers/fake-codex-launch-probes' diff --git a/tests/e2e/orchestration-worker-transcript-providers.spec.ts b/tests/e2e/orchestration-worker-transcript-providers.spec.ts index c9d75f2f56a..8f2242df986 100644 --- a/tests/e2e/orchestration-worker-transcript-providers.spec.ts +++ b/tests/e2e/orchestration-worker-transcript-providers.spec.ts @@ -13,7 +13,7 @@ import path from 'node:path' import { test as base, expect } from './helpers/orca-app' import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' import { waitForActivePaneHookDescriptor, waitForActivePanePtyId } from './helpers/terminal' -import { RuntimeClient } from '../../src/cli/runtime-client' +import { RuntimeClient } from '../../src/cli/runtime/client' import type { RuntimeTerminalListResult, RuntimeTerminalSummary diff --git a/tests/e2e/renderer-blocked-navigation-graph-authority.spec.ts b/tests/e2e/renderer-blocked-navigation-graph-authority.spec.ts index 04f76dee1e8..f3cb761e3f2 100644 --- a/tests/e2e/renderer-blocked-navigation-graph-authority.spec.ts +++ b/tests/e2e/renderer-blocked-navigation-graph-authority.spec.ts @@ -1,5 +1,5 @@ import { test, expect } from './helpers/orca-app' -import { RuntimeClient } from '../../src/cli/runtime-client' +import { RuntimeClient } from '../../src/cli/runtime/client' import type { RuntimeStatus } from '../../src/shared/runtime-types' import { waitForSessionReady } from './helpers/store' diff --git a/tests/e2e/restart-unopened-workspace-terminal-attach.spec.ts b/tests/e2e/restart-unopened-workspace-terminal-attach.spec.ts index f90128da584..bf3d224fef2 100644 --- a/tests/e2e/restart-unopened-workspace-terminal-attach.spec.ts +++ b/tests/e2e/restart-unopened-workspace-terminal-attach.spec.ts @@ -1,7 +1,7 @@ // A terminal that survives a quit in a workspace the window never opened must stream to main after relaunch. import { readFileSync, rmSync, writeFileSync } from 'node:fs' import path from 'node:path' -import { RuntimeClient } from '../../src/cli/runtime-client' +import { RuntimeClient } from '../../src/cli/runtime/client' import type { RuntimeTerminalSummary } from '../../src/shared/runtime-types' import { expect, test } from './helpers/orca-app' import { TEST_REPO_PATH_FILE } from './global-setup' diff --git a/tests/e2e/settled-worker-tab-survives-restart.spec.ts b/tests/e2e/settled-worker-tab-survives-restart.spec.ts index 536c3d9e216..808edd027b7 100644 --- a/tests/e2e/settled-worker-tab-survives-restart.spec.ts +++ b/tests/e2e/settled-worker-tab-survives-restart.spec.ts @@ -27,7 +27,7 @@ import { readCompletedWorkerLedger, seedCurrentCodexTranscript } from './helpers/completed-worker-retirement-fixture' -import { RuntimeClient } from '../../src/cli/runtime-client' +import { RuntimeClient } from '../../src/cli/runtime/client' import type { RuntimeTerminalSummary } from '../../src/shared/runtime-types' import { splitWorktreeIdForFilesystem } from '../../src/shared/worktree/id' diff --git a/tests/e2e/unopened-workspace-agent-single-resume.spec.ts b/tests/e2e/unopened-workspace-agent-single-resume.spec.ts index 96460093809..ada716a6966 100644 --- a/tests/e2e/unopened-workspace-agent-single-resume.spec.ts +++ b/tests/e2e/unopened-workspace-agent-single-resume.spec.ts @@ -2,7 +2,7 @@ // Reject a second fresh-tab resume that would put two agents on one transcript. import { chmodSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import path from 'node:path' -import { RuntimeClient } from '../../src/cli/runtime-client' +import { RuntimeClient } from '../../src/cli/runtime/client' import { makePaneKey } from '../../src/shared/workspace-layout/stable-pane-id' import { PROTOCOL_VERSION } from '../../src/main/daemon/protocol/daemon-protocol-version' import { expect, test } from './helpers/orca-app' diff --git a/tests/e2e/worktree-status-warning.unit.test.ts b/tests/e2e/worktree-status-warning.unit.test.ts index e1a24048ae8..b77779b4816 100644 --- a/tests/e2e/worktree-status-warning.unit.test.ts +++ b/tests/e2e/worktree-status-warning.unit.test.ts @@ -1,7 +1,8 @@ import type * as childProcess from 'node:child_process' import { describe, expect, it, vi } from 'vitest' -import type { OrcaRuntimeService } from '../../src/main/runtime/orca-runtime' + import { RpcDispatcher } from '../../src/main/runtime/rpc/dispatcher' +import type { OrcaRuntimeService } from '../../src/main/runtime/orca-runtime' import { WORKTREE_METHODS } from '../../src/main/runtime/rpc/methods/workspaces/worktree' import type { WorkspaceStatusDefinition } from '../../src/shared/worktree/types' import { DEFAULT_WORKSPACE_STATUSES, getWorkspaceStatus } from '../../src/shared/workspace-statuses' @@ -16,10 +17,20 @@ const mocks = vi.hoisted(() => ({ spawnMock: vi.fn() })) -vi.mock('../../src/cli/runtime-client', async () => { +vi.mock('../../src/cli/runtime/client', async () => { const { createRuntimeClientModuleMock } = await import('../../src/cli/index-test-harness.js') return createRuntimeClientModuleMock(mocks) }) + +vi.mock('../../src/cli/runtime/launch', async (importOriginal) => ({ + ...(await importOriginal>()), + serveOrcaApp: mocks.serveOrcaAppMock +})) + +vi.mock('../../src/cli/runtime/metadata', async (importOriginal) => ({ + ...(await importOriginal>()), + getDefaultUserDataPath: mocks.getDefaultUserDataPathMock +})) vi.mock('../../src/cli/runtime/environments', () => ({ addEnvironmentFromPairingCode: mocks.addEnvironmentFromPairingCodeMock, removeEnvironment: vi.fn(), @@ -36,7 +47,7 @@ vi.mock('child_process', async (importOriginal) => { }) import { main } from '../../src/cli/index' -import { buildWorktree } from '../../src/cli/test-fixtures' +import { buildWorktree } from '../../src/cli/runtime/fixtures/runtime-rpc-fixtures' import { useWorktreeAwarenessEnvironment } from '../../src/cli/index-test-harness' const CUSTOM_STATUSES: WorkspaceStatusDefinition[] = [ @@ -153,26 +164,4 @@ describe('workspace status warnings through CLI and owning RPC handler', () => { expect(mocks.callMock).toHaveBeenCalledTimes(1) } ) - - it.each(['completed', 'shipped'])('accepts valid column %s without warnings', async (status) => { - const { stored, log, error } = fixture({ - statuses: status === 'shipped' ? CUSTOM_STATUSES : undefined - }) - await setStatus(status, true) - expect(stored.workspaceStatus).toBe(status) - const response = JSON.parse(log.mock.calls.flat().join('\n')) - expect(response).toMatchObject({ ok: true, result: { worktree: { workspaceStatus: status } } }) - expect(response.result).not.toHaveProperty('warnings') - expect(error).not.toHaveBeenCalled() - }) - - it('preserves the completed write when owner settings cannot be read', async () => { - const { stored, log, error } = fixture({ failRead: true }) - await setStatus('done', true) - expect(stored.workspaceStatus).toBe('done') - const response = JSON.parse(log.mock.calls.flat().join('\n')) - expect(response).toMatchObject({ ok: true }) - expect(response.result).not.toHaveProperty('warnings') - expect(error).not.toHaveBeenCalled() - }) })