diff --git a/.github/workflows/git-command-termination-runtime.yml b/.github/workflows/git-command-termination-runtime.yml index 60f82987909..9e5adf69606 100644 --- a/.github/workflows/git-command-termination-runtime.yml +++ b/.github/workflows/git-command-termination-runtime.yml @@ -3,7 +3,7 @@ on: pull_request: types: [opened, synchronize, reopened, ready_for_review, converted_to_draft] paths: - - 'src/main/git/command-runner/spawned-command-tree-kill*' + - 'src/main/git/command-runner/process-capture/spawned-command-tree-kill*' - '.github/workflows/git-command-termination-runtime.yml' workflow_dispatch: permissions: @@ -24,4 +24,4 @@ jobs: persist-credentials: false - uses: ./.github/actions/install-node-dependencies - name: Verify exited native child does not trigger taskkill - run: node node_modules/vitest/vitest.mjs run --config config/vitest.config.ts src/main/git/command-runner/spawned-command-tree-kill.test.ts + run: node node_modules/vitest/vitest.mjs run --config config/vitest.config.ts src/main/git/command-runner/process-capture/spawned-command-tree-kill.test.ts diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index be8bdf2f09a..8af730de1ae 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -8,7 +8,7 @@ 1 test-no-in-test-import-actual:src/main/claude/claude-agent-sdk-process-spawn.test.ts 5 test-no-in-test-import-actual:src/main/daemon/endpoint/publication/testing/daemon-endpoint-publish.test.ts 1 test-no-in-test-import-actual:src/main/daemon/history/storage/testing/terminal-history-permissions.test.ts -1 test-no-in-test-import-actual:src/main/git/command-runner/spawned-command-tree-kill.test.ts +1 test-no-in-test-import-actual:src/main/git/command-runner/process-capture/spawned-command-tree-kill.test.ts 1 test-no-in-test-import-actual:src/main/ipc/filesystem/filesystem-content-search-cancellation.test.ts 1 test-no-in-test-import-actual:src/main/linear/accounts/linear-account-client.test.ts 1 test-no-in-test-import-actual:src/main/linear/issues/linear-description-images.test.ts @@ -468,7 +468,7 @@ 2 test-no-wall-clock:src/main/daemon/transport/framing/testing/daemon-stream-binary-negotiation.test.ts 2 test-no-wall-clock:src/main/external-conversations/external-conversation-cancel-settlement.test.ts 3 test-no-wall-clock:src/main/external-conversations/external-conversation-cancel.test.ts -2 test-no-wall-clock:src/main/git/command-runner/git-command-resolution-windows-checkout.test.ts +2 test-no-wall-clock:src/main/git/command-runner/host-routing/git-command-resolution-windows-checkout.test.ts 1 test-no-wall-clock:src/main/git/gh-rate-limit-breaker.test.ts 1 test-no-wall-clock:src/main/git/refs/maintenance/pack-refs-lock-ownership.test.ts 2 test-no-wall-clock:src/main/git/refs/maintenance/repo-ref-maintenance-real-git.test.ts @@ -797,7 +797,6 @@ 1 test-timeout-needs-reason:tests/e2e/paired-desktop-server-layout-frames.spec.ts 1 test-timeout-needs-reason:tests/e2e/paired-desktop-server-layout-intents.spec.ts 1 test-timeout-needs-reason:tests/e2e/paired-desktop-server-layout-writes.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-external-worktree-discovery.spec.ts 2 test-timeout-needs-reason:tests/e2e/paired-host-usage-credentials.spec.ts 7 test-timeout-needs-reason:tests/e2e/paired-instant-browser-tab.spec.ts 1 test-timeout-needs-reason:tests/e2e/paired-mobile-desktop-mirror-files-git-review.spec.ts diff --git a/config/main-sync-spawn-baseline.txt b/config/main-sync-spawn-baseline.txt index 3b71fe0aa11..3835c905a0f 100644 --- a/config/main-sync-spawn-baseline.txt +++ b/config/main-sync-spawn-baseline.txt @@ -25,7 +25,6 @@ 3 src/main/filesystem/atomic-file-publication.ts 1 src/main/git/command-runner/git-exec-file-sync.ts 1 src/main/git/repo-detection-command.ts -1 src/main/git/runner.ts 1 src/main/ipc/worktree-logic.ts 1 src/main/network/macos-tailscale-dns-diagnostic.ts 1 src/main/opencode/status-hooks/legacy-plugin-acl-retry.ts diff --git a/config/process-host-direct-import-baseline.txt b/config/process-host-direct-import-baseline.txt index eaedb1195d7..5eb55e1acc4 100644 --- a/config/process-host-direct-import-baseline.txt +++ b/config/process-host-direct-import-baseline.txt @@ -28,13 +28,13 @@ src/main/emulator/serve-sim-runtime-materializer.ts src/main/emulator/simctl-simulator-devices.ts src/main/emulator/simulator-app-visibility.ts src/main/external-editors/external-editor-launch.ts -src/main/git/command-runner/exec-file-capture.ts +src/main/git/command-runner/process-capture/exec-file-capture.ts src/main/git/command-runner/git-exec-file-sync.ts src/main/git/command-runner/git-spawn.ts src/main/git/command-runner/git-stream-stdout.ts -src/main/git/command-runner/spawn-command-capture.ts -src/main/git/command-runner/spawned-command-tree-kill.ts -src/main/git/command-runner/wsl-aware-spawn.ts +src/main/git/command-runner/process-capture/spawn-command-capture.ts +src/main/git/command-runner/process-capture/spawned-command-tree-kill.ts +src/main/git/command-runner/host-routing/wsl-aware-spawn.ts src/main/git/wsl-git-read-environment.ts src/main/github/gh-utils.ts src/main/workspace-hooks/hooks.ts diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index a86257f8967..1737f7d93c3 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -3439,7 +3439,7 @@ "providers": ["local", "ssh"], "coveredPlatforms": ["macos"], "coveredProviders": [], - "coverageNotes": "Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. The whole main-window attach-services suite is removed: runtime/window attach, notifier wiring, reload/teardown and permission-handler mock orchestration alarms are intentionally lost. Prune its exact deleted command selectors, testFiles entries and notifier assertionRef where present; complete prior selectors/ref are archived. Unrelated dated receipts remain exact and retain their original scope; no fresh reduced-selector, native-window or remote execution is claimed. Module layout SSH policy: Retire reset/private-arithmetic generation rollover registrations. The two retained local-versus-SSH mutation refusals do not establish process-scope rollover or sibling-token invalidation; remove this unrelated gate selector and its rollover assertion claim. Unchanged unrelated execution receipts retain only their original scope. No replacement, fresh rollover execution or cross-platform proof is claimed. Historical prior account (preserved verbatim): Audit2003: Remove the standalone one-client shared-runtime/headless-publication example. The retained two-client callback (real WebSocket/runtime coordination with supplied Git listings and watcher notifications) and invalidated scan/reconnect races keep their exact owning scope, without replacement-equivalence or rendered-headless proof. Retire the entire dated38-case receipt through its effective currentCommand. Preserve the unrelated SSH bridge receipt and paired Electron receipt within their original commands. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1645 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1412 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Local deterministic evidence covers git-common classification, desktop watcher debounce counts, non-overlapping poller semantics, macOS native-watch fallback, paired-runtime publication to two independent clients with reconnect and stale-cache checks, and process generation-scope rollover across sibling targets. A headed macOS Electron host and separate paired Electron client both rendered a worktree created through the real Git binary and watcher entry path without reconnect. Linux/Windows desktop clients, multi-target live fanout, and WSL runs remain gaps. Audit1309: src/main/ipc/worktrees/creation/worktree-head-identity-reader.test.ts: Keep real filesystem HEAD/loose/packed/relative metadata reads and traversal refusal. Remove invalid-oid/nonstandard-layout characterization. Lose malformed object-id and bare-dir omission alarms; no Git-produced layout claim. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1381 removes the two mock-forwarding registrations in src/renderer/src/components/right-sidebar/source-control/sync/git-status-push-signal-refresh.test.ts. Sibling attribution suppression and missing/unknown attribution refresh callback alarms are intentionally lost; no equivalent replacement or real hook lifecycle/status-update coverage is claimed. Remaining exact receipts, platform/provider scope, and budgets remain limited to their unchanged selectors; no new execution result is claimed. Audit1412: src/main/ssh/ssh-provider-authority.test.ts removed. Loses real AbortController revocation/target isolation/reentrancy outcomes, recreated-target generation-floor/session rollover behavior, stale mutation refusal and settled-registration cleanup alarms. These useful alarms are deliberately lost; no equivalent cancellation coverage is claimed. No equivalent replacement coverage is claimed.", + "coverageNotes": "Command-runner layout policy retires the paired external-worktree E2E: rendered two-client discovery and transport-continuity coverage is lost, with no equivalent replacement. The archived dated receipt does not validate current source. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. The whole main-window attach-services suite is removed: runtime/window attach, notifier wiring, reload/teardown and permission-handler mock orchestration alarms are intentionally lost. Prune its exact deleted command selectors, testFiles entries and notifier assertionRef where present; complete prior selectors/ref are archived. Unrelated dated receipts remain exact and retain their original scope; no fresh reduced-selector, native-window or remote execution is claimed. Module layout SSH policy: Retire reset/private-arithmetic generation rollover registrations. The two retained local-versus-SSH mutation refusals do not establish process-scope rollover or sibling-token invalidation; remove this unrelated gate selector and its rollover assertion claim. Unchanged unrelated execution receipts retain only their original scope. No replacement, fresh rollover execution or cross-platform proof is claimed. Historical prior account (preserved verbatim): Audit2003: Remove the standalone one-client shared-runtime/headless-publication example. The retained two-client callback (real WebSocket/runtime coordination with supplied Git listings and watcher notifications) and invalidated scan/reconnect races keep their exact owning scope, without replacement-equivalence or rendered-headless proof. Retire the entire dated38-case receipt through its effective currentCommand. Preserve the unrelated SSH bridge receipt and paired Electron receipt within their original commands. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1645 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1412 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Local deterministic evidence covers git-common classification, desktop watcher debounce counts, non-overlapping poller semantics, macOS native-watch fallback, paired-runtime publication to two independent clients with reconnect and stale-cache checks, and process generation-scope rollover across sibling targets. A headed macOS Electron host and separate paired Electron client both rendered a worktree created through the real Git binary and watcher entry path without reconnect. Linux/Windows desktop clients, multi-target live fanout, and WSL runs remain gaps. Audit1309: src/main/ipc/worktrees/creation/worktree-head-identity-reader.test.ts: Keep real filesystem HEAD/loose/packed/relative metadata reads and traversal refusal. Remove invalid-oid/nonstandard-layout characterization. Lose malformed object-id and bare-dir omission alarms; no Git-produced layout claim. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1381 removes the two mock-forwarding registrations in src/renderer/src/components/right-sidebar/source-control/sync/git-status-push-signal-refresh.test.ts. Sibling attribution suppression and missing/unknown attribution refresh callback alarms are intentionally lost; no equivalent replacement or real hook lifecycle/status-update coverage is claimed. Remaining exact receipts, platform/provider scope, and budgets remain limited to their unchanged selectors; no new execution result is claimed. Audit1412: src/main/ssh/ssh-provider-authority.test.ts removed. Loses real AbortController revocation/target isolation/reentrancy outcomes, recreated-target generation-floor/session rollover behavior, stale mutation refusal and settled-registration cleanup alarms. These useful alarms are deliberately lost; no equivalent cancellation coverage is claimed. No equivalent replacement coverage is claimed.", "motivatingLinks": [ "https://github.com/stablyai/orca/pull/7086", "https://github.com/stablyai/orca/issues/16477" @@ -3449,14 +3449,12 @@ "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/worktrees/creation/worktree-base-directory-event-filter.test.ts src/main/ipc/worktrees/creation/worktree-head-identity-reader.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/workspaces/catalog/external-worktree-paired-client-discovery.integration.test.ts", - "ORCA_E2E_FORCE_HEADFUL=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-external-worktree-discovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/hooks/useIpcEvents-agent-status-ssh-authority.test.ts --reporter=dot" ], "testFiles": [ "src/main/ipc/worktrees/creation/worktree-base-directory-event-filter.test.ts", "src/main/ipc/worktrees/creation/worktree-head-identity-reader.test.ts", "src/main/runtime/workspaces/catalog/external-worktree-paired-client-discovery.integration.test.ts", - "tests/e2e/paired-external-worktree-discovery.spec.ts", "src/renderer/src/hooks/useIpcEvents-agent-status-ssh-authority.test.ts" ], "assertionRefs": [ @@ -3482,14 +3480,6 @@ "a disconnected client reconnects to current catalog state without replaying a stale invalidation", "an event-ignoring client remains compatible, and colliding local/SSH owners do not publish an owner-blind event" ] - }, - { - "file": "tests/e2e/paired-external-worktree-discovery.spec.ts", - "assertions": [ - "a real git worktree add advances the authoritative host inventory", - "the headed host and separate paired Electron client render the same new worktree identity", - "the paired client's main-process shared-control transport keeps one connection epoch while converging and compares Windows paths case-insensitively" - ] } ], "evidenceRuns": [ @@ -3501,15 +3491,6 @@ "result": "passed", "durationSeconds": 1.21, "summary": "The direct SSH state-bridge wiring file passed with 6 tests after the reconnect coordinator, scheduler and telemetry were deleted." - }, - { - "date": "2026-08-26", - "runner": "local", - "platform": "macos", - "command": "ORCA_E2E_FORCE_HEADFUL=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-external-worktree-discovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "result": "passed", - "durationSeconds": 17.96, - "summary": "One forced-visible paired Electron test passed: real Git inventory, matching visible host/client rows, and one unchanged main-process shared-control transport epoch during convergence." } ], "runtimeBudget": { @@ -3558,7 +3539,8 @@ "Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. The whole main-window attach-services suite is removed: runtime/window attach, notifier wiring, reload/teardown and permission-handler mock orchestration alarms are intentionally lost. Prune its exact deleted command selectors, testFiles entries and notifier assertionRef where present; complete prior selectors/ref are archived. Unrelated dated receipts remain exact and retain their original scope; no fresh reduced-selector, native-window or remote execution is claimed. All earlier notes and dated/archived evidence retain original scopes.", "Exact prior command before deleted attach-main-window-services selector removal: \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/workspaces/catalog/external-worktree-paired-client-discovery.integration.test.ts src/main/window/attach-main-window-services.test.ts\"", "Exact retired testFiles selector: \"src/main/window/attach-main-window-services.test.ts\"", - "Complete prior assertionRef retired as historical data only: {\n \"file\": \"src/main/window/attach-main-window-services.test.ts\",\n \"assertions\": [\n \"main-window wiring installs the runtime as the watched-worktree remote-client notifier alongside the existing repo notifier\"\n ]\n }" + "Complete prior assertionRef retired as historical data only: {\n \"file\": \"src/main/window/attach-main-window-services.test.ts\",\n \"assertions\": [\n \"main-window wiring installs the runtime as the watched-worktree remote-client notifier alongside the existing repo notifier\"\n ]\n }", + "Command-runner layout policy: historical paired external-worktree receipt, preserved verbatim; it no longer validates current source:\n{\n \"date\": \"2026-08-26\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"ORCA_E2E_FORCE_HEADFUL=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-external-worktree-discovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 17.96,\n \"summary\": \"One forced-visible paired Electron test passed: real Git inventory, matching visible host/client rows, and one unchanged main-process shared-control transport epoch during convergence.\"\n }" ], "demotionRule": "Keep experimental or demote if the focused gate flakes without a product or harness bug, if index-only churn can emit worktrees:changed, or if structural add/remove/HEAD/lock changes fail to converge." }, diff --git a/config/scripts/performance/wsl-git/wsl-git-shell-benchmark.mjs b/config/scripts/performance/wsl-git/wsl-git-shell-benchmark.mjs index 92dbfad149b..a2d652021ea 100644 --- a/config/scripts/performance/wsl-git/wsl-git-shell-benchmark.mjs +++ b/config/scripts/performance/wsl-git/wsl-git-shell-benchmark.mjs @@ -325,7 +325,7 @@ async function main() { '--untracked-files=all' ] const [{ gitExecFileAsync }, { getWslGitReadEnvironment }, expected] = await Promise.all([ - jiti.import('../../../../src/main/git/runner.ts'), + jiti.import('../../../../src/main/git/command-runner/git-exec-file.ts'), jiti.import('../../../../src/main/git/wsl-git-read-environment.ts'), runGit('fast', repo, args) ]) diff --git a/config/scripts/static-analysis/process-boundaries/check-main-sync-spawn-ratchet.mjs b/config/scripts/static-analysis/process-boundaries/check-main-sync-spawn-ratchet.mjs index 46960ad57e5..f6a4e6b05a1 100644 --- a/config/scripts/static-analysis/process-boundaries/check-main-sync-spawn-ratchet.mjs +++ b/config/scripts/static-analysis/process-boundaries/check-main-sync-spawn-ratchet.mjs @@ -34,8 +34,7 @@ const GATED_FAMILIES = [ { modules: [ 'src/main/git/command-runner/git-exec-file', - 'src/main/git/command-runner/git-exec-file-sync', - 'src/main/git/runner' + 'src/main/git/command-runner/git-exec-file-sync' ], advice: { gitExecFileSync: 'use gitExecFileAsync' } }, diff --git a/config/scripts/static-analysis/process-boundaries/check-main-sync-spawn-ratchet.test.mjs b/config/scripts/static-analysis/process-boundaries/check-main-sync-spawn-ratchet.test.mjs index 15c416efd14..429eefa9836 100644 --- a/config/scripts/static-analysis/process-boundaries/check-main-sync-spawn-ratchet.test.mjs +++ b/config/scripts/static-analysis/process-boundaries/check-main-sync-spawn-ratchet.test.mjs @@ -121,7 +121,7 @@ describe('main sync-spawn ratchet', () => { 'const other = { spawnSync() {} }\nother.spawnSync()', "// execFileSync('git')\nconst script = \"require('child_process').execSync('ls')\"", "import * as cp from 'child_process'\ncp.spawn('git')", - "import { gitExecFileAsync } from './git/runner'\ngitExecFileAsync(['status'])" + "import { gitExecFileAsync } from './git/command-runner/git-exec-file'\ngitExecFileAsync(['status'])" ])('ignores %s', (source) => { expect(uses(source)).toEqual({ count: 0, symbols: [] }) }) diff --git a/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs b/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs index e6e67ccb73b..5fb8153819f 100644 --- a/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs +++ b/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs @@ -93,7 +93,7 @@ const NODE_RUNTIME_INCLUDE = [ 'src/main/ipc/command-path/command-path-directory-worker.test.ts', // Asserts Node's spawn-failure close signal and that a dead worker closes its children's pipes. 'src/main/worker-thread-child-process/worker-thread-child-process.test.ts', - 'src/main/git/command-runner/worker-exec-file.test.ts', + 'src/main/git/command-runner/process-capture/worker-exec-file.test.ts', 'src/main/git/worktrees/removal/worktree-removal-real-git.test.ts', 'src/main/git/worktrees/catalog/worktree-list-paths.test.ts', 'src/main/runtime/workspaces/removal/runtime-failed-local-worktree-removal.test.ts', diff --git a/src/main/git/branch-switch-target.ts b/src/main/git/branch-switch-target.ts index e8af2ba1d2e..6d4d4d9af43 100644 --- a/src/main/git/branch-switch-target.ts +++ b/src/main/git/branch-switch-target.ts @@ -3,7 +3,7 @@ import type { BranchSwitchCreation } from '../../shared/git/branch-switch-target' import { isBranchNameValid } from '../../shared/git/branch-switch-target' -import { gitExecFileAsync } from './runner' +import { gitExecFileAsync } from './command-runner/git-exec-file' import { gitOptionsForWorktree, type GitRuntimeOptions } from './git-runtime-options' import { readGitCommandFailureStderr } from '../../shared/git/commands/git-command-failure-text' diff --git a/src/main/git/branch-switch.ts b/src/main/git/branch-switch.ts index 363e018ba73..a72c82bddd2 100644 --- a/src/main/git/branch-switch.ts +++ b/src/main/git/branch-switch.ts @@ -16,7 +16,8 @@ import { normalizeRuntimePathForComparison } from '../../shared/cross-platform-p import { isGitWorktreeMutationInFlight } from './command-runner/git-worktree-mutation-state' import { resolveGitDir } from './source-control/resolve-git-dir' import { gitOptionsForWorktree, type GitRuntimeOptions } from './git-runtime-options' -import { gitExecFileAsync, gitOptionalLocksDisabledEnv } from './runner' +import { gitExecFileAsync } from './command-runner/git-exec-file' +import { gitOptionalLocksDisabledEnv } from './command-runner/git-environment/git-process-env' import { parseCheckoutSkippedPaths } from './checkout-skipped-paths' import { readGitCommandFailureStderr } from '../../shared/git/commands/git-command-failure-text' diff --git a/src/main/git/canonical-repo-key.ts b/src/main/git/canonical-repo-key.ts index aefe55ee633..bb3ce42ada5 100644 --- a/src/main/git/canonical-repo-key.ts +++ b/src/main/git/canonical-repo-key.ts @@ -1,7 +1,7 @@ import type { LocalGitExecOptions } from './repo-default-base-ref' import type { GitExecOptions } from './command-runner/git-exec-options' import { toWslExecutionSpace } from '../../shared/wsl-paths' -import { gitExecFileAsync } from './runner' +import { gitExecFileAsync } from './command-runner/git-exec-file' import { resolveRevParsePath } from './worktrees/catalog/worktree-path-comparison' /** Fetch serialization and ref maintenance share a host-scoped Git common-dir identity across worktrees. */ diff --git a/src/main/git/checkout.ts b/src/main/git/checkout.ts index 1a130f9571e..3eadf925712 100644 --- a/src/main/git/checkout.ts +++ b/src/main/git/checkout.ts @@ -2,8 +2,8 @@ import type { RuntimeGitLocalBranches } from '../../shared/runtime-worktree-cont import type { BranchSwitchCreation } from '../../shared/git/branch-switch-target' import type { GitRuntimeOptions } from './git-runtime-options' import { gitOptionsForWorktree } from './git-runtime-options' -import { gitExecFileAsync } from './runner' -import { gitEnvWithoutYesNoPrompt } from './command-runner/git-no-prompt-env' +import { gitExecFileAsync } from './command-runner/git-exec-file' +import { gitEnvWithoutYesNoPrompt } from './command-runner/git-environment/git-no-prompt-env' import { translateWorktreePath } from './worktrees/catalog/worktree-path-comparison' import { parseCheckoutSkippedPaths } from './checkout-skipped-paths' import { runWithGitReadCacheInvalidation } from './source-control/git-read-cache-invalidation' diff --git a/src/main/git/command-runner/git-operation-executor.test.ts b/src/main/git/command-runner/admission/git-operation-executor.test.ts similarity index 94% rename from src/main/git/command-runner/git-operation-executor.test.ts rename to src/main/git/command-runner/admission/git-operation-executor.test.ts index 8084af88491..6e089300ef9 100644 --- a/src/main/git/command-runner/git-operation-executor.test.ts +++ b/src/main/git/command-runner/admission/git-operation-executor.test.ts @@ -5,7 +5,7 @@ import { _resetGitAdmissionForTests } from './git-subprocess-admission' import { worktreeCreateGit, worktreePreparationGit -} from '../worktrees/creation/worktree-create-git-executor' +} from '../../worktrees/creation/worktree-create-git-executor' afterEach(() => _resetGitAdmissionForTests()) diff --git a/src/main/git/command-runner/git-operation-executor.ts b/src/main/git/command-runner/admission/git-operation-executor.ts similarity index 90% rename from src/main/git/command-runner/git-operation-executor.ts rename to src/main/git/command-runner/admission/git-operation-executor.ts index b32fe644728..4af6c3e3be4 100644 --- a/src/main/git/command-runner/git-operation-executor.ts +++ b/src/main/git/command-runner/admission/git-operation-executor.ts @@ -1,5 +1,5 @@ import { AsyncLocalStorage } from 'node:async_hooks' -import type { GitAdmissionTier } from './git-exec-options' +import type { GitAdmissionTier } from '../../../../shared/rpc-contract/git-admission-tier-params' const operations = new AsyncLocalStorage<{ tier: GitAdmissionTier; active: boolean }>() diff --git a/src/main/git/command-runner/git-subprocess-admission.ts b/src/main/git/command-runner/admission/git-subprocess-admission.ts similarity index 82% rename from src/main/git/command-runner/git-subprocess-admission.ts rename to src/main/git/command-runner/admission/git-subprocess-admission.ts index 24bfd71967d..17e3b3442d7 100644 --- a/src/main/git/command-runner/git-subprocess-admission.ts +++ b/src/main/git/command-runner/admission/git-subprocess-admission.ts @@ -1,8 +1,8 @@ -import { GitAdmissionScheduler } from '../../../shared/git/admission/git-admission-scheduler' +import { GitAdmissionScheduler } from '../../../../shared/git/admission/git-admission-scheduler' import type { GitAdmissionGrant, GitAdmissionRequest -} from '../../../shared/git/admission/git-admission-state' +} from '../../../../shared/git/admission/git-admission-state' import { resolveGitAdmissionTier } from './git-operation-executor' let scheduler = new GitAdmissionScheduler() diff --git a/src/main/git/command-runner/git-admission-storm-measurement.test.ts b/src/main/git/command-runner/git-admission-storm-measurement.test.ts deleted file mode 100644 index 48d8718c242..00000000000 --- a/src/main/git/command-runner/git-admission-storm-measurement.test.ts +++ /dev/null @@ -1,172 +0,0 @@ -import { existsSync, watch } from 'node:fs' -import { chmod, mkdir, readdir, writeFile } from 'node:fs/promises' -import path from 'node:path' -import { describe, expect, it } from 'vitest' -import { runProcess } from '@orca/process-host' -import { gitExecFileAsync } from './git-exec-file' -import { - GENERAL_CAP, - GENERAL_HEADROOM, - type GitAdmissionEvent -} from '../../../shared/git/admission/git-admission-state' -import { GitAdmissionScheduler } from '../../../shared/git/admission/git-admission-scheduler' -import { - _gitAdmissionSnapshotForTests, - _resetGitAdmissionForTests -} from './git-subprocess-admission' -import { - assertAdmissionLedger, - createStormRoot, - type InteractiveQueueSnapshot -} from './git-admission-storm-test-fixture' - -function waitForLiveChild(stateDir: string, id: string, signal: AbortSignal): Promise { - return new Promise((resolve, reject) => { - const watcher = watch(stateDir) - const finish = (error?: Error): void => { - clearTimeout(deadline) - watcher.close() - signal.removeEventListener('abort', aborted) - if (error) { - reject(error) - } else { - resolve() - } - } - const aborted = (): void => finish(new Error(`Aborted waiting for ${id}`)) - const deadline = setTimeout(() => finish(new Error(`Child ${id} did not start`)), 5_000) - const check = (): void => { - if (existsSync(path.join(stateDir, `${id}.live`))) { - finish() - } - } - watcher.on('change', check) - watcher.once('error', finish) - signal.addEventListener('abort', aborted, { once: true }) - if (signal.aborted) { - aborted() - } else { - check() - } - }) -} - -async function verifySpawnContention(): Promise { - delete process.env.ORCA_GIT_ADMISSION_DISABLED - const admissionEvents: GitAdmissionEvent[] = [] - _resetGitAdmissionForTests( - new GitAdmissionScheduler({ - now: () => 0, - onAdmissionEvent: (event) => admissionEvents.push(event) - }) - ) - const root = await createStormRoot('contention') - const stateDir = path.join(root, 'state') - const gateDir = path.join(root, 'gates') - const binDir = path.join(root, 'bin') - await Promise.all([stateDir, gateDir, binDir].map((directory) => mkdir(directory))) - const backgroundIds = Array.from({ length: GENERAL_CAP + 4 }, (_, index) => `background-${index}`) - const headroomIds = Array.from({ length: GENERAL_HEADROOM }, (_, index) => `interactive-${index}`) - const queuedIds = ['interactive-queued-0', 'interactive-queued-1'] - const ids = [...backgroundIds, ...headroomIds, ...queuedIds] - const gates = await runProcess({ - program: 'mkfifo', - args: ids.map((id) => path.join(gateDir, id)) - }) - expect(gates.code, gates.stderr).toBe(0) - const stub = path.join(binDir, 'git') - await writeFile( - stub, - `#!/bin/sh -set -eu -live="$ORCA_STUB_STATE_DIR/$ORCA_STUB_ID.live" -: > "$live" -trap 'rm -f "$live"' EXIT HUP INT TERM -IFS= read -r release < "$ORCA_STUB_GATE_DIR/$ORCA_STUB_ID" -printf 'stub:%s\\n' "$*" -` - ) - await chmod(stub, 0o755) - const controller = new AbortController() - const commands = new Map>() - const interactiveQueueSnapshots: InteractiveQueueSnapshot[] = [] - const start = (id: string, tier: 'background' | 'interactive'): void => { - if (tier === 'interactive') { - interactiveQueueSnapshots.push({ - commandLabel: id, - backgroundWaiterIds: _gitAdmissionSnapshotForTests() - .queuedWaiters.filter((waiter) => waiter.tier === 'background') - .map((waiter) => waiter.id) - }) - } - const command = gitExecFileAsync([tier === 'background' ? 'status' : 'rev-parse', id], { - cwd: root, - admissionTier: tier, - signal: controller.signal, - env: { - ...process.env, - PATH: `${binDir}${path.delimiter}${process.env.PATH ?? ''}`, - ORCA_STUB_ID: id, - ORCA_STUB_STATE_DIR: stateDir, - ORCA_STUB_GATE_DIR: gateDir - } - }) - void command.catch(() => {}) - commands.set(id, command) - } - const release = async (id: string): Promise => { - await waitForLiveChild(stateDir, id, controller.signal) - await writeFile(path.join(gateDir, id), 'release\n') - await expect(commands.get(id)).resolves.toEqual({ - stdout: `stub:${id.startsWith('background-') ? 'status' : 'rev-parse'} ${id}\n`, - stderr: '' - }) - } - try { - backgroundIds.forEach((id) => start(id, 'background')) - expect(_gitAdmissionSnapshotForTests().queued).toBe(4) - headroomIds.forEach((id) => start(id, 'interactive')) - queuedIds.forEach((id) => start(id, 'interactive')) - expect(_gitAdmissionSnapshotForTests()).toMatchObject({ - queued: 6, - budgets: { general: { baseUsed: GENERAL_CAP, headroomUsed: GENERAL_HEADROOM } } - }) - await Promise.all( - [...backgroundIds.slice(0, GENERAL_CAP), ...headroomIds].map((id) => - waitForLiveChild(stateDir, id, controller.signal) - ) - ) - expect(await readdir(stateDir)).toHaveLength(GENERAL_CAP + GENERAL_HEADROOM) - for (const [index, id] of queuedIds.entries()) { - await release(backgroundIds[index]) - await waitForLiveChild(stateDir, id, controller.signal) - } - expect(_gitAdmissionSnapshotForTests().queuedWaiters.map((waiter) => waiter.tier)).toEqual([ - 'background', - 'background', - 'background', - 'background' - ]) - for (const id of [...headroomIds, ...queuedIds, ...backgroundIds.slice(queuedIds.length)]) { - await release(id) - } - expect(admissionEvents.filter((event) => event.phase === 'grant')).toHaveLength(ids.length) - expect(admissionEvents.filter((event) => event.phase === 'release')).toHaveLength(ids.length) - assertAdmissionLedger({ admissionEvents, interactiveQueueSnapshots }) - expect(_gitAdmissionSnapshotForTests()).toMatchObject({ - queued: 0, - budgets: { general: { baseUsed: 0, headroomUsed: 0 } } - }) - expect(await readdir(stateDir)).toEqual([]) - } finally { - controller.abort() - await Promise.allSettled(commands.values()) - } -} - -describe.skipIf(process.platform === 'win32')('git admission storm measurement', () => { - it( - 'bounds real children and drains interactive work before the background backlog', - verifySpawnContention - ) -}) diff --git a/src/main/git/command-runner/git-admission-storm-test-fixture.ts b/src/main/git/command-runner/git-admission-storm-test-fixture.ts deleted file mode 100644 index b2329a0a7c3..00000000000 --- a/src/main/git/command-runner/git-admission-storm-test-fixture.ts +++ /dev/null @@ -1,244 +0,0 @@ -// PATH-injected POSIX fixture: report timings, but assert only structure in CI. -import { chmod, mkdtemp, mkdir, readdir, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import path from 'node:path' -import { afterEach, expect } from 'vitest' -import { gitExecFileAsync } from './git-exec-file' -import { - GIT_ADMISSION_AGING_MS, - MAX_GIT_CHILDREN, - type GitAdmissionEvent -} from '../../../shared/git/admission/git-admission-state' -import { GitAdmissionScheduler } from '../../../shared/git/admission/git-admission-scheduler' -import { - _gitAdmissionSnapshotForTests, - _resetGitAdmissionForTests -} from './git-subprocess-admission' - -type StormMeasurement = { - mode: 'disabled' | 'enabled' - maxConcurrentChildren: number - eventLoopMaxDriftMs: number - eventLoopP99DriftMs: number - interactiveP50Ms: number - interactiveP95Ms: number - totalWallMs: number - admissionEvents: GitAdmissionEvent[] - interactiveQueueSnapshots: InteractiveQueueSnapshot[] -} - -export type InteractiveQueueSnapshot = { - commandLabel: string - backgroundWaiterIds: number[] -} - -const tempRoots: string[] = [] -const originalAdmissionDisabled = process.env.ORCA_GIT_ADMISSION_DISABLED - -afterEach(async () => { - if (originalAdmissionDisabled === undefined) { - delete process.env.ORCA_GIT_ADMISSION_DISABLED - } else { - process.env.ORCA_GIT_ADMISSION_DISABLED = originalAdmissionDisabled - } - _resetGitAdmissionForTests() - await Promise.all(tempRoots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) -}) - -export async function createStormRoot(label: string): Promise { - const root = await mkdtemp(path.join(tmpdir(), `orca-git-storm-${label}-`)) - tempRoots.push(root) - return root -} - -function percentile(values: readonly number[], percentileValue: number): number { - if (values.length === 0) { - return 0 - } - const sorted = [...values].sort((a, b) => a - b) - return sorted[Math.min(sorted.length - 1, Math.ceil(sorted.length * percentileValue) - 1)] -} - -async function liveChildCount(stateDir: string): Promise { - return (await readdir(stateDir)).filter((name) => name.endsWith('.live')).length -} - -async function createStubGit(root: string): Promise { - const binDir = path.join(root, 'bin') - await mkdir(binDir) - const stubPath = path.join(binDir, 'git') - await writeFile( - stubPath, - `#!/bin/sh -set -eu -live="$ORCA_STUB_STATE_DIR/$ORCA_STUB_ID.live" -: > "$live" -trap 'rm -f "$live"' EXIT HUP INT TERM -sleep "$(awk "BEGIN { print $ORCA_STUB_SLEEP_MS / 1000 }")" -printf 'stub:%s\\n' "$*" -` - ) - await chmod(stubPath, 0o755) - return binDir -} - -function setAdmissionMode(mode: StormMeasurement['mode']): void { - if (mode === 'disabled') { - process.env.ORCA_GIT_ADMISSION_DISABLED = '1' - } else { - delete process.env.ORCA_GIT_ADMISSION_DISABLED - } -} - -export async function measureStorm(mode: StormMeasurement['mode']): Promise { - setAdmissionMode(mode) - const admissionEvents: GitAdmissionEvent[] = [] - const admissionClockStartedAt = performance.now() - _resetGitAdmissionForTests( - new GitAdmissionScheduler({ - now: () => Math.min(performance.now() - admissionClockStartedAt, GIT_ADMISSION_AGING_MS - 1), - onAdmissionEvent: (event) => admissionEvents.push(event) - }) - ) - const root = await createStormRoot(mode) - const stateDir = path.join(root, 'state') - await mkdir(stateDir) - const binDir = await createStubGit(root) - const repoDirs = await Promise.all( - Array.from({ length: 6 }, async (_, index) => { - const repoDir = path.join(root, `repo-${index}`) - await mkdir(repoDir) - return repoDir - }) - ) - const baseEnv = { ...process.env, PATH: `${binDir}${path.delimiter}${process.env.PATH ?? ''}` } - const startedAt = performance.now() - const drifts: number[] = [] - let nextJankSample = performance.now() + 50 - const jankTimer = setInterval(() => { - const now = performance.now() - drifts.push(Math.max(0, now - nextJankSample)) - nextJankSample = now + 50 - }, 50) - let maxConcurrentChildren = 0 - const censusTimer = setInterval(() => { - void liveChildCount(stateDir).then((count) => { - maxConcurrentChildren = Math.max(maxConcurrentChildren, count) - }) - }, 5) - - const background = Array.from({ length: 60 }, (_, index) => - gitExecFileAsync(['status', '--porcelain=v2', `storm-${index}`], { - cwd: repoDirs[index % repoDirs.length], - env: { - ...baseEnv, - ORCA_STUB_ID: `background-${index}`, - ORCA_STUB_SLEEP_MS: index % 10 === 0 ? '5000' : '200', - ORCA_STUB_STATE_DIR: stateDir - }, - admissionTier: 'background' - }) - ) - const interactiveQueueSnapshots: InteractiveQueueSnapshot[] = [] - const interactiveLatencies = await Promise.all( - Array.from( - { length: 10 }, - (_, index) => - new Promise((resolve, reject) => { - setTimeout( - () => { - void (async () => { - const concurrentAtInjection = await liveChildCount(stateDir) - const commandStartedAt = performance.now() - const commandLabel = `interactive-${index}` - interactiveQueueSnapshots.push({ - commandLabel, - backgroundWaiterIds: _gitAdmissionSnapshotForTests() - .queuedWaiters.filter((waiter) => waiter.tier === 'background') - .map((waiter) => waiter.id) - }) - await gitExecFileAsync(['rev-parse', commandLabel], { - cwd: repoDirs[index % repoDirs.length], - env: { - ...baseEnv, - ORCA_STUB_ID: `interactive-${index}`, - ORCA_STUB_SLEEP_MS: String(Math.max(10, concurrentAtInjection * 12)), - ORCA_STUB_STATE_DIR: stateDir - }, - admissionTier: 'interactive' - }) - resolve(performance.now() - commandStartedAt) - })().catch(reject) - }, - 50 * (index + 1) - ) - }) - ) - ) - await Promise.all(background) - clearInterval(censusTimer) - clearInterval(jankTimer) - maxConcurrentChildren = Math.max(maxConcurrentChildren, await liveChildCount(stateDir)) - const totalWallMs = performance.now() - startedAt - return { - mode, - maxConcurrentChildren, - eventLoopMaxDriftMs: Math.max(0, ...drifts), - eventLoopP99DriftMs: percentile(drifts, 0.99), - interactiveP50Ms: percentile(interactiveLatencies, 0.5), - interactiveP95Ms: percentile(interactiveLatencies, 0.95), - totalWallMs, - admissionEvents, - interactiveQueueSnapshots - } -} - -export function formatMeasurementTable(rows: readonly StormMeasurement[]): string { - const rounded = rows.map((row) => ({ - mode: row.mode, - maxConcurrentChildren: row.maxConcurrentChildren, - eventLoopMaxDriftMs: row.eventLoopMaxDriftMs.toFixed(1), - eventLoopP99DriftMs: row.eventLoopP99DriftMs.toFixed(1), - interactiveP50Ms: row.interactiveP50Ms.toFixed(1), - interactiveP95Ms: row.interactiveP95Ms.toFixed(1), - totalWallMs: row.totalWallMs.toFixed(1) - })) - return JSON.stringify(rounded) -} - -export function assertAdmissionLedger( - measurement: Pick -): void { - const activeWaiters = new Set() - const grantSequenceByWaiter = new Map() - const grantByLabel = new Map() - - measurement.admissionEvents.forEach((event, index) => { - expect(event.sequence).toBe(index) - if (event.phase === 'grant') { - activeWaiters.add(event.waiterId) - grantSequenceByWaiter.set(event.waiterId, event.sequence) - const label = event.args.find((arg) => arg.startsWith('interactive-')) - if (label) { - grantByLabel.set(label, event) - } - } else { - expect(activeWaiters.delete(event.waiterId)).toBe(true) - } - expect(activeWaiters.size).toBeLessThanOrEqual(MAX_GIT_CHILDREN) - for (const budget of event.budgets) { - expect(budget.baseUsed).toBeLessThanOrEqual(budget.baseCapacity) - expect(budget.headroomUsed).toBeLessThanOrEqual(budget.headroomCapacity) - } - }) - expect(activeWaiters.size).toBe(0) - - for (const snapshot of measurement.interactiveQueueSnapshots) { - const interactiveGrant = grantByLabel.get(snapshot.commandLabel) - expect(interactiveGrant).toBeDefined() - const preceded = snapshot.backgroundWaiterIds.filter( - (waiterId) => interactiveGrant!.sequence < (grantSequenceByWaiter.get(waiterId) ?? Infinity) - ).length - expect(preceded).toBeGreaterThanOrEqual(Math.ceil(snapshot.backgroundWaiterIds.length * 0.9)) - } -} diff --git a/src/main/git/command-runner/git-capability-state.test.ts b/src/main/git/command-runner/git-capability-state.test.ts deleted file mode 100644 index e1c78b867bd..00000000000 --- a/src/main/git/command-runner/git-capability-state.test.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { beforeEach, describe, expect, it } from 'vitest' -import { - clearGitCapabilityStateForTests, - getLocalGitCapabilityCache, - withLocalGitCapabilityCacheForExecution -} from './git-capability-state' -import { resetWslLinkedWorktreeGitRoutingForTests } from './wsl-linked-worktree-git-routing' - -describe('Git capability execution-host state', () => { - beforeEach(() => { - clearGitCapabilityStateForTests() - resetWslLinkedWorktreeGitRoutingForTests() - }) - - it('bounds local capability entries during WSL distro churn', () => { - const first = getLocalGitCapabilityCache({ wslDistro: 'first-distro' }) - first.rememberUnsupported('worktree-list-z') - for (let index = 0; index < 132; index += 1) { - getLocalGitCapabilityCache({ wslDistro: `distro-${index}` }) - } - expect( - getLocalGitCapabilityCache({ wslDistro: 'first-distro' }).shouldTry('worktree-list-z') - ).toBe(true) - }) - - it('starts non-candidate capability work without an added async turn', async () => { - let started = false - const result = withLocalGitCapabilityCacheForExecution({ cwd: '/repo' }, async () => { - started = true - return 'done' - }) - - expect(started).toBe(true) - await expect(result).resolves.toBe('done') - }) -}) diff --git a/src/main/git/command-runner/git-command-resolution-windows-checkout.test.ts b/src/main/git/command-runner/git-command-resolution-windows-checkout.test.ts deleted file mode 100644 index 60d5cdffd1c..00000000000 --- a/src/main/git/command-runner/git-command-resolution-windows-checkout.test.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { resolveGitCommand, resolveGitCommandWithoutProbe } from './git-command-resolution' -import { - recordHostAutocrlf, - recordLineEndingSample, - resetWslWindowsCheckoutGitConfigForTests, - wslWindowsCheckoutKey -} from '../wsl-windows-checkout-git-config' -import { - resetWslLinkedWorktreeGitRoutingForTests, - seedWslLinkedWorktreeGitRoutingForTests -} from './wsl-linked-worktree-git-routing' -import { bulkPathspecCommands } from '../source-control/git-pathspec' -import { - commandLineLength, - MAX_COMMAND_LINE_CHARS -} from '../../../shared/windows-command-line-budget' - -const originalPlatform = process.platform -const DRIVE_REPO = String.raw`C:\Users\dev\repo` - -function detectWindowsCheckout(): void { - const key = wslWindowsCheckoutKey(DRIVE_REPO, 'Ubuntu') - recordHostAutocrlf(key, 'true', Date.now()) - recordLineEndingSample(key, 'windows', 'clone', Date.now()) -} - -describe('WSL git on a Windows Git checkout', () => { - beforeEach(() => { - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - }) - - afterEach(() => { - Object.defineProperty(process, 'platform', { configurable: true, value: originalPlatform }) - resetWslWindowsCheckoutGitConfigForTests() - resetWslLinkedWorktreeGitRoutingForTests() - }) - - it('runs WSL git with Windows Git line-ending and stat settings once detected', () => { - detectWindowsCheckout() - - const resolved = resolveGitCommandWithoutProbe(['add', '--', 'a.ts'], { - cwd: DRIVE_REPO, - wslDistro: 'Ubuntu' - }) - - expect(resolved.binary).toBe('wsl.exe') - expect(resolved.args.join(' ')).toMatch(/core\.autocrlf=true.+core\.checkStat=minimal.+add/) - expect(resolved.args.join(' ')).not.toContain('trustctime') - }) - - it('leaves host-routed commands and undetected checkouts unchanged', () => { - expect( - resolveGitCommandWithoutProbe(['status'], { cwd: DRIVE_REPO, wslDistro: 'Ubuntu' }).args.join( - ' ' - ) - ).not.toContain('core.autocrlf') - - detectWindowsCheckout() - expect(resolveGitCommand(['status'], { cwd: DRIVE_REPO }).args).toEqual(['status']) - - seedWslLinkedWorktreeGitRoutingForTests(DRIVE_REPO) - expect(resolveGitCommand(['status'], { cwd: DRIVE_REPO, wslDistro: 'Ubuntu' }).args).toEqual([ - 'status' - ]) - }) - - it('keeps every bulk chunk under the command-line cap once the config is prepended', () => { - const paths = Array.from({ length: 400 }, (_, index) => `src/${'deep/'.repeat(12)}f${index}.ts`) - const chunks = bulkPathspecCommands(['add', '--'], paths, DRIVE_REPO, { wslDistro: 'Ubuntu' }) - detectWindowsCheckout() - - expect(chunks.length).toBeGreaterThan(1) - for (const chunk of chunks) { - const resolved = resolveGitCommandWithoutProbe(chunk, { - cwd: DRIVE_REPO, - wslDistro: 'Ubuntu' - }) - expect(commandLineLength([resolved.binary, ...resolved.args])).toBeLessThanOrEqual( - MAX_COMMAND_LINE_CHARS - ) - } - }) -}) diff --git a/src/main/git/command-runner/git-no-prompt-env.ts b/src/main/git/command-runner/git-environment/git-no-prompt-env.ts similarity index 100% rename from src/main/git/command-runner/git-no-prompt-env.ts rename to src/main/git/command-runner/git-environment/git-no-prompt-env.ts diff --git a/src/main/git/command-runner/git-process-env.ts b/src/main/git/command-runner/git-environment/git-process-env.ts similarity index 86% rename from src/main/git/command-runner/git-process-env.ts rename to src/main/git/command-runner/git-environment/git-process-env.ts index 9a72134400a..cc233232983 100644 --- a/src/main/git/command-runner/git-process-env.ts +++ b/src/main/git/command-runner/git-environment/git-process-env.ts @@ -1,6 +1,6 @@ -import { addWslEnvKeys } from '../../../shared/wsl-env' -import { gitCredentialPromptGuardEnv } from '../../../shared/git/commands/git-credential-prompt-env' -import { UNTRANSLATED_GIT_OUTPUT_ENV } from '../../../shared/git/commands/git-output-locale' +import { addWslEnvKeys } from '../../../../shared/wsl-env' +import { gitCredentialPromptGuardEnv } from '../../../../shared/git/commands/git-credential-prompt-env' +import { UNTRANSLATED_GIT_OUTPUT_ENV } from '../../../../shared/git/commands/git-output-locale' export function gitOptionalLocksDisabledEnv( env: NodeJS.ProcessEnv = process.env diff --git a/src/main/git/command-runner/git-ssh-policy-env.ts b/src/main/git/command-runner/git-environment/git-ssh-policy-env.ts similarity index 81% rename from src/main/git/command-runner/git-ssh-policy-env.ts rename to src/main/git/command-runner/git-environment/git-ssh-policy-env.ts index 39ed3b29d19..5a9dd9fb069 100644 --- a/src/main/git/command-runner/git-ssh-policy-env.ts +++ b/src/main/git/command-runner/git-environment/git-ssh-policy-env.ts @@ -1,16 +1,16 @@ -import { addWslEnvKeys } from '../../../shared/wsl-env' +import { addWslEnvKeys } from '../../../../shared/wsl-env' import { buildGitSshPolicyEnv, GIT_SSH_CONFIG_ARGS, parseGitSshConfig, type GitSshPolicyMode -} from '../../../shared/git/commands/git-ssh-policy-env' -import { findGitSubcommandIndex } from '../../../shared/git/commands/git-command-classification' -import { execFileCapture } from './exec-file-capture' -import { resolveGitCommand } from './git-command-resolution' -import { DEFAULT_GIT_MAX_BUFFER, type GitExecOptions } from './git-exec-options' +} from '../../../../shared/git/commands/git-ssh-policy-env' +import { findGitSubcommandIndex } from '../../../../shared/git/commands/git-command-classification' +import { execFileCapture } from '../process-capture/exec-file-capture' +import { resolveGitCommand } from '../host-routing/git-command-resolution' +import { DEFAULT_GIT_MAX_BUFFER, type GitExecOptions } from '../git-exec-options' import { promptGuardGitEnv } from './git-process-env' -import { acquireGitAdmission } from './git-subprocess-admission' +import { acquireGitAdmission } from '../admission/git-subprocess-admission' const CORE_SSH_COMMAND_PROBE_TIMEOUT_MS = 2500 // Cold WSL starts and login rc files need the environment probe's startup budget. diff --git a/src/main/git/command-runner/git-exec-admission-lifetime.test.ts b/src/main/git/command-runner/git-exec-admission-lifetime.test.ts index 328731e9916..bd26cf55d00 100644 --- a/src/main/git/command-runner/git-exec-admission-lifetime.test.ts +++ b/src/main/git/command-runner/git-exec-admission-lifetime.test.ts @@ -1,6 +1,5 @@ -import type { ChildProcess } from 'node:child_process' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { createFakeSpawnedChild } from '../../../shared/__fixtures__/fake-spawned-child' + import type * as GitFetchHeadLockModule from '../../../shared/git/fetch/git-fetch-head-lock' const { @@ -22,7 +21,7 @@ vi.mock('node:child_process', async (importOriginal) => ({ execFile: execFileMock, spawn: spawnMock })) -vi.mock('./spawned-command-tree-kill', () => ({ +vi.mock('./process-capture/spawned-command-tree-kill', () => ({ killSpawnedCommandTree: killSpawnedCommandTreeMock })) vi.mock('@orca/process-host/process-tree-termination', () => ({ @@ -44,36 +43,14 @@ vi.mock('../../../shared/git/fetch/git-fetch-head-lock', async (importOriginal) } }) -import { RuntimeRemoteFetchController } from '../../runtime/repositories/runtime-remote-fetch-controller' -import { gitExecFileAsync, gitExecFileAsyncBuffer } from './git-exec-file' -import { execFileCapture } from './exec-file-capture' -import { isGitWorktreeMutationInFlight } from './git-worktree-mutation-state' +import { execFileCapture } from './process-capture/exec-file-capture' + import { - acquireGitAdmission, _gitAdmissionSnapshotForTests, _resetGitAdmissionForTests -} from './git-subprocess-admission' +} from './admission/git-subprocess-admission' import { GitAdmissionScheduler } from '../../../shared/git/admission/git-admission-scheduler' -type ExecCallback = (error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void - -function mockChild(pid: number | undefined = 1234): ChildProcess { - return createFakeSpawnedChild(pid) -} - -function mockMissingSshConfig(callback: ExecCallback): ChildProcess { - const child = mockChild() - queueMicrotask(() => { - callback(Object.assign(new Error('No SSH configuration'), { code: 1 }), '', '') - child.emit('close', 1, null) - }) - return child -} - -async function settleAdmissionGrant(): Promise { - await vi.advanceTimersByTimeAsync(0) -} - describe('git exec admission lifetime', () => { beforeEach(() => { vi.useFakeTimers() @@ -89,146 +66,6 @@ describe('git exec admission lifetime', () => { _resetGitAdmissionForTests() }) - it('keeps the SSH policy probe queued beyond its execution budget until caller cancellation', async () => { - _resetGitAdmissionForTests(new GitAdmissionScheduler({ generalCap: 1, generalHeadroom: 0 })) - const holding = acquireGitAdmission({ args: ['status'], cwd: '/repo' }) - await settleAdmissionGrant() - const blocker = await holding - const controller = new AbortController() - const pending = gitExecFileAsync(['fetch', 'origin'], { - cwd: '/repo', - env: { ...process.env, GIT_SSH_COMMAND: '' }, - useConfiguredSshCommandForNetwork: true, - signal: controller.signal - }) - const rejection = expect(pending).rejects.toMatchObject({ name: 'AbortError' }) - await settleAdmissionGrant() - await vi.advanceTimersByTimeAsync(10_000) - expect(_gitAdmissionSnapshotForTests().queued).toBe(1) - expect(execFileMock).not.toHaveBeenCalled() - controller.abort() - await rejection - blocker.release() - expect(_gitAdmissionSnapshotForTests().queued).toBe(0) - }) - - it.each([false, true])( - 'never spawns an expired preview after admission (late timer: %s)', - async (lateTimer) => { - vi.stubEnv('GIT_SSH_COMMAND', 'ssh') - _resetGitAdmissionForTests(new GitAdmissionScheduler({ networkCap: 1, networkHeadroom: 0 })) - const blocker = await acquireGitAdmission({ args: ['fetch'], cwd: '/preview' }) - const controller = new RuntimeRemoteFetchController() - vi.spyOn(controller, 'getCanonicalRepoKey').mockResolvedValue('local::/preview/.git') - const preview = controller.refreshRemoteTrackingBaseForPreview('/preview', { - remote: 'origin', - branch: 'main', - ref: 'refs/remotes/origin/main', - base: 'origin/main' - }) - await settleAdmissionGrant() - expect(_gitAdmissionSnapshotForTests().queued).toBe(1) - vi.setSystemTime(Date.now() + (lateTimer ? 10_001 : 0)) - await vi.advanceTimersByTimeAsync(lateTimer ? 0 : 10_001) - blocker.release() - await settleAdmissionGrant() - await expect(preview).resolves.toEqual({ ok: false, errorKind: 'git_error' }) - expect(execFileMock).not.toHaveBeenCalled() - } - ) - - it.each(['timeout', 'abort'] as const)( - 'retains the string-exec permit and mutation after %s until close', - async (reason) => { - const child = mockChild() - execFileMock.mockReturnValue(child) - const controller = new AbortController() - const pending = gitExecFileAsync(['rebase', '--continue'], { - cwd: '/repo', - timeout: 10, - signal: controller.signal - }) - const rejection = expect(pending).rejects.toThrow( - reason === 'timeout' ? 'timed out' : 'aborted' - ) - await settleAdmissionGrant() - expect(execFileMock).toHaveBeenCalledOnce() - await expect(isGitWorktreeMutationInFlight('/repo', {})).resolves.toBe(true) - - if (reason === 'timeout') { - await vi.advanceTimersByTimeAsync(10) - } else { - controller.abort() - } - await rejection - expect(_gitAdmissionSnapshotForTests().budgets.general?.baseUsed).toBe(1) - const mutationBeforeClose = await isGitWorktreeMutationInFlight('/repo', {}) - - child.emit('close', null, 'SIGKILL') - await Promise.resolve() - expect(_gitAdmissionSnapshotForTests().budgets.general?.baseUsed).toBe(0) - expect(mutationBeforeClose).toBe(true) - await expect(isGitWorktreeMutationInFlight('/repo', {})).resolves.toBe(false) - } - ) - - it('retains the buffer-exec permit after maxBuffer settlement until close', async () => { - const child = mockChild() - let callback: ExecCallback | undefined - execFileMock.mockImplementation( - (_command: string, _args: string[], _options: unknown, received: ExecCallback) => { - callback = received - return child - } - ) - const pending = gitExecFileAsyncBuffer(['show', 'HEAD:file'], { cwd: '/repo' }) - await vi.waitFor(() => expect(callback).toBeTypeOf('function')) - - callback?.(new Error('maxBuffer exceeded'), Buffer.alloc(0), Buffer.alloc(0)) - await expect(pending).rejects.toThrow('maxBuffer exceeded') - expect(_gitAdmissionSnapshotForTests().budgets.general?.baseUsed).toBe(1) - - child.emit('close', null, 'SIGTERM') - await Promise.resolve() - expect(_gitAdmissionSnapshotForTests().budgets.general?.baseUsed).toBe(0) - }) - - it('does not admit a same-repo fetch while it waits for the FETCH_HEAD lock', async () => { - _resetGitAdmissionForTests(new GitAdmissionScheduler({ networkCap: 2, networkHeadroom: 0 })) - const children = [mockChild(1001), mockChild(1002)] - const callbacks: ExecCallback[] = [] - execFileMock.mockImplementation( - (_command: string, args: string[], _options: unknown, callback: ExecCallback) => { - if (args[0] === 'config') { - return mockMissingSshConfig(callback) - } - callbacks.push(callback) - return children[callbacks.length - 1] - } - ) - - const first = gitExecFileAsync(['fetch', 'origin'], { cwd: '/same-repo' }) - await vi.waitFor(() => expect(callbacks).toHaveLength(1)) - const second = gitExecFileAsync(['fetch', 'origin'], { cwd: '/same-repo' }) - await Promise.resolve() - - expect(execFileMock).toHaveBeenCalledTimes(2) - expect(_gitAdmissionSnapshotForTests()).toMatchObject({ - queued: 0, - budgets: { network: { baseUsed: 1, headroomUsed: 0 } } - }) - - callbacks[0]?.(null, '', '') - children[0].emit('close', 0, null) - await expect(first).resolves.toEqual({ stdout: '', stderr: '' }) - await vi.waitFor(() => expect(callbacks).toHaveLength(2)) - expect(execFileMock).toHaveBeenCalledTimes(4) - callbacks[1]?.(null, '', '') - children[1].emit('close', 0, null) - await expect(second).resolves.toEqual({ stdout: '', stderr: '' }) - expect(_gitAdmissionSnapshotForTests().budgets.network?.baseUsed).toBe(0) - }) - it('reports pre-aborted capture as a no-child termination', async () => { const controller = new AbortController() const onChildTerminated = vi.fn() @@ -243,149 +80,4 @@ describe('git exec admission lifetime', () => { expect(execFileMock).not.toHaveBeenCalled() expect(onChildTerminated).toHaveBeenCalledOnce() }) - - it('retains barrier admission past bounded settlement until termination is observed', async () => { - const child = mockChild() - spawnMock.mockReturnValue(child) - const pending = gitExecFileAsync(['rebase', '--continue'], { - cwd: '/repo', - terminationBarrier: true, - timeout: 10 - }) - const rejection = expect(pending).rejects.toThrow('timed out') - await settleAdmissionGrant() - expect(spawnMock).toHaveBeenCalledOnce() - - await vi.advanceTimersByTimeAsync(2010) - expect(_gitAdmissionSnapshotForTests().budgets.general?.baseUsed).toBe(1) - await vi.advanceTimersByTimeAsync(10_000) - await rejection - expect(_gitAdmissionSnapshotForTests().budgets.general?.baseUsed).toBe(1) - const mutationBeforeClose = await isGitWorktreeMutationInFlight('/repo', {}) - - child.emit('close', null, 'SIGKILL') - await Promise.resolve() - expect(_gitAdmissionSnapshotForTests().budgets.general?.baseUsed).toBe(0) - expect(mutationBeforeClose).toBe(true) - await expect(isGitWorktreeMutationInFlight('/repo', {})).resolves.toBe(false) - }) - - it.each([false, true])( - 'waits beyond the execution timeout before spawning (buffer: %s)', - async (buffer) => { - _resetGitAdmissionForTests(new GitAdmissionScheduler({ generalCap: 1, generalHeadroom: 0 })) - const holding = acquireGitAdmission({ args: ['status'], cwd: '/repo' }) - await settleAdmissionGrant() - const blocker = await holding - const child = mockChild() - let callback: ExecCallback | undefined - execFileMock.mockImplementation((_command, _args, _options, received: ExecCallback) => { - callback = received - return child - }) - const pending = buffer - ? gitExecFileAsyncBuffer(['status'], { cwd: '/repo', timeout: 50 }) - : gitExecFileAsync(['status'], { cwd: '/repo', timeout: 50 }) - await settleAdmissionGrant() - await vi.advanceTimersByTimeAsync(500) - expect(execFileMock).not.toHaveBeenCalled() - expect(_gitAdmissionSnapshotForTests().queued).toBe(1) - blocker.release() - await settleAdmissionGrant() - expect(execFileMock).toHaveBeenCalledOnce() - await vi.advanceTimersByTimeAsync(49) - callback?.(null, buffer ? Buffer.from('ok') : 'ok', buffer ? Buffer.alloc(0) : '') - child.emit('close', 0, null) - expect((await pending).stdout.toString()).toBe('ok') - expect(_gitAdmissionSnapshotForTests().queued).toBe(0) - expect(_gitAdmissionSnapshotForTests().budgets.general?.baseUsed).toBe(0) - } - ) - - it('still reports a caller abort of a queued command as an abort', async () => { - vi.useRealTimers() - _resetGitAdmissionForTests(new GitAdmissionScheduler({ generalCap: 1, generalHeadroom: 0 })) - const blocker = mockChild() - let finishBlocker: ExecCallback | undefined - execFileMock.mockImplementation( - (_command: string, _args: string[], _options: unknown, callback: ExecCallback) => { - finishBlocker = callback - return blocker - } - ) - const holding = gitExecFileAsync(['status'], { cwd: '/repo' }) - await vi.waitFor(() => expect(finishBlocker).toBeTypeOf('function')) - - const controller = new AbortController() - const queued = gitExecFileAsync(['rebase', '--continue'], { - cwd: '/repo', - timeout: 60_000, - signal: controller.signal - }) - await vi.waitFor(() => expect(_gitAdmissionSnapshotForTests().queued).toBe(1)) - await expect(isGitWorktreeMutationInFlight('/repo', {})).resolves.toBe(true) - controller.abort() - - await expect(queued).rejects.toMatchObject({ name: 'AbortError' }) - expect(execFileMock).toHaveBeenCalledOnce() - await expect(isGitWorktreeMutationInFlight('/repo', {})).resolves.toBe(false) - - finishBlocker?.(null, '', '') - blocker.emit('close', 0, null) - await expect(holding).resolves.toEqual({ stdout: '', stderr: '' }) - }) - - it('serializes FETCH_HEAD callers before they enter admission', async () => { - _resetGitAdmissionForTests(new GitAdmissionScheduler({ networkCap: 1, networkHeadroom: 1 })) - const children = new Map() - const callbacks = new Map() - execFileMock.mockImplementation( - (_command: string, args: string[], _options: unknown, callback: ExecCallback) => { - if (args[0] === 'config') { - return mockMissingSshConfig(callback) - } - const label = args[1] ?? '' - const child = mockChild() - children.set(label, child) - callbacks.set(label, callback) - return child - } - ) - - const first = gitExecFileAsync(['fetch', 'first'], { - cwd: '/repo', - admissionTier: 'background' - }) - await vi.waitFor(() => expect(callbacks.has('first')).toBe(true)) - const background = gitExecFileAsync(['fetch', 'background'], { - cwd: '/repo', - admissionTier: 'background' - }) - const interactive = gitExecFileAsync(['fetch', 'interactive'], { - cwd: '/repo', - admissionTier: 'interactive' - }) - - await Promise.resolve() - expect(_gitAdmissionSnapshotForTests().queued).toBe(0) - expect([...callbacks.keys()]).toEqual(['first']) - - callbacks.get('first')?.(null, '', '') - await expect(first).resolves.toEqual({ stdout: '', stderr: '' }) - await vi.waitFor(() => expect(_gitAdmissionSnapshotForTests().queued).toBe(1)) - expect([...callbacks.keys()]).toEqual(['first']) - - children.get('first')?.emit('close', 0, null) - await vi.waitFor(() => expect(callbacks.has('background')).toBe(true)) - expect([...callbacks.keys()]).toEqual(['first', 'background']) - - callbacks.get('background')?.(null, '', '') - await expect(background).resolves.toEqual({ stdout: '', stderr: '' }) - await vi.waitFor(() => expect(callbacks.has('interactive')).toBe(true)) - - children.get('background')?.emit('close', 0, null) - callbacks.get('interactive')?.(null, '', '') - await expect(interactive).resolves.toEqual({ stdout: '', stderr: '' }) - children.get('interactive')?.emit('close', 0, null) - }) }) diff --git a/src/main/git/command-runner/git-exec-file-sync.ts b/src/main/git/command-runner/git-exec-file-sync.ts index e5468fdfd84..b62c0494686 100644 --- a/src/main/git/command-runner/git-exec-file-sync.ts +++ b/src/main/git/command-runner/git-exec-file-sync.ts @@ -1,7 +1,7 @@ import { execFileSync, type SpawnOptions } from 'node:child_process' import { recordSubprocessSpawn } from '../../diagnostics/main-thread-churn-probe' -import { untranslatedGitOutputEnv } from './git-process-env' -import { resolveCommand } from './wsl-command-resolution' +import { untranslatedGitOutputEnv } from './git-environment/git-process-env' +import { resolveCommand } from './host-routing/wsl-command-resolution' // Bound synchronous Git: a dead network drive can freeze the main thread. const GIT_EXEC_SYNC_TIMEOUT_MS = 15_000 diff --git a/src/main/git/command-runner/git-exec-file.ts b/src/main/git/command-runner/git-exec-file.ts index 99f36d3f9e5..5b6714ecac8 100644 --- a/src/main/git/command-runner/git-exec-file.ts +++ b/src/main/git/command-runner/git-exec-file.ts @@ -4,10 +4,11 @@ import { runWithGitFetchHeadLock } from '../../../shared/git/fetch/git-fetch-head-lock' import { pendingWslDriveCheckoutGitRouting } from '../wsl-drive-checkout-git-routing' -import type { ResolvedCommand } from './wsl-command-resolution' -import { annotateWslHostFailure, isTransientWslFailure } from './wsl-host-failure' -import type { GitAdmissionTier, GitExecOptions } from './git-exec-options' -import { execFileCapture, execFileCaptureToTermination } from './exec-file-capture' +import type { ResolvedCommand } from './host-routing/wsl-command-resolution' +import { annotateWslHostFailure, isTransientWslFailure } from './host-routing/wsl-host-failure' +import type { GitAdmissionTier } from '../../../shared/rpc-contract/git-admission-tier-params' +import type { GitExecOptions } from './git-exec-options' +import { execFileCapture, execFileCaptureToTermination } from './process-capture/exec-file-capture' import { pendingWslDirectGitReadEnvironment, directWslGitExitCode, @@ -15,22 +16,22 @@ import { disableDirectWslGitAfterSuccessfulFallback, invalidateMissingDirectWslGit, resolveGitCommand -} from './git-command-resolution' -import { prepareWindowsHostGitEnvironment } from './windows-host-git-environment' -import { buildNetworkSshPolicyEnv } from './git-ssh-policy-env' -import { nonInteractiveGitEnv, untranslatedGitOutputEnv } from './git-process-env' -import { acquireGitAdmission } from './git-subprocess-admission' +} from './host-routing/git-command-resolution' +import { prepareWindowsHostGitEnvironment } from './host-routing/windows-host-git-environment' +import { buildNetworkSshPolicyEnv } from './git-environment/git-ssh-policy-env' +import { nonInteractiveGitEnv, untranslatedGitOutputEnv } from './git-environment/git-process-env' +import { acquireGitAdmission } from './admission/git-subprocess-admission' import { GitCommandTimeoutError, gitCommandTimeoutMs } from '../../../shared/git/commands/git-command-timeout' import { classifyGitCommand } from '../../../shared/git/commands/git-command-classification' -import { createAbortError } from './abort-error' -import { readCapturedGitBuffer, readCapturedGitString } from './captured-git-output' -import { runUnlessGitCwdKnownMissing } from './missing-git-spawn-cwd' +import { createAbortError } from './process-capture/abort-error' +import { readCapturedGitBuffer, readCapturedGitString } from './process-capture/captured-git-output' +import { runUnlessGitCwdKnownMissing } from './host-routing/missing-git-spawn-cwd' import { trackGitWorktreeMutation } from './git-worktree-mutation-state' -import { routeLocalGitOptions, runAdmittedWslGit } from './local-git-runtime-route' -import { gitRunsIn } from './git-runs-in' +import { routeLocalGitOptions, runAdmittedWslGit } from './host-routing/local-git-runtime-route' +import { gitRunsIn } from './host-routing/git-runs-in' async function gitExecFileAsyncUnlocked( args: string[], diff --git a/src/main/git/command-runner/git-exec-options.ts b/src/main/git/command-runner/git-exec-options.ts index 82ff71da4cd..e98f02ca1f1 100644 --- a/src/main/git/command-runner/git-exec-options.ts +++ b/src/main/git/command-runner/git-exec-options.ts @@ -3,8 +3,6 @@ export const DEFAULT_GIT_MAX_BUFFER = 10 * 1024 * 1024 import type { GitAdmissionTier } from '../../../shared/rpc-contract/git-admission-tier-params' -export type { GitAdmissionTier } - export type GitExecOptions = { cwd: string encoding?: BufferEncoding | 'buffer' diff --git a/src/main/git/command-runner/git-spawn-wsl-admission.test.ts b/src/main/git/command-runner/git-spawn-wsl-admission.test.ts deleted file mode 100644 index 86ab71f1f1b..00000000000 --- a/src/main/git/command-runner/git-spawn-wsl-admission.test.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { EventEmitter } from 'node:events' -import type { ChildProcess } from 'node:child_process' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { withGitAdmission } from './git-spawn' -import { - admitWslGit, - resetWslGitAdmissionForTests, - setLocalGitRuntimeRouter, - WslGitSkippedError -} from './local-git-runtime-route' - -const originalPlatform = process.platform -const CWD = String.raw`C:\wsl-project` - -function failingChild(stderr: string): ChildProcess { - const child = Object.assign(new EventEmitter(), { pid: 42, stderr: new EventEmitter() }) - setTimeout(() => { - child.stderr.emit('data', Buffer.from(stderr)) - child.emit('close', 1, null) - }, 0) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: withGitAdmission uses only pid, stderr and the error/close events. - return child as unknown as ChildProcess -} - -beforeEach(() => { - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) -}) - -afterEach(() => { - setLocalGitRuntimeRouter(null) - resetWslGitAdmissionForTests() - Object.defineProperty(process, 'platform', { configurable: true, value: originalPlatform }) -}) - -async function spawnAndClose(stderr: string, wslDistro?: string): Promise { - const child = await withGitAdmission( - ['status'], - { cwd: CWD, ...(wslDistro ? { wslDistro } : {}) }, - () => failingChild(stderr) - ) - await new Promise((resolve) => child.once('close', resolve)) -} - -describe('withGitAdmission and a missing distro', () => { - it('records a spawned WSL Git that reports its distro missing, so the next call fails at once', async () => { - setLocalGitRuntimeRouter(() => 'Ubuntu') - await spawnAndClose('There is no distribution with the supplied name.\n') - await expect(admitWslGit({ cwd: CWD, wslDistro: 'Ubuntu' })).rejects.toBeInstanceOf( - WslGitSkippedError - ) - }) -}) diff --git a/src/main/git/command-runner/git-spawn.ts b/src/main/git/command-runner/git-spawn.ts index 56d8243f2ff..7f552324699 100644 --- a/src/main/git/command-runner/git-spawn.ts +++ b/src/main/git/command-runner/git-spawn.ts @@ -1,22 +1,22 @@ import { spawn, type ChildProcess, type SpawnOptions } from 'node:child_process' import { recordSubprocessSpawn } from '../../diagnostics/main-thread-churn-probe' import { startGitSpan } from '../../observability/instrumentation' -import { createAbortError } from './abort-error' -import { resolveGitCommand } from './git-command-resolution' +import { createAbortError } from './process-capture/abort-error' +import { resolveGitCommand } from './host-routing/git-command-resolution' import { pendingWslDriveCheckoutGitRouting } from '../wsl-drive-checkout-git-routing' -import { untranslatedGitOutputEnv } from './git-process-env' -import { prepareWindowsHostGitEnvironment } from './windows-host-git-environment' -import type { GitAdmissionTier } from './git-exec-options' -import { acquireGitAdmission } from './git-subprocess-admission' +import { untranslatedGitOutputEnv } from './git-environment/git-process-env' +import { prepareWindowsHostGitEnvironment } from './host-routing/windows-host-git-environment' +import type { GitAdmissionTier } from '../../../shared/rpc-contract/git-admission-tier-params' +import { acquireGitAdmission } from './admission/git-subprocess-admission' import { classifyGitCommand } from '../../../shared/git/commands/git-command-classification' -import { buildNetworkSshPolicyEnv } from './git-ssh-policy-env' +import { buildNetworkSshPolicyEnv } from './git-environment/git-ssh-policy-env' import { admitWslGit, isLocalGitRuntimeRouterInstalled, noteWslGitFailure, routeLocalGitOptions -} from './local-git-runtime-route' -import { gitRunsIn } from './git-runs-in' +} from './host-routing/local-git-runtime-route' +import { gitRunsIn } from './host-routing/git-runs-in' export type GitSpawnOptions = SpawnOptions & { cwd: string diff --git a/src/main/git/command-runner/git-stream-stdout.ts b/src/main/git/command-runner/git-stream-stdout.ts index 9b7fec7187e..1f90f5daac0 100644 --- a/src/main/git/command-runner/git-stream-stdout.ts +++ b/src/main/git/command-runner/git-stream-stdout.ts @@ -2,15 +2,13 @@ import { spawn, type ChildProcess, type SpawnOptions } from 'node:child_process' import { StringDecoder } from 'node:string_decoder' import { withGitSpan } from '../../observability/instrumentation' import { recordSubprocessSpawn } from '../../diagnostics/main-thread-churn-probe' -import { createAbortError } from './abort-error' -import { killSpawnedCommandTree } from './spawned-command-tree-kill' +import { createAbortError } from './process-capture/abort-error' +import { killSpawnedCommandTree } from './process-capture/spawned-command-tree-kill' import { pendingWslDriveCheckoutGitRouting } from '../wsl-drive-checkout-git-routing' -import type { ResolvedCommand } from './wsl-command-resolution' -import { - DEFAULT_GIT_MAX_BUFFER, - type GitAdmissionTier, - type GitExecOptions -} from './git-exec-options' +import type { ResolvedCommand } from './host-routing/wsl-command-resolution' +import { DEFAULT_GIT_MAX_BUFFER } from './git-exec-options' +import type { GitAdmissionTier } from '../../../shared/rpc-contract/git-admission-tier-params' +import type { GitExecOptions } from './git-exec-options' import { pendingWslDirectGitReadEnvironment, directWslGitExitCode, @@ -18,17 +16,17 @@ import { invalidateMissingDirectWslGit, resolveGitCommand, resolveGitCommandWithoutProbe -} from './git-command-resolution' -import { prepareWindowsHostGitEnvironment } from './windows-host-git-environment' -import { nonInteractiveGitEnv, untranslatedGitOutputEnv } from './git-process-env' +} from './host-routing/git-command-resolution' +import { prepareWindowsHostGitEnvironment } from './host-routing/windows-host-git-environment' +import { nonInteractiveGitEnv, untranslatedGitOutputEnv } from './git-environment/git-process-env' import { gitSpawn } from './git-spawn' -import { acquireGitAdmission } from './git-subprocess-admission' +import { acquireGitAdmission } from './admission/git-subprocess-admission' import { GitCommandTimeoutError, gitCommandTimeoutMs } from '../../../shared/git/commands/git-command-timeout' -import { routeLocalGitOptions, runAdmittedWslGit } from './local-git-runtime-route' -import { gitRunsIn } from './git-runs-in' +import { routeLocalGitOptions, runAdmittedWslGit } from './host-routing/local-git-runtime-route' +import { gitRunsIn } from './host-routing/git-runs-in' /** Result of a streamed git command; `stoppedEarly` is true when onStdout asked to stop before the child exited. */ export type GitStreamResult = { stoppedEarly: boolean } diff --git a/src/main/git/command-runner/git-capability-state.ts b/src/main/git/command-runner/host-routing/git-capability-state.ts similarity index 93% rename from src/main/git/command-runner/git-capability-state.ts rename to src/main/git/command-runner/host-routing/git-capability-state.ts index f1c5c051d91..601d38c3bde 100644 --- a/src/main/git/command-runner/git-capability-state.ts +++ b/src/main/git/command-runner/host-routing/git-capability-state.ts @@ -1,5 +1,5 @@ -import { GitCapabilityCache } from '../../../shared/git/commands/git-capability-cache' -import { parseWslUncPath } from '../../../shared/wsl-paths' +import { GitCapabilityCache } from '../../../../shared/git/commands/git-capability-cache' +import { parseWslUncPath } from '../../../../shared/wsl-paths' import { isWslLinkedWorktreeGitRoutingCandidate, prepareWslLinkedWorktreeGitRouting diff --git a/src/main/git/command-runner/host-routing/git-command-resolution-windows-checkout.test.ts b/src/main/git/command-runner/host-routing/git-command-resolution-windows-checkout.test.ts new file mode 100644 index 00000000000..cac67e1e114 --- /dev/null +++ b/src/main/git/command-runner/host-routing/git-command-resolution-windows-checkout.test.ts @@ -0,0 +1,43 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { resolveGitCommandWithoutProbe } from './git-command-resolution' +import { + recordHostAutocrlf, + recordLineEndingSample, + resetWslWindowsCheckoutGitConfigForTests, + wslWindowsCheckoutKey +} from '../../wsl-windows-checkout-git-config' +import { resetWslLinkedWorktreeGitRoutingForTests } from './wsl-linked-worktree-git-routing' + +const originalPlatform = process.platform +const DRIVE_REPO = String.raw`C:\Users\dev\repo` + +function detectWindowsCheckout(): void { + const key = wslWindowsCheckoutKey(DRIVE_REPO, 'Ubuntu') + recordHostAutocrlf(key, 'true', Date.now()) + recordLineEndingSample(key, 'windows', 'clone', Date.now()) +} + +describe('WSL git on a Windows Git checkout', () => { + beforeEach(() => { + Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) + }) + + afterEach(() => { + Object.defineProperty(process, 'platform', { configurable: true, value: originalPlatform }) + resetWslWindowsCheckoutGitConfigForTests() + resetWslLinkedWorktreeGitRoutingForTests() + }) + + it('runs WSL git with Windows Git line-ending and stat settings once detected', () => { + detectWindowsCheckout() + + const resolved = resolveGitCommandWithoutProbe(['add', '--', 'a.ts'], { + cwd: DRIVE_REPO, + wslDistro: 'Ubuntu' + }) + + expect(resolved.binary).toBe('wsl.exe') + expect(resolved.args.join(' ')).toMatch(/core\.autocrlf=true.+core\.checkStat=minimal.+add/) + expect(resolved.args.join(' ')).not.toContain('trustctime') + }) +}) diff --git a/src/main/git/command-runner/git-command-resolution.ts b/src/main/git/command-runner/host-routing/git-command-resolution.ts similarity index 90% rename from src/main/git/command-runner/git-command-resolution.ts rename to src/main/git/command-runner/host-routing/git-command-resolution.ts index bc80c83a8c8..99121c1e22a 100644 --- a/src/main/git/command-runner/git-command-resolution.ts +++ b/src/main/git/command-runner/host-routing/git-command-resolution.ts @@ -1,8 +1,8 @@ -import { wslDistroForCommand } from '../../../shared/wsl-paths' -export { wslDistroForCommand } from '../../../shared/wsl-paths' -import { waitForPromiseWithSignal } from '../../../shared/abort-signal-reason' -import { withTimeout } from '../../../shared/promise-timeout-fallback' -import { isWslDirectGitReadCommand } from '../../../shared/git/commands/git-command-classification' +import { wslDistroForCommand } from '../../../../shared/wsl-paths' + +import { waitForPromiseWithSignal } from '../../../../shared/abort-signal-reason' +import { withTimeout } from '../../../../shared/promise-timeout-fallback' +import { isWslDirectGitReadCommand } from '../../../../shared/git/commands/git-command-classification' import { disableWslGitReadEnvironment, getWslGitReadEnvironment, @@ -10,11 +10,11 @@ import { isWslGitReadEnvironmentSettled, peekWslGitReadEnvironment, WSL_GIT_READ_ENVIRONMENT_WAIT_MS -} from '../wsl-git-read-environment' +} from '../../wsl-git-read-environment' import { usesHostGitForWslLinkedWorktree } from './wsl-linked-worktree-git-routing' -import { withWslWindowsCheckoutGitConfig } from '../wsl-windows-checkout-git-config' +import { withWslWindowsCheckoutGitConfig } from '../../wsl-windows-checkout-git-config' import { resolveCommand, type ResolvedCommand } from './wsl-command-resolution' -import type { GitExecOptions } from './git-exec-options' +import type { GitExecOptions } from '../git-exec-options' // Linux Git needs Windows-checkout settings; classify original args and inject only at spawn. function wslGitArgs(args: string[], options: GitExecOptions): string[] { diff --git a/src/main/git/command-runner/git-runs-in.ts b/src/main/git/command-runner/host-routing/git-runs-in.ts similarity index 100% rename from src/main/git/command-runner/git-runs-in.ts rename to src/main/git/command-runner/host-routing/git-runs-in.ts diff --git a/src/main/git/command-runner/local-git-runtime-route.ts b/src/main/git/command-runner/host-routing/local-git-runtime-route.ts similarity index 96% rename from src/main/git/command-runner/local-git-runtime-route.ts rename to src/main/git/command-runner/host-routing/local-git-runtime-route.ts index 5e9b0383851..941258ed923 100644 --- a/src/main/git/command-runner/local-git-runtime-route.ts +++ b/src/main/git/command-runner/host-routing/local-git-runtime-route.ts @@ -4,8 +4,8 @@ * two on one checkout is what lets one Git prune the other's worktrees (risk R36). A UNC cwd already * names its distro; a caller that must run the host's Git anyway says so with `hostGit: true`. */ -import { isWslDistroNotFoundFailure } from '../../wsl/discovery/wsl-distro-unsupported' -import type { GitAdmissionTier } from './git-exec-options' +import { isWslDistroNotFoundFailure } from '../../../wsl/discovery/wsl-distro-unsupported' +import type { GitAdmissionTier } from '../../../../shared/rpc-contract/git-admission-tier-params' type RoutableGitOptions = { cwd: string diff --git a/src/main/git/command-runner/missing-git-spawn-cwd.ts b/src/main/git/command-runner/host-routing/missing-git-spawn-cwd.ts similarity index 90% rename from src/main/git/command-runner/missing-git-spawn-cwd.ts rename to src/main/git/command-runner/host-routing/missing-git-spawn-cwd.ts index 76623f8b2bc..3409c1063bc 100644 --- a/src/main/git/command-runner/missing-git-spawn-cwd.ts +++ b/src/main/git/command-runner/host-routing/missing-git-spawn-cwd.ts @@ -1,7 +1,7 @@ import { stat } from 'node:fs/promises' -import { isDefinitiveAbsence } from '../../../shared/definitive-filesystem-absence' -import { waitForPromiseWithSignal } from '../../../shared/abort-signal-reason' -import { isMissingCommandBinaryError } from '../exec-error' +import { isDefinitiveAbsence } from '../../../../shared/definitive-filesystem-absence' +import { waitForPromiseWithSignal } from '../../../../shared/abort-signal-reason' +import { isMissingCommandBinaryError } from '../../exec-error' const MAX_KNOWN_MISSING_CWDS = 256 // Remember missing folders in memory to avoid a failing Git spawn on every sweep. diff --git a/src/main/git/command-runner/windows-host-git-environment.ts b/src/main/git/command-runner/host-routing/windows-host-git-environment.ts similarity index 97% rename from src/main/git/command-runner/windows-host-git-environment.ts rename to src/main/git/command-runner/host-routing/windows-host-git-environment.ts index b67a4a16e67..8d6c85afe31 100644 --- a/src/main/git/command-runner/windows-host-git-environment.ts +++ b/src/main/git/command-runner/host-routing/windows-host-git-environment.ts @@ -1,4 +1,4 @@ -import { createAbortError } from './abort-error' +import { createAbortError } from '../process-capture/abort-error' import { resolveGitCommand } from './git-command-resolution' import type { ResolvedCommand } from './wsl-command-resolution' diff --git a/src/main/git/command-runner/wsl-aware-spawn.ts b/src/main/git/command-runner/host-routing/wsl-aware-spawn.ts similarity index 90% rename from src/main/git/command-runner/wsl-aware-spawn.ts rename to src/main/git/command-runner/host-routing/wsl-aware-spawn.ts index e0fce9a4de7..50e151e6c5b 100644 --- a/src/main/git/command-runner/wsl-aware-spawn.ts +++ b/src/main/git/command-runner/host-routing/wsl-aware-spawn.ts @@ -1,10 +1,10 @@ import { spawn, type ChildProcess, type SpawnOptions } from 'node:child_process' -import { recordSubprocessSpawn } from '../../diagnostics/main-thread-churn-probe' +import { recordSubprocessSpawn } from '../../../diagnostics/main-thread-churn-probe' import { commandLineLength, MAX_COMMAND_LINE_CHARS, WindowsCommandLineBudgetError -} from '../../../shared/windows-command-line-budget' +} from '../../../../shared/windows-command-line-budget' import { resolveCommand, withWslPreparation } from './wsl-command-resolution' export function wslAwareSpawn( diff --git a/src/main/git/command-runner/wsl-command-resolution-allowlist.test.ts b/src/main/git/command-runner/host-routing/wsl-command-resolution-allowlist.test.ts similarity index 69% rename from src/main/git/command-runner/wsl-command-resolution-allowlist.test.ts rename to src/main/git/command-runner/host-routing/wsl-command-resolution-allowlist.test.ts index feefc6d5ad8..35465504c64 100644 --- a/src/main/git/command-runner/wsl-command-resolution-allowlist.test.ts +++ b/src/main/git/command-runner/host-routing/wsl-command-resolution-allowlist.test.ts @@ -10,13 +10,13 @@ vi.mock('node:child_process', async (original) => ({ spawn: spawnMock, execFileSync: execFileSyncMock })) -vi.mock('../../wsl/discovery/wsl-background-distro-gate', () => ({ +vi.mock('../../../wsl/discovery/wsl-background-distro-gate', () => ({ noteWslDistroLaunched: vi.fn() })) import { resolveCommand } from './wsl-command-resolution' -import { gitExecFileSync } from './git-exec-file-sync' -import { gitSpawn } from './git-spawn' +import { gitExecFileSync } from '../git-exec-file-sync' +import { gitSpawn } from '../git-spawn' import { wslAwareSpawn } from './wsl-aware-spawn' const ALLOWLIST = 'ORCA_INTERNAL_WSL_DISTRO_ALLOWLIST' @@ -38,25 +38,6 @@ afterEach(() => { }) describe('resolveCommand under the internal WSL distro allowlist', () => { - it('unset: resolves exactly as with the distro allowlisted, without throwing', () => { - vi.stubEnv(ALLOWLIST, undefined) - const unset = [ - resolveCommand('git', ['status'], UBUNTU_REPO), - resolveCommand('gh', ['auth', 'status'], undefined, 'Ubuntu', { useWslLoginShell: true }), - resolveCommand('git', ['status'], 'C:\\repo') - ] - vi.stubEnv(ALLOWLIST, 'ubuntu') - const allowlisted = [ - resolveCommand('git', ['status'], UBUNTU_REPO), - resolveCommand('gh', ['auth', 'status'], undefined, 'Ubuntu', { useWslLoginShell: true }), - resolveCommand('git', ['status'], 'C:\\repo') - ] - - expect(unset).toEqual(allowlisted) - expect(unset[0]).toMatchObject({ binary: 'wsl.exe', wslMode: 'non-login-shell' }) - expect(unset[2]).toMatchObject({ binary: 'git', wsl: null }) - }) - it('refuses a WSL resolution into another distro, but never a Windows-host one', () => { vi.stubEnv(ALLOWLIST, 'orca-test-a') diff --git a/src/main/git/command-runner/wsl-command-resolution-object-store.test.ts b/src/main/git/command-runner/host-routing/wsl-command-resolution-object-store.test.ts similarity index 100% rename from src/main/git/command-runner/wsl-command-resolution-object-store.test.ts rename to src/main/git/command-runner/host-routing/wsl-command-resolution-object-store.test.ts diff --git a/src/main/git/command-runner/wsl-command-resolution.ts b/src/main/git/command-runner/host-routing/wsl-command-resolution.ts similarity index 91% rename from src/main/git/command-runner/wsl-command-resolution.ts rename to src/main/git/command-runner/host-routing/wsl-command-resolution.ts index b45fd0b660c..71f8aee3a42 100644 --- a/src/main/git/command-runner/wsl-command-resolution.ts +++ b/src/main/git/command-runner/host-routing/wsl-command-resolution.ts @@ -1,23 +1,23 @@ import { assertWslDistroAllowed } from '@orca/process-host/wsl-distro-allowlist' -import { getDefaultWslDistro } from '../../wsl/discovery/distro-catalog' -import { parseWslPath } from '../../wsl/filesystem/unc-path-access' -import type { WslUncPathInfo as WslPathInfo } from '../../../shared/wsl-paths' +import { getDefaultWslDistro } from '../../../wsl/discovery/distro-catalog' +import { parseWslPath } from '../../../wsl/filesystem/unc-path-access' +import type { WslUncPathInfo as WslPathInfo } from '../../../../shared/wsl-paths' import { buildWslCapturedLoginShellCommand, buildWslExecArgs, buildWslLoginShellCommand, type WslCapturedLoginShellCommand -} from '../../../shared/wsl-login-shell-command' -import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' -import { UNTRANSLATED_GIT_OUTPUT_ENV } from '../../../shared/git/commands/git-output-locale' -import type { WslGitReadEnvironment } from '../wsl-git-read-environment' +} from '../../../../shared/wsl-login-shell-command' +import { quotePosixShell } from '../../../../shared/shell/launch/shell-argument-quoting' +import { UNTRANSLATED_GIT_OUTPUT_ENV } from '../../../../shared/git/commands/git-output-locale' +import type { WslGitReadEnvironment } from '../../wsl-git-read-environment' import { createWslProcessGroupTermination, type WslProcessGroupTermination -} from '../wsl-process-group-termination' +} from '../../wsl-process-group-termination' import { translateArgForWsl, translateArgsForWsl } from './wsl-path-translation' -import { resolveWslInteropSpawnCwd } from '../../wsl/execution/wsl-interop-spawn-directory' -import { noteWslDistroLaunched } from '../../wsl/discovery/wsl-background-distro-gate' +import { resolveWslInteropSpawnCwd } from '../../../wsl/execution/wsl-interop-spawn-directory' +import { noteWslDistroLaunched } from '../../../wsl/discovery/wsl-background-distro-gate' // Carry Git locale pins in the WSL command; these assignment values are shell-safe. const GIT_OUTPUT_LOCALE_SHELL_PREFIX = Object.entries(UNTRANSLATED_GIT_OUTPUT_ENV) diff --git a/src/main/git/command-runner/wsl-host-failure.test.ts b/src/main/git/command-runner/host-routing/wsl-host-failure.test.ts similarity index 92% rename from src/main/git/command-runner/wsl-host-failure.test.ts rename to src/main/git/command-runner/host-routing/wsl-host-failure.test.ts index daa1a1285b9..217a59384ba 100644 --- a/src/main/git/command-runner/wsl-host-failure.test.ts +++ b/src/main/git/command-runner/host-routing/wsl-host-failure.test.ts @@ -8,14 +8,14 @@ vi.mock('node:child_process', () => ({ execFileSync: vi.fn(), spawn: vi.fn() })) -vi.mock('../../observability/instrumentation', () => ({ +vi.mock('../../../observability/instrumentation', () => ({ withGitSpan: (_attributes: unknown, run: (span: unknown) => unknown) => run({ setAttribute: () => {} }) })) -vi.mock('../../diagnostics/main-thread-churn-probe', () => ({ recordSubprocessSpawn: vi.fn() })) +vi.mock('../../../diagnostics/main-thread-churn-probe', () => ({ recordSubprocessSpawn: vi.fn() })) -import { gitExecFileAsync } from '../runner' -import { _resetGitAdmissionForTests } from './git-subprocess-admission' +import { gitExecFileAsync } from '../git-exec-file' +import { _resetGitAdmissionForTests } from '../admission/git-subprocess-admission' import { readWslHostFailureDiagnostic } from './wsl-host-failure' import type { ResolvedCommand } from './wsl-command-resolution' diff --git a/src/main/git/command-runner/wsl-host-failure.ts b/src/main/git/command-runner/host-routing/wsl-host-failure.ts similarity index 97% rename from src/main/git/command-runner/wsl-host-failure.ts rename to src/main/git/command-runner/host-routing/wsl-host-failure.ts index 6fac413652c..2a6216417d1 100644 --- a/src/main/git/command-runner/wsl-host-failure.ts +++ b/src/main/git/command-runner/host-routing/wsl-host-failure.ts @@ -1,7 +1,7 @@ import { isWslHostFailureExitCode, readWslHostDiagnostic -} from '../../wsl/execution/wsl-process-failure' +} from '../../../wsl/execution/wsl-process-failure' import type { ResolvedCommand } from './wsl-command-resolution' function outputText(value: unknown): string { diff --git a/src/main/git/command-runner/wsl-linked-worktree-git-route-probe.ts b/src/main/git/command-runner/host-routing/wsl-linked-worktree-git-route-probe.ts similarity index 100% rename from src/main/git/command-runner/wsl-linked-worktree-git-route-probe.ts rename to src/main/git/command-runner/host-routing/wsl-linked-worktree-git-route-probe.ts diff --git a/src/main/git/command-runner/wsl-linked-worktree-git-routing.ts b/src/main/git/command-runner/host-routing/wsl-linked-worktree-git-routing.ts similarity index 100% rename from src/main/git/command-runner/wsl-linked-worktree-git-routing.ts rename to src/main/git/command-runner/host-routing/wsl-linked-worktree-git-routing.ts diff --git a/src/main/git/command-runner/wsl-path-translation.ts b/src/main/git/command-runner/host-routing/wsl-path-translation.ts similarity index 87% rename from src/main/git/command-runner/wsl-path-translation.ts rename to src/main/git/command-runner/host-routing/wsl-path-translation.ts index 5538e91aa36..4c87e843684 100644 --- a/src/main/git/command-runner/wsl-path-translation.ts +++ b/src/main/git/command-runner/host-routing/wsl-path-translation.ts @@ -1,5 +1,9 @@ -import { isDrvfsLinuxPath, toWindowsWslPath, toWindowsWslUncPath } from '../../../shared/wsl-paths' -import { parseWslPath } from '../../wsl/filesystem/unc-path-access' +import { + isDrvfsLinuxPath, + toWindowsWslPath, + toWindowsWslUncPath +} from '../../../../shared/wsl-paths' +import { parseWslPath } from '../../../wsl/filesystem/unc-path-access' /** Windows arguments need Linux spellings for WSL Git: UNC paths become native and drives map under /mnt. */ export function translateArgsForWsl(args: string[]): string[] { diff --git a/src/main/git/command-runner/default-wsl-cli-fallback.ts b/src/main/git/command-runner/hosted-cli/default-wsl-cli-fallback.ts similarity index 88% rename from src/main/git/command-runner/default-wsl-cli-fallback.ts rename to src/main/git/command-runner/hosted-cli/default-wsl-cli-fallback.ts index a963602813c..e8aed6f104b 100644 --- a/src/main/git/command-runner/default-wsl-cli-fallback.ts +++ b/src/main/git/command-runner/hosted-cli/default-wsl-cli-fallback.ts @@ -1,14 +1,14 @@ -import { blockedWslDistroForExec } from '../../wsl/discovery/wsl-background-exec-gate' +import { blockedWslDistroForExec } from '../../../wsl/discovery/wsl-background-exec-gate' import { runAsWslUserAct, WslDistroStoppedError, WslDistroUnverifiableError -} from '../../wsl/filesystem/wsl-unc-access-gate' +} from '../../../wsl/filesystem/wsl-unc-access-gate' import { defaultWslCliDistro, resolveDefaultWslCli, type ResolvedCommand -} from './wsl-command-resolution' +} from '../host-routing/wsl-command-resolution' /** * The default distro's gh/glab for a cwd-less call whose host CLI is missing. Background work must diff --git a/src/main/git/command-runner/gh-bound-account-env.ts b/src/main/git/command-runner/hosted-cli/gh-bound-account-env.ts similarity index 90% rename from src/main/git/command-runner/gh-bound-account-env.ts rename to src/main/git/command-runner/hosted-cli/gh-bound-account-env.ts index c1fcb1564f2..d2d7766f430 100644 --- a/src/main/git/command-runner/gh-bound-account-env.ts +++ b/src/main/git/command-runner/hosted-cli/gh-bound-account-env.ts @@ -1,7 +1,7 @@ -import { normalizeGhAccountBinding } from '../../../shared/github/account-binding' +import { normalizeGhAccountBinding } from '../../../../shared/github/account-binding' import type { GhExecOptions } from './gh-exec-file' import { collectGhArgvHostSignals } from './gh-host-args' -import type { ResolvedCommand } from './wsl-command-resolution' +import type { ResolvedCommand } from '../host-routing/wsl-command-resolution' import type { GhCaptureLifetimeHooks } from './gh-capture-lifetime' const GH_BOUND_ACCOUNT_ERROR_CODES = new Set([ @@ -38,7 +38,7 @@ export async function resolveBoundGhExecEnv( createGhBoundAccountHostMismatchError, createGhBoundAccountUnavailableError, resolveGhAccountToken - } = await import('../../github/gh-account-token') + } = await import('../../../github/gh-account-token') const normalized = normalizeGhAccountBinding(binding) if (!normalized) { throw createGhBoundAccountUnavailableError(binding) diff --git a/src/main/git/command-runner/gh-capture-lifetime.ts b/src/main/git/command-runner/hosted-cli/gh-capture-lifetime.ts similarity index 97% rename from src/main/git/command-runner/gh-capture-lifetime.ts rename to src/main/git/command-runner/hosted-cli/gh-capture-lifetime.ts index 812f1c2f4e1..bf2dc335c2d 100644 --- a/src/main/git/command-runner/gh-capture-lifetime.ts +++ b/src/main/git/command-runner/hosted-cli/gh-capture-lifetime.ts @@ -1,4 +1,4 @@ -import { createAbortError } from './abort-error' +import { createAbortError } from '../process-capture/abort-error' export type GhCaptureLifetimeHooks = { onTerminationPending: (terminated: Promise) => void diff --git a/src/main/git/command-runner/gh-exec-file-deadline.test.ts b/src/main/git/command-runner/hosted-cli/gh-exec-file-deadline.test.ts similarity index 96% rename from src/main/git/command-runner/gh-exec-file-deadline.test.ts rename to src/main/git/command-runner/hosted-cli/gh-exec-file-deadline.test.ts index a9394f97a1d..c9b6f004d54 100644 --- a/src/main/git/command-runner/gh-exec-file-deadline.test.ts +++ b/src/main/git/command-runner/hosted-cli/gh-exec-file-deadline.test.ts @@ -1,6 +1,6 @@ import type { ChildProcess } from 'node:child_process' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { createFakeSpawnedChild } from '../../../shared/__fixtures__/fake-spawned-child' +import { createFakeSpawnedChild } from '../../../../shared/__fixtures__/fake-spawned-child' const { spawnMock, processKillMock } = vi.hoisted(() => ({ spawnMock: vi.fn(), diff --git a/src/main/git/command-runner/gh-exec-file-lifetime.test.ts b/src/main/git/command-runner/hosted-cli/gh-exec-file-lifetime.test.ts similarity index 94% rename from src/main/git/command-runner/gh-exec-file-lifetime.test.ts rename to src/main/git/command-runner/hosted-cli/gh-exec-file-lifetime.test.ts index 91227bfc3b6..d7193e952e7 100644 --- a/src/main/git/command-runner/gh-exec-file-lifetime.test.ts +++ b/src/main/git/command-runner/hosted-cli/gh-exec-file-lifetime.test.ts @@ -1,5 +1,5 @@ import type { ChildProcess } from 'node:child_process' -import { createFakeSpawnedChild } from '../../../shared/__fixtures__/fake-spawned-child' +import { createFakeSpawnedChild } from '../../../../shared/__fixtures__/fake-spawned-child' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const { spawnMock, signalMock, forceMock, resolveSelectedMock } = vi.hoisted(() => ({ @@ -13,7 +13,7 @@ vi.mock('@orca/process-host/process-tree-termination', () => ({ signalProcessTree: signalMock, forceTerminateProcessTree: forceMock })) -vi.mock('../../ipc/command-path/command-path-resolver', () => ({ +vi.mock('../../../ipc/command-path/command-path-resolver', () => ({ resolveSelectedLocalCommand: resolveSelectedMock })) diff --git a/src/main/git/command-runner/gh-exec-file.ts b/src/main/git/command-runner/hosted-cli/gh-exec-file.ts similarity index 96% rename from src/main/git/command-runner/gh-exec-file.ts rename to src/main/git/command-runner/hosted-cli/gh-exec-file.ts index 9eb9b7c973a..2998b0966cb 100644 --- a/src/main/git/command-runner/gh-exec-file.ts +++ b/src/main/git/command-runner/hosted-cli/gh-exec-file.ts @@ -8,18 +8,18 @@ import { isGhRateLimitProbe, notifyGhPrimaryRateLimit, type GhRateLimitBucket -} from '../gh-rate-limit-breaker' -import { extractExecError, parseRetryAfterMs } from '../exec-error' -import { resolveCommand, type ResolvedCommand } from './wsl-command-resolution' +} from '../../gh-rate-limit-breaker' +import { extractExecError, parseRetryAfterMs } from '../../exec-error' +import { resolveCommand, type ResolvedCommand } from '../host-routing/wsl-command-resolution' import { resolveDefaultWslCliFallback } from './default-wsl-cli-fallback' import { canFallBackToHostGitHubCli, isHostCommandMissing, resolveHostGitHubCli } from './github-cli-host-fallback' -import { execFileCaptureToTermination } from './exec-file-capture' +import { execFileCaptureToTermination } from '../process-capture/exec-file-capture' import { logHostedCliDeadlineKill } from './hosted-cli-deadline-log' -import type { GitExecOptions } from './git-exec-options' +import type { GitExecOptions } from '../git-exec-options' import { argsLookIdempotent } from './gh-idempotency' import { GhExecutableAbsenceBatch } from './gh-executable-absence-batch' import { applyGhHostToArgs, explicitGhHostname, explicitGhRepoHostname } from './gh-host-args' diff --git a/src/main/git/command-runner/gh-executable-absence-batch.ts b/src/main/git/command-runner/hosted-cli/gh-executable-absence-batch.ts similarity index 96% rename from src/main/git/command-runner/gh-executable-absence-batch.ts rename to src/main/git/command-runner/hosted-cli/gh-executable-absence-batch.ts index a2362641c3a..63ab1634e10 100644 --- a/src/main/git/command-runner/gh-executable-absence-batch.ts +++ b/src/main/git/command-runner/hosted-cli/gh-executable-absence-batch.ts @@ -4,8 +4,8 @@ import path from 'node:path' import { isCommandOnLocalPath, resolveSelectedLocalCommand -} from '../../ipc/command-path/command-path-resolver' -import type { ResolvedCommand } from './wsl-command-resolution' +} from '../../../ipc/command-path/command-path-resolver' +import type { ResolvedCommand } from '../host-routing/wsl-command-resolution' const currentBatch = new AsyncLocalStorage() const batches = new Set() diff --git a/src/main/git/command-runner/gh-host-args.ts b/src/main/git/command-runner/hosted-cli/gh-host-args.ts similarity index 100% rename from src/main/git/command-runner/gh-host-args.ts rename to src/main/git/command-runner/hosted-cli/gh-host-args.ts diff --git a/src/main/git/command-runner/gh-idempotency.ts b/src/main/git/command-runner/hosted-cli/gh-idempotency.ts similarity index 100% rename from src/main/git/command-runner/gh-idempotency.ts rename to src/main/git/command-runner/hosted-cli/gh-idempotency.ts diff --git a/src/main/git/command-runner/gh-retry-policy.ts b/src/main/git/command-runner/hosted-cli/gh-retry-policy.ts similarity index 93% rename from src/main/git/command-runner/gh-retry-policy.ts rename to src/main/git/command-runner/hosted-cli/gh-retry-policy.ts index 1a8ab117998..3de5454c22f 100644 --- a/src/main/git/command-runner/gh-retry-policy.ts +++ b/src/main/git/command-runner/hosted-cli/gh-retry-policy.ts @@ -1,5 +1,5 @@ -import { parseRetryAfterMs } from '../exec-error' -import { createAbortError } from './abort-error' +import { parseRetryAfterMs } from '../../exec-error' +import { createAbortError } from '../process-capture/abort-error' /** Retry 5xx/resets and 429 without Retry-After; propagate explicit waits and primary 403s. */ export function isTransientGhError(stderr: string): boolean { diff --git a/src/main/git/command-runner/github-cli-host-fallback.ts b/src/main/git/command-runner/hosted-cli/github-cli-host-fallback.ts similarity index 97% rename from src/main/git/command-runner/github-cli-host-fallback.ts rename to src/main/git/command-runner/hosted-cli/github-cli-host-fallback.ts index 14cdec84dea..0166a8804ec 100644 --- a/src/main/git/command-runner/github-cli-host-fallback.ts +++ b/src/main/git/command-runner/hosted-cli/github-cli-host-fallback.ts @@ -1,4 +1,4 @@ -import type { ResolvedCommand } from './wsl-command-resolution' +import type { ResolvedCommand } from '../host-routing/wsl-command-resolution' function hasExplicitRepoArg(args: string[]): boolean { for (let i = 0; i < args.length; i++) { diff --git a/src/main/git/command-runner/glab-exec-file.ts b/src/main/git/command-runner/hosted-cli/glab-exec-file.ts similarity index 91% rename from src/main/git/command-runner/glab-exec-file.ts rename to src/main/git/command-runner/hosted-cli/glab-exec-file.ts index 088064440a3..bcd6dac3673 100644 --- a/src/main/git/command-runner/glab-exec-file.ts +++ b/src/main/git/command-runner/hosted-cli/glab-exec-file.ts @@ -1,11 +1,11 @@ -import { addWslEnvKeys } from '../../../shared/wsl-env' -import { extractExecError, parseRetryAfterMs } from '../exec-error' -import { resolveCommand } from './wsl-command-resolution' +import { addWslEnvKeys } from '../../../../shared/wsl-env' +import { extractExecError, parseRetryAfterMs } from '../../exec-error' +import { resolveCommand } from '../host-routing/wsl-command-resolution' import { resolveDefaultWslCliFallback } from './default-wsl-cli-fallback' import { isHostCommandMissing } from './github-cli-host-fallback' -import { execFileCaptureToTermination } from './exec-file-capture' +import { execFileCaptureToTermination } from '../process-capture/exec-file-capture' import { logHostedCliDeadlineKill } from './hosted-cli-deadline-log' -import type { GitExecOptions } from './git-exec-options' +import type { GitExecOptions } from '../git-exec-options' import { argsLookIdempotent } from './gh-idempotency' import { isTransientGhError, diff --git a/src/main/git/command-runner/hosted-cli-deadline-log.ts b/src/main/git/command-runner/hosted-cli/hosted-cli-deadline-log.ts similarity index 100% rename from src/main/git/command-runner/hosted-cli-deadline-log.ts rename to src/main/git/command-runner/hosted-cli/hosted-cli-deadline-log.ts diff --git a/src/main/git/command-runner/missing-git-spawn-cwd.test.ts b/src/main/git/command-runner/missing-git-spawn-cwd.test.ts deleted file mode 100644 index 71fc5b9dcd6..00000000000 --- a/src/main/git/command-runner/missing-git-spawn-cwd.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { mkdir, mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import path from 'node:path' -import type * as ChildProcessModule from 'node:child_process' -import { afterEach, expect, it, vi } from 'vitest' - -const { execFileSpy } = vi.hoisted(() => ({ execFileSpy: vi.fn() })) - -vi.mock('node:child_process', async (importOriginal) => { - const actual = await importOriginal() - execFileSpy.mockImplementation(actual.execFile) - return { ...actual, execFile: execFileSpy } -}) - -import { gitExecFileAsync } from './git-exec-file' - -let root: string | null = null - -afterEach(async () => { - if (root) { - await rm(root, { recursive: true, force: true }) - } -}) - -it('stops spawning Git in a deleted folder and resumes once it returns', async () => { - root = await mkdtemp(path.join(tmpdir(), 'orca-missing-git-cwd-')) - const cwd = path.join(root, 'repo') - vi.spyOn(console, 'warn').mockImplementation(() => {}) - - await expect(gitExecFileAsync(['status'], { cwd })).rejects.toMatchObject({ code: 'ENOENT' }) - expect(execFileSpy).toHaveBeenCalledTimes(1) - - await expect(gitExecFileAsync(['status'], { cwd })).rejects.toMatchObject({ - code: 'ENOENT', - syscall: 'spawn git' - }) - expect(execFileSpy).toHaveBeenCalledTimes(1) - - await mkdir(cwd) - await gitExecFileAsync(['status'], { cwd }).catch(() => undefined) - expect(execFileSpy).toHaveBeenCalledTimes(2) -}) diff --git a/src/main/git/command-runner/abort-error.ts b/src/main/git/command-runner/process-capture/abort-error.ts similarity index 100% rename from src/main/git/command-runner/abort-error.ts rename to src/main/git/command-runner/process-capture/abort-error.ts diff --git a/src/main/git/command-runner/captured-git-output.ts b/src/main/git/command-runner/process-capture/captured-git-output.ts similarity index 93% rename from src/main/git/command-runner/captured-git-output.ts rename to src/main/git/command-runner/process-capture/captured-git-output.ts index eeffdb9b379..cfcc55834b8 100644 --- a/src/main/git/command-runner/captured-git-output.ts +++ b/src/main/git/command-runner/process-capture/captured-git-output.ts @@ -1,4 +1,4 @@ -import type { ResolvedCommand } from './wsl-command-resolution' +import type { ResolvedCommand } from '../host-routing/wsl-command-resolution' /** Find fences in bytes to preserve binary blobs; return untouched output if no fence is found. */ export function readCapturedGitBuffer(stdout: Buffer, resolved: ResolvedCommand): Buffer { diff --git a/src/main/git/command-runner/command-exec-file.ts b/src/main/git/command-runner/process-capture/command-exec-file.ts similarity index 85% rename from src/main/git/command-runner/command-exec-file.ts rename to src/main/git/command-runner/process-capture/command-exec-file.ts index 46e5c69bf9b..e1a60cc1b1c 100644 --- a/src/main/git/command-runner/command-exec-file.ts +++ b/src/main/git/command-runner/process-capture/command-exec-file.ts @@ -1,7 +1,7 @@ -import { isWindowsBatchScript } from '../../../shared/windows-batch-spawn' -import { resolveWindowsCommand } from '../../windows/windows-command-paths' -import { isMissingCommandBinaryError } from '../exec-error' -import { resolveCommand, type ResolvedCommand } from './wsl-command-resolution' +import { isWindowsBatchScript } from '../../../../shared/windows-batch-spawn' +import { resolveWindowsCommand } from '../../../windows/windows-command-paths' +import { isMissingCommandBinaryError } from '../../exec-error' +import { resolveCommand, type ResolvedCommand } from '../host-routing/wsl-command-resolution' import { execFileCapture } from './exec-file-capture' import { spawnCommandCapture, type CommandExecOptions } from './spawn-command-capture' diff --git a/src/main/git/command-runner/exec-file-capture-bytes.test.ts b/src/main/git/command-runner/process-capture/exec-file-capture-bytes.test.ts similarity index 63% rename from src/main/git/command-runner/exec-file-capture-bytes.test.ts rename to src/main/git/command-runner/process-capture/exec-file-capture-bytes.test.ts index 38a9d32294a..8903f3229a8 100644 --- a/src/main/git/command-runner/exec-file-capture-bytes.test.ts +++ b/src/main/git/command-runner/process-capture/exec-file-capture-bytes.test.ts @@ -1,6 +1,6 @@ -import { describe, expect, it, vi } from 'vitest' +import { describe, expect, it } from 'vitest' import { execFileCaptureToTermination } from './exec-file-capture' -import { createWslProcessGroupTermination } from '../wsl-process-group-termination' +import { createWslProcessGroupTermination } from '../../wsl-process-group-termination' const stdout = Buffer.from([0, 255, 128, 10]) const stderr = Buffer.from([128, 255, 0, 10]) @@ -62,36 +62,4 @@ describe('termination-barrier binary output', () => { ) ).resolves.toEqual({ stdout, stderr: Buffer.concat([stderr, Buffer.from([255, 128])]) }) }) - - it.each(['abort', 'timeout'] as const)( - 'retains raw output after %s and reports termination', - async (mode) => { - const controller = new AbortController() - const onChildTerminated = vi.fn() - const timeoutError = new Error('byte capture deadline') - const pending = execFileCaptureToTermination( - process.execPath, - ['-e', `${writeBytes}setInterval(()=>{},1000)`], - { - encoding: 'buffer', - timeout: mode === 'timeout' ? 200 : 2_000, - signal: controller.signal, - onChildTerminated, - createTimeoutError: () => timeoutError - } - ) - const rejection = expect(pending).rejects.toMatchObject({ - ...(mode === 'abort' ? { name: 'AbortError' } : { message: timeoutError.message }), - stdout, - stderr - }) - const timer = mode === 'abort' ? setTimeout(() => controller.abort(), 200) : undefined - try { - await rejection - await vi.waitFor(() => expect(onChildTerminated).toHaveBeenCalledOnce()) - } finally { - clearTimeout(timer) - } - } - ) }) diff --git a/src/main/git/command-runner/exec-file-capture-stdin.test.ts b/src/main/git/command-runner/process-capture/exec-file-capture-stdin.test.ts similarity index 78% rename from src/main/git/command-runner/exec-file-capture-stdin.test.ts rename to src/main/git/command-runner/process-capture/exec-file-capture-stdin.test.ts index 22e3e2794b8..8ca7c108eea 100644 --- a/src/main/git/command-runner/exec-file-capture-stdin.test.ts +++ b/src/main/git/command-runner/process-capture/exec-file-capture-stdin.test.ts @@ -18,19 +18,6 @@ describe.each([ expect(result).toEqual({ stdout: JSON.stringify({ input: '' }), stderr: '' }) }) - - it.each(['', 'commit message\nλ\n'.repeat(10_000)])( - 'delivers explicit stdin completely before EOF (%#)', - async (input) => { - const result = await capture(process.execPath, readStdin, { - encoding: 'utf8', - stdin: input, - timeout: 3_000 - }) - - expect(result).toEqual({ stdout: JSON.stringify({ input }), stderr: '' }) - } - ) }) it('delivers non-UTF8 image bytes unchanged through the termination barrier', async () => { diff --git a/src/main/git/command-runner/exec-file-capture.ts b/src/main/git/command-runner/process-capture/exec-file-capture.ts similarity index 93% rename from src/main/git/command-runner/exec-file-capture.ts rename to src/main/git/command-runner/process-capture/exec-file-capture.ts index 89edb391bd3..ac51b15a605 100644 --- a/src/main/git/command-runner/exec-file-capture.ts +++ b/src/main/git/command-runner/process-capture/exec-file-capture.ts @@ -1,15 +1,16 @@ import { execFile, type ChildProcess, type ExecFileOptions } from 'node:child_process' -import { recordSubprocessSpawn } from '../../diagnostics/main-thread-churn-probe' -import { endSubprocessStdin } from '../../../shared/subprocess-stdin-write' +import { recordSubprocessSpawn } from '../../../diagnostics/main-thread-churn-probe' +import { endSubprocessStdin } from '../../../../shared/subprocess-stdin-write' import { runProcess } from '@orca/process-host' -import { resolveSelectedLocalCommand } from '../../ipc/command-path/command-path-resolver' -import type { WslProcessGroupTermination } from '../wsl-process-group-termination' +import { resolveSelectedLocalCommand } from '../../../ipc/command-path/command-path-resolver' +import type { WslProcessGroupTermination } from '../../wsl-process-group-termination' import { createAbortError } from './abort-error' import { killSpawnedCommandTree } from './spawned-command-tree-kill' -import { DEFAULT_GIT_MAX_BUFFER, type GitAdmissionTier } from './git-exec-options' +import { DEFAULT_GIT_MAX_BUFFER } from '../git-exec-options' +import type { GitAdmissionTier } from '../../../../shared/rpc-contract/git-admission-tier-params' import { workerExecFile } from './worker-exec-file' -import type { WorkerThreadChildProcess } from '../../worker-thread-child-process/worker-thread-child-process' +import type { WorkerThreadChildProcess } from '../../../worker-thread-child-process/worker-thread-child-process' type ExecFileCaptureOptions = Omit & { timeout?: number diff --git a/src/main/git/command-runner/spawn-command-capture.ts b/src/main/git/command-runner/process-capture/spawn-command-capture.ts similarity index 95% rename from src/main/git/command-runner/spawn-command-capture.ts rename to src/main/git/command-runner/process-capture/spawn-command-capture.ts index fc7c4900904..5f0049ff5b1 100644 --- a/src/main/git/command-runner/spawn-command-capture.ts +++ b/src/main/git/command-runner/process-capture/spawn-command-capture.ts @@ -1,6 +1,6 @@ import { spawn } from 'node:child_process' -import { recordSubprocessSpawn } from '../../diagnostics/main-thread-churn-probe' -import { getSpawnArgsForWindows } from '../../../shared/windows-batch-spawn' +import { recordSubprocessSpawn } from '../../../diagnostics/main-thread-churn-probe' +import { getSpawnArgsForWindows } from '../../../../shared/windows-batch-spawn' import { createAbortError } from './abort-error' import { killSpawnedCommandTree } from './spawned-command-tree-kill' diff --git a/src/main/git/command-runner/spawned-command-tree-kill.test.ts b/src/main/git/command-runner/process-capture/spawned-command-tree-kill.test.ts similarity index 97% rename from src/main/git/command-runner/spawned-command-tree-kill.test.ts rename to src/main/git/command-runner/process-capture/spawned-command-tree-kill.test.ts index bd9085976a4..1f4f9e7854b 100644 --- a/src/main/git/command-runner/spawned-command-tree-kill.test.ts +++ b/src/main/git/command-runner/process-capture/spawned-command-tree-kill.test.ts @@ -13,7 +13,7 @@ vi.mock('node:child_process', async (importOriginal) => ({ ...(await importOriginal()), spawn: spawnMock })) -vi.mock('../../pty/process-retirement/own-chromium-tree-kill-guard', () => ({ +vi.mock('../../../pty/process-retirement/own-chromium-tree-kill-guard', () => ({ admitSelfInitiatedTreeKill: admitMock })) diff --git a/src/main/git/command-runner/spawned-command-tree-kill.ts b/src/main/git/command-runner/process-capture/spawned-command-tree-kill.ts similarity index 94% rename from src/main/git/command-runner/spawned-command-tree-kill.ts rename to src/main/git/command-runner/process-capture/spawned-command-tree-kill.ts index 2f595d03b30..63429b8253b 100644 --- a/src/main/git/command-runner/spawned-command-tree-kill.ts +++ b/src/main/git/command-runner/process-capture/spawned-command-tree-kill.ts @@ -1,5 +1,5 @@ import { spawn, type ChildProcess } from 'node:child_process' -import { admitSelfInitiatedTreeKill } from '../../pty/process-retirement/own-chromium-tree-kill-guard' +import { admitSelfInitiatedTreeKill } from '../../../pty/process-retirement/own-chromium-tree-kill-guard' const WINDOWS_TREE_KILL_WAIT_MS = 2_000 diff --git a/src/main/git/command-runner/worker-exec-file.test.ts b/src/main/git/command-runner/process-capture/worker-exec-file.test.ts similarity index 79% rename from src/main/git/command-runner/worker-exec-file.test.ts rename to src/main/git/command-runner/process-capture/worker-exec-file.test.ts index 0b3b2b8ecab..73bbe5e2773 100644 --- a/src/main/git/command-runner/worker-exec-file.test.ts +++ b/src/main/git/command-runner/process-capture/worker-exec-file.test.ts @@ -1,9 +1,9 @@ import { setImmediate as nextTurn } from 'node:timers/promises' import { Worker } from 'node:worker_threads' import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' -import type * as WorkerChildModule from '../../worker-thread-child-process/worker-thread-child-process' -import type { WorkerThreadChildProcessHost } from '../../worker-thread-child-process/worker-thread-child-process' -import { createWorkerThreadChildProcessTestEntry } from '../../worker-thread-child-process/worker-thread-child-process-worker.test-fixtures' +import type * as WorkerChildModule from '../../../worker-thread-child-process/worker-thread-child-process' +import type { WorkerThreadChildProcessHost } from '../../../worker-thread-child-process/worker-thread-child-process' +import { createWorkerThreadChildProcessTestEntry } from '../../../worker-thread-child-process/worker-thread-child-process-worker.test-fixtures' import { workerExecFile } from './worker-exec-file' import { execFileCapture } from './exec-file-capture' @@ -11,7 +11,7 @@ const state = vi.hoisted(() => { const state: { host: WorkerThreadChildProcessHost | null } = { host: null } return state }) -vi.mock('../../worker-thread-child-process/worker-thread-child-process', async (original) => ({ +vi.mock('../../../worker-thread-child-process/worker-thread-child-process', async (original) => ({ ...(await original()), spawnProcessOnWorkerThread: (spec: Parameters[0]) => { if (!state.host) { @@ -37,7 +37,7 @@ afterAll(async () => { async function createHost(gate?: SharedArrayBuffer) { const { WorkerThreadChildProcessHost } = - await import('../../worker-thread-child-process/worker-thread-child-process') + await import('../../../worker-thread-child-process/worker-thread-child-process') state.host = new WorkerThreadChildProcessHost(() => { // Hold this worker synchronously before process creation; the UI loop must still turn. const worker = gate @@ -122,30 +122,6 @@ describe('worker-owned Git capture', () => { }) }) -describe.skipIf(process.platform !== 'darwin')('macOS worker capture stdin', () => { - it.each([undefined, '', 'commit message\nλ\n'.repeat(10_000)])( - 'delivers stdin completely before EOF (%#)', - async (input) => { - await createHost() - const result = await execFileCapture( - process.execPath, - [ - '-e', - 'process.stdin.setEncoding("utf8"); let input = ""; process.stdin.on("data", chunk => { input += chunk }); process.stdin.on("end", () => { process.stdout.write(JSON.stringify({ input })) })' - ], - { - encoding: 'utf8', - timeout: 3_000, - spawnOnWorkerThread: true, - ...(input === undefined ? {} : { stdin: input }) - } - ) - - expect(result).toEqual({ stdout: JSON.stringify({ input: input ?? '' }), stderr: '' }) - } - ) -}) - describe.skipIf(process.platform !== 'darwin')('macOS worker capture cancellation', () => { it('does not report a queued child terminated until the worker processes its kill', async () => { const gate = new SharedArrayBuffer(4) diff --git a/src/main/git/command-runner/worker-exec-file.ts b/src/main/git/command-runner/process-capture/worker-exec-file.ts similarity index 92% rename from src/main/git/command-runner/worker-exec-file.ts rename to src/main/git/command-runner/process-capture/worker-exec-file.ts index fd61e5e1034..ae4a36b2248 100644 --- a/src/main/git/command-runner/worker-exec-file.ts +++ b/src/main/git/command-runner/process-capture/worker-exec-file.ts @@ -1,7 +1,7 @@ import { createOutputSink } from '@orca/process-host/bounded-output-sink' import { fileURLToPath } from 'node:url' -import { spawnProcessOnWorkerThread } from '../../worker-thread-child-process/worker-thread-child-process' -import type { WorkerThreadChildProcess } from '../../worker-thread-child-process/worker-thread-child-process' +import { spawnProcessOnWorkerThread } from '../../../worker-thread-child-process/worker-thread-child-process' +import type { WorkerThreadChildProcess } from '../../../worker-thread-child-process/worker-thread-child-process' /** Capture a worker-owned child; the caller still owns deadlines and aborts. */ export function workerExecFile( diff --git a/src/main/git/command-runner/wsl-linked-worktree-git-route-invalidation.test.ts b/src/main/git/command-runner/wsl-linked-worktree-git-route-invalidation.test.ts deleted file mode 100644 index 2f4117bd6cd..00000000000 --- a/src/main/git/command-runner/wsl-linked-worktree-git-route-invalidation.test.ts +++ /dev/null @@ -1,108 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { - invalidateWslLinkedWorktreeGitRouting, - prepareWslLinkedWorktreeGitRouting, - resetWslLinkedWorktreeGitRoutingForTests -} from './wsl-linked-worktree-git-routing' -import type { WslLinkedWorktreeRoutingFileSystem } from './wsl-linked-worktree-git-route-probe' - -afterEach(() => resetWslLinkedWorktreeGitRoutingForTests()) - -const CWD = String.raw`C:\repo` -const fileMarker = { isDirectory: () => false, isFile: () => true } -const directoryMarker = { isDirectory: () => true, isFile: () => false } -const hostGitdir = 'gitdir: C:/main/.git/worktrees/linked\n' - -function prepare(fileSystem: WslLinkedWorktreeRoutingFileSystem): Promise { - return prepareWslLinkedWorktreeGitRouting(CWD, 'Ubuntu', { platform: 'win32', fileSystem }) -} - -describe('invalidateWslLinkedWorktreeGitRouting', () => { - it('re-probes a settled route after the worktree marker is rewritten', async () => { - const fileSystem: WslLinkedWorktreeRoutingFileSystem = { - stat: vi - .fn() - .mockResolvedValueOnce(directoryMarker) - .mockResolvedValueOnce(fileMarker), - readFile: vi.fn(async () => hostGitdir) - } - - await expect(prepare(fileSystem)).resolves.toBe(false) - invalidateWslLinkedWorktreeGitRouting(CWD) - - await expect(prepare(fileSystem)).resolves.toBe(true) - expect(fileSystem.stat).toHaveBeenCalledTimes(2) - }) - - it('clears the retry backoff so a marker that just appeared is probed immediately', async () => { - const currentTime = 1_000 - let markerExists = false - const fileSystem: WslLinkedWorktreeRoutingFileSystem = { - stat: vi.fn(async () => { - if (!markerExists) { - throw Object.assign(new Error('device unavailable'), { code: 'EIO' }) - } - return fileMarker - }), - readFile: vi.fn(async () => hostGitdir) - } - const probe = (): Promise => - prepareWslLinkedWorktreeGitRouting(CWD, 'Ubuntu', { - platform: 'win32', - fileSystem, - now: () => currentTime - }) - - // The second miss enters the exponential retry window, so the third never probes. - await expect(probe()).resolves.toBe(false) - await expect(probe()).resolves.toBe(false) - await expect(probe()).resolves.toBe(false) - expect(fileSystem.stat).toHaveBeenCalledTimes(2) - - markerExists = true - invalidateWslLinkedWorktreeGitRouting(CWD) - await expect(probe()).resolves.toBe(true) - expect(fileSystem.stat).toHaveBeenCalledTimes(3) - }) - - it('drops routes cached for paths inside the mutated worktree', async () => { - const submodule = String.raw`C:\repo\sub` - const sibling = String.raw`C:\repo-other` - const fileSystem: WslLinkedWorktreeRoutingFileSystem = { - stat: vi.fn(async () => fileMarker), - readFile: vi.fn(async () => hostGitdir) - } - const probe = (cwd: string): Promise => - prepareWslLinkedWorktreeGitRouting(cwd, 'Ubuntu', { platform: 'win32', fileSystem }) - - await expect(probe(submodule)).resolves.toBe(true) - await expect(probe(sibling)).resolves.toBe(true) - invalidateWslLinkedWorktreeGitRouting(CWD) - - // Sibling prefixes must not be mistaken for descendants. - await expect(probe(submodule)).resolves.toBe(true) - await expect(probe(sibling)).resolves.toBe(true) - expect(fileSystem.stat).toHaveBeenCalledTimes(3) - }) - - it('leaves a probe that is already in flight alone', async () => { - // In-flight probes must still cache their route before synchronous command resolution reads it. - let releaseMarker: ((marker: typeof fileMarker) => void) | undefined - const inFlight = new Promise((resolve) => { - releaseMarker = resolve - }) - const fileSystem: WslLinkedWorktreeRoutingFileSystem = { - stat: vi.fn().mockReturnValueOnce(inFlight), - readFile: vi.fn(async () => hostGitdir) - } - - const first = prepare(fileSystem) - invalidateWslLinkedWorktreeGitRouting(CWD) - const joined = prepare(fileSystem) - releaseMarker?.(fileMarker) - - await expect(first).resolves.toBe(true) - await expect(joined).resolves.toBe(true) - expect(fileSystem.stat).toHaveBeenCalledTimes(1) - }) -}) diff --git a/src/main/git/command-runner/wsl-service-failure-direct-git.test.ts b/src/main/git/command-runner/wsl-service-failure-direct-git.test.ts deleted file mode 100644 index 3dfe397e492..00000000000 --- a/src/main/git/command-runner/wsl-service-failure-direct-git.test.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { EventEmitter } from 'node:events' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { execFileMock } = vi.hoisted(() => ({ execFileMock: vi.fn() })) - -vi.mock('node:child_process', () => ({ - execFile: execFileMock, - execFileSync: vi.fn(), - spawn: vi.fn() -})) -vi.mock('../../observability/instrumentation', () => ({ - withGitSpan: (_attributes: unknown, run: (span: unknown) => unknown) => - run({ setAttribute: () => {} }) -})) -vi.mock('../../diagnostics/main-thread-churn-probe', () => ({ recordSubprocessSpawn: vi.fn() })) - -import { gitExecFileAsync } from '../runner' -import { - peekWslGitReadEnvironment, - resetWslGitReadEnvironmentForTests, - seedWslGitReadEnvironmentForTests -} from '../wsl-git-read-environment' -import { _resetGitAdmissionForTests } from './git-subprocess-admission' - -function hostFailure(stdout: string): Error { - return Object.assign(new Error('Command failed: wsl.exe -d kali-linux --exec sh -lc ...'), { - code: 4294967295, - stdout, - stderr: '' - }) -} - -async function withPlatform(platform: NodeJS.Platform, run: () => Promise): Promise { - const original = process.platform - Object.defineProperty(process, 'platform', { configurable: true, value: platform }) - try { - return await run() - } finally { - Object.defineProperty(process, 'platform', { configurable: true, value: original }) - } -} - -describe('git reads over wsl.exe when the WSL service fails', () => { - beforeEach(() => { - execFileMock.mockReset() - }) - afterEach(() => { - _resetGitAdmissionForTests() - }) - - const TRANSIENT = 'Catastrophic failure \r\nError code: Wsl/Service/E_UNEXPECTED\r\n' - - function answerWith(results: ({ fail: string } | { stdout: string })[]): void { - execFileMock.mockImplementation((_command, _args, _options, callback) => { - const child = Object.assign(new EventEmitter(), { pid: 4321, kill: () => {} }) - const next = results.shift() ?? { stdout: '' } - queueMicrotask(() => - 'fail' in next - ? callback?.(hostFailure(next.fail), next.fail, '') - : callback?.(null, next.stdout, '') - ) - return child - }) - } - - it('fails a direct read on a WSL service error without the login-shell fallback', async () => { - await withPlatform('win32', async () => { - const environment = { gitPath: '/usr/bin/git', home: '/home/u', path: '/usr/bin:/bin' } - seedWslGitReadEnvironmentForTests('Ubuntu', environment) - answerWith([{ fail: TRANSIENT }, { stdout: 'login-shell fallback' }]) - const failure = await gitExecFileAsync(['status', '--short'], { - cwd: String.raw`C:\repo`, - preferWslDirectGit: true, - wslDistro: 'Ubuntu' - }).catch((error: unknown) => error) - expect(String(failure)).toContain('Wsl/Service/E_UNEXPECTED') - // One direct launch and no login-shell fallback, so the fast path stays on. - expect(execFileMock).toHaveBeenCalledOnce() - expect(peekWslGitReadEnvironment('Ubuntu')).toEqual(environment) - }).finally(resetWslGitReadEnvironmentForTests) - }) -}) diff --git a/src/main/git/commit-actions.ts b/src/main/git/commit-actions.ts index 3639a71a7c9..29951f1007e 100644 --- a/src/main/git/commit-actions.ts +++ b/src/main/git/commit-actions.ts @@ -8,7 +8,7 @@ import type { import { readGitCommandFailureStderr } from '../../shared/git/commands/git-command-failure-text' import { gitFailureLine, withCheckoutLock } from './branch-switch' import { gitOptionsForWorktree, type GitRuntimeOptions } from './git-runtime-options' -import { gitExecFileAsync } from './runner' +import { gitExecFileAsync } from './command-runner/git-exec-file' import { runWithGitReadCacheInvalidation } from './source-control/git-read-cache-invalidation' import { bulkPathspecCommands } from './source-control/git-pathspec' import { resolveGitDir } from './source-control/resolve-git-dir' diff --git a/src/main/git/create-branch.ts b/src/main/git/create-branch.ts index ea4f3893463..398ab603798 100644 --- a/src/main/git/create-branch.ts +++ b/src/main/git/create-branch.ts @@ -3,7 +3,7 @@ import { readGitCommandFailureStderr } from '../../shared/git/commands/git-comma import type { GitCommitActionResult } from '../../shared/git/commands/git-commit-action' import { withCheckoutLock } from './branch-switch' import { gitOptionsForWorktree, type GitRuntimeOptions } from './git-runtime-options' -import { gitExecFileAsync } from './runner' +import { gitExecFileAsync } from './command-runner/git-exec-file' import { runWithGitReadCacheInvalidation } from './source-control/git-read-cache-invalidation' export async function createBranch( diff --git a/src/main/git/default-wsl-cli-fallback-gate.test.ts b/src/main/git/default-wsl-cli-fallback-gate.test.ts index e5e293b9c4c..2bb916e6054 100644 --- a/src/main/git/default-wsl-cli-fallback-gate.test.ts +++ b/src/main/git/default-wsl-cli-fallback-gate.test.ts @@ -27,7 +27,9 @@ vi.mock('../wsl/discovery/wsl-background-distro-gate', async (importOriginal) => readWslDistroRunningState: readWslDistroRunningStateMock })) -import { ghExecFileAsync, glabExecFileAsync, setDefaultWslDistroOverride } from './runner' +import { ghExecFileAsync } from './command-runner/hosted-cli/gh-exec-file' +import { glabExecFileAsync } from './command-runner/hosted-cli/glab-exec-file' +import { setDefaultWslDistroOverride } from './command-runner/host-routing/wsl-command-resolution' import { _resetGhRateLimitBreaker } from './gh-rate-limit-breaker' import { runAsWslExecUserAct } from '../wsl/discovery/wsl-background-exec-gate' import { diff --git a/src/main/git/fork-sync.ts b/src/main/git/fork-sync.ts index 217d5660d74..bd7f424d8a1 100644 --- a/src/main/git/fork-sync.ts +++ b/src/main/git/fork-sync.ts @@ -6,7 +6,7 @@ import { } from '../../shared/git/remotes/git-fork-sync' import type { GitRuntimeOptions } from './git-runtime-options' import { gitOptionsForWorktree } from './git-runtime-options' -import { gitExecFileAsync } from './runner' +import { gitExecFileAsync } from './command-runner/git-exec-file' import { abortSignalWithTimeout } from '../lib/abort-signal-with-timeout' export async function gitSyncForkDefaultBranch( diff --git a/src/main/git/git-network-safety-real-git.test.ts b/src/main/git/git-network-safety-real-git.test.ts index f902b0cb73e..7ddcbcd045a 100644 --- a/src/main/git/git-network-safety-real-git.test.ts +++ b/src/main/git/git-network-safety-real-git.test.ts @@ -4,7 +4,8 @@ import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { runProcess } from '@orca/process-host' import { quotePosixShell } from '../../shared/shell/launch/shell-argument-quoting' -import { gitExecFileAsync, gitSpawnAfterWindowsEnvironmentReady } from './runner' + +import { gitSpawnAfterWindowsEnvironmentReady } from './command-runner/git-spawn' let root = '' let repo = '' @@ -72,17 +73,6 @@ async function expectIdentity(identity: string): Promise { } describe('network SSH configuration with real Git', () => { - it('preserves command-line SSH configuration ahead of repository configuration', async () => { - await git(['config', 'core.sshCommand', sshCommand('repository')]) - await expect( - gitExecFileAsync( - ['-c', `core.sshCommand=${sshCommand('command-line')}`, 'ls-remote', 'origin'], - { cwd: repo, env } - ) - ).rejects.toThrow() - await expectIdentity('command-line') - }) - it('honors configured global SSH wrappers for streaming clones from a folder', async () => { await git(['config', '--global', 'core.sshCommand', sshCommand('clone identity')]) const child = await gitSpawnAfterWindowsEnvironmentReady( diff --git a/src/main/git/git-runtime-options.ts b/src/main/git/git-runtime-options.ts index 429cae7cffc..48735ed7393 100644 --- a/src/main/git/git-runtime-options.ts +++ b/src/main/git/git-runtime-options.ts @@ -1,4 +1,4 @@ -import type { GitAdmissionTier } from './command-runner/git-exec-options' +import type { GitAdmissionTier } from '../../shared/rpc-contract/git-admission-tier-params' export type GitRuntimeOptions = { wslDistro?: string diff --git a/src/main/git/git-username.ts b/src/main/git/git-username.ts index 2fac8bb4b59..79538afdfa1 100644 --- a/src/main/git/git-username.ts +++ b/src/main/git/git-username.ts @@ -1,4 +1,6 @@ -import { extractExecError, ghExecFileAsync, gitExecFileAsync } from './runner' +import { extractExecError } from './exec-error' +import { ghExecFileAsync } from './command-runner/hosted-cli/gh-exec-file' +import { gitExecFileAsync } from './command-runner/git-exec-file' import { parseHostedRemote } from './remotes/hosted-remote-url' import { resolveDefaultBaseRefViaExec } from '../../shared/git/refs/git-default-base-ref' import { createGitConfigSnapshotRunner } from '../../shared/git/commands/git-config-snapshot-runner' diff --git a/src/main/git/history.ts b/src/main/git/history.ts index 50d2bd8292e..ae37e11f7ba 100644 --- a/src/main/git/history.ts +++ b/src/main/git/history.ts @@ -8,7 +8,7 @@ import type { import { loadGitHistoryFromExecutor } from '../../shared/git/history/git-history-execution' import type { GitRuntimeOptions } from './git-runtime-options' import { gitOptionsForWorktree } from './git-runtime-options' -import { gitExecFileAsync } from './runner' +import { gitExecFileAsync } from './command-runner/git-exec-file' export async function getHistory( worktreePath: string, diff --git a/src/main/git/local-git-object-quarantine.test.ts b/src/main/git/local-git-object-quarantine.test.ts index bf0e404a46d..7f3cfd70ea8 100644 --- a/src/main/git/local-git-object-quarantine.test.ts +++ b/src/main/git/local-git-object-quarantine.test.ts @@ -12,7 +12,7 @@ import { import { resetWslLinkedWorktreeGitRoutingForTests, seedWslLinkedWorktreeGitRoutingForTests -} from './command-runner/wsl-linked-worktree-git-routing' +} from './command-runner/host-routing/wsl-linked-worktree-git-routing' const { readRepoCommonDirFromGitMock } = vi.hoisted(() => ({ readRepoCommonDirFromGitMock: vi.fn() diff --git a/src/main/git/local-git-object-quarantine.ts b/src/main/git/local-git-object-quarantine.ts index 4ae45d56106..c6451ee566b 100644 --- a/src/main/git/local-git-object-quarantine.ts +++ b/src/main/git/local-git-object-quarantine.ts @@ -8,7 +8,7 @@ import { } from '../../shared/git/objects/git-object-quarantine' import { toLinuxPath, toWindowsWslPath } from '../../shared/wsl-paths' import { parseWslPath } from '../wsl/filesystem/unc-path-access' -import { usesHostGitForWslLinkedWorktree } from './command-runner/wsl-linked-worktree-git-routing' +import { usesHostGitForWslLinkedWorktree } from './command-runner/host-routing/wsl-linked-worktree-git-routing' import { readRepoCommonDirFromGit } from './worktrees/catalog/worktree-list-reader' export type LocalGitObjectQuarantine = { diff --git a/src/main/git/merge-tree-object-quarantine-real-git.test.ts b/src/main/git/merge-tree-object-quarantine-real-git.test.ts index 1c84bcf27a3..e0bd1bc206c 100644 --- a/src/main/git/merge-tree-object-quarantine-real-git.test.ts +++ b/src/main/git/merge-tree-object-quarantine-real-git.test.ts @@ -1,4 +1,4 @@ -import { existsSync, readdirSync, writeFileSync } from 'node:fs' +import { readdirSync, writeFileSync } from 'node:fs' import type * as NodeFsPromises from 'node:fs/promises' import { basename, dirname, join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -12,9 +12,8 @@ import { getPRConflictSummary } from '../github/conflict-summary' import { __resetPRConflictSummaryDerivationCachesForTests } from '../github/conflict-summary-cache' -import { getLocalGitCapabilityCache } from './command-runner/git-capability-state' -import { createLocalGitObjectQuarantine } from './local-git-object-quarantine' -import { gitExecFileAsync } from './runner' +import { getLocalGitCapabilityCache } from './command-runner/host-routing/git-capability-state' + import { deleteBranchAfterWorktreeRemoval } from './worktrees/removal/worktree-branch-removal' const scratchFoldersMade = vi.hoisted((): string[] => []) @@ -52,47 +51,6 @@ describe('merge-tree runs against a scratch object store (real Git)', () => { fixture.dispose() }) - function unquarantinedConflictFiles(cwd: string, base: string, head: string): string[] { - const mergeBase = fixture.git(cwd, 'merge-base', head, base).trim() - let stdout: string - try { - stdout = fixture.git( - cwd, - 'merge-tree', - '--write-tree', - '--name-only', - '-z', - '--no-messages', - '--merge-base', - mergeBase, - head, - base - ) - } catch (error) { - // A conflicted merge exits 1 but still prints the file list. - stdout = error instanceof Error && 'stdout' in error ? String(error.stdout) : '' - } - return stdout.split('\0').filter(Boolean).slice(1) - } - - it.each([ - ['the main worktree', (f: DivergentRepoFixture) => f.repoPath], - ['a linked worktree', (f: DivergentRepoFixture) => f.linkedPath] - ])('conflict summary from %s writes no loose objects', async (_label, pickCwd) => { - const cwd = pickCwd(fixture) - const base = fixture.git(cwd, 'rev-parse', 'main').trim() - const head = fixture.git(cwd, 'rev-parse', 'feature-conflict').trim() - const before = fixture.looseObjectCount() - - const summary = await getPRConflictSummary(cwd, 'main', base, head) - - expect(fixture.looseObjectCount()).toBe(before) - expect(fixture.scratchDirectories()).toEqual([]) - expect(summary?.files).toEqual(['shared.txt']) - expect(unquarantinedConflictFiles(cwd, base, head)).toEqual(summary?.files) - expect(fixture.looseObjectCount()).toBeGreaterThan(before) - }) - it.each([ ['the main worktree', (f: DivergentRepoFixture) => f.repoPath], ['a linked worktree', (f: DivergentRepoFixture) => f.linkedPath] @@ -123,88 +81,6 @@ describe('merge-tree runs against a scratch object store (real Git)', () => { expect(mergeTree(squashedHead)).toBe(mainTree) expect(fixture.looseObjectCount()).toBeGreaterThan(before) }) - - it('keeps file contents a partial clone downloads, so the next check does not fetch them again', async () => { - const clone = fixture.createPartialClone() - const git = (...args: string[]): string => fixture.git(clone.clonePath, ...args).trim() - const base = git('rev-parse', 'origin/main') - const head = git('rev-parse', 'origin/feature-conflict') - const packsBefore = clone.packCount() - const looseBefore = clone.looseObjectCount() - - const first = await getPRConflictSummary(clone.clonePath, 'main', base, head) - const packsAfterFirst = clone.packCount() - __resetPRConflictSummaryDerivationCachesForTests() - const second = await getPRConflictSummary(clone.clonePath, 'main', base, head) - - expect(first?.files).toEqual(['shared.txt']) - expect(second?.files).toEqual(['shared.txt']) - // The first check lazily fetches missing blobs; the second reuses them. - expect(packsAfterFirst).toBeGreaterThan(packsBefore) - expect(clone.packCount()).toBe(packsAfterFirst) - expect(clone.looseObjectCount()).toBe(looseBefore) - expect(scratchFoldersMade).toHaveLength(2) - expect(clone.scratchDirectories()).toEqual([]) - }) - - it('lists a partial clone’s conflicts offline once an earlier check downloaded the contents', async () => { - const clone = fixture.createPartialClone() - const git = (...args: string[]): string => fixture.git(clone.clonePath, ...args).trim() - const base = git('rev-parse', 'origin/main') - const head = git('rev-parse', 'origin/feature-conflict') - - const online = await getPRConflictSummary(clone.clonePath, 'main', base, head) - git('remote', 'set-url', 'origin', join(dirname(clone.clonePath), 'unreachable-origin')) - __resetPRConflictSummaryDerivationCachesForTests() - const offline = await getPRConflictSummary(clone.clonePath, 'main', base, head) - - expect(online?.files).toEqual(['shared.txt']) - expect(offline?.files).toEqual(['shared.txt']) - expect(scratchFoldersMade).toHaveLength(2) - expect(clone.scratchDirectories()).toEqual([]) - }) - - it('removes the scratch directory when the Git command fails', async () => { - const quarantine = createLocalGitObjectQuarantine(fixture.linkedPath) - let scratch: string | undefined - - await expect( - quarantine.run(async (env) => { - scratch = env?.GIT_OBJECT_DIRECTORY - expect(scratch && existsSync(scratch)).toBe(true) - return gitExecFileAsync(['merge-tree', '--write-tree', 'main', 'no-such-branch'], { - cwd: fixture.linkedPath, - env - }) - }) - ).rejects.toThrow() - - expect(scratch).toBeDefined() - expect(existsSync(scratch ?? '')).toBe(false) - expect(fixture.scratchDirectories()).toEqual([]) - }) - - it('removes the scratch directory when the command is aborted', async () => { - const quarantine = createLocalGitObjectQuarantine(fixture.repoPath) - const controller = new AbortController() - let scratch: string | undefined - - await expect( - quarantine.run(async (env) => { - scratch = env?.GIT_OBJECT_DIRECTORY - const running = gitExecFileAsync(['merge-tree', '--write-tree', 'main', 'feature-extra'], { - cwd: fixture.repoPath, - env, - signal: controller.signal - }) - controller.abort() - return running - }) - ).rejects.toThrow() - - expect(scratch).toBeDefined() - expect(existsSync(scratch ?? '')).toBe(false) - }) }) describe('merge-tree quarantine keeps the object stores Git would otherwise see (real Git)', () => { diff --git a/src/main/git/push-target-validation.ts b/src/main/git/push-target-validation.ts index 0b133ebcb88..6f67273f989 100644 --- a/src/main/git/push-target-validation.ts +++ b/src/main/git/push-target-validation.ts @@ -1,6 +1,6 @@ import type { GitPushTarget } from '../../shared/worktree/types' import { assertValidGitPushTarget } from '../../shared/git/remotes/git-push-target-validation' -import { gitExecFileAsync } from './runner' +import { gitExecFileAsync } from './command-runner/git-exec-file' import type { GitExecOptions as GitCommandExecOptions } from './command-runner/git-exec-options' type GitExecOptions = Pick diff --git a/src/main/git/refs/maintenance/repo-maintenance-admission.test.ts b/src/main/git/refs/maintenance/repo-maintenance-admission.test.ts deleted file mode 100644 index 1795683fc38..00000000000 --- a/src/main/git/refs/maintenance/repo-maintenance-admission.test.ts +++ /dev/null @@ -1,369 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -type CaptureOptions = { signal?: AbortSignal; onChildTerminated?: () => void } -const { capture, probe, stamp, count, claimOwner, releaseOwner, stopWatch } = vi.hoisted(() => ({ - capture: - vi.fn< - ( - binary: string, - argv: string[], - options: CaptureOptions - ) => Promise<{ stdout: string; stderr: string }> - >(), - probe: vi.fn(), - stamp: vi.fn(), - count: vi.fn(), - claimOwner: vi.fn(), - releaseOwner: vi.fn(), - stopWatch: vi.fn() -})) - -vi.mock('../../../../shared/loose-ref-count', () => ({ countLooseRefs: count })) -vi.mock('../../worktrees/catalog/worktree-list-reader', () => ({ - readRepoCommonDirFromGit: async () => '/repo/.git' -})) -vi.mock('./pack-refs-lock-ownership', () => ({ - PackRefsLockOwnership: class { - claim = claimOwner - watchLock = () => ({ stop: stopWatch }) - release = releaseOwner - } -})) -vi.mock('../../../observability/tracer', () => ({ - withSpan: async (_name: string, run: (span: unknown) => unknown) => - run({ setAttribute: () => {} }) -})) -vi.mock('./repo-pack-index-state', () => ({ - probeRepoPackIndexDirectory: probe, - readRepoPackDirectoryStamp: stamp -})) -vi.mock('../../runner', async () => import('../../command-runner/git-exec-file')) -vi.mock('../../command-runner/exec-file-capture', () => ({ - execFileCapture: capture, - execFileCaptureToTermination: capture -})) -vi.mock('../../../observability/instrumentation', () => ({ - withGitSpan: async (_args: unknown, run: (span: unknown) => unknown) => - run({ setAttribute: () => {} }) -})) - -import { RepoRefMaintenance } from '../../../../shared/repo-ref-maintenance' -import { createLocalRepoRefMaintenanceTarget } from './local-repo-ref-maintenance' -import { clearRepoPackIndexMaintenanceCache } from './repo-pack-index-maintenance' -import { gitExecFileAsync } from '../../command-runner/git-exec-file' -import { GENERAL_CAP } from '../../../../shared/git/admission/git-admission-state' -import { GitAdmissionScheduler } from '../../../../shared/git/admission/git-admission-scheduler' -import { - acquireGitAdmission, - _gitAdmissionSnapshotForTests, - _resetGitAdmissionForTests -} from '../../command-runner/git-subprocess-admission' - -beforeEach(() => { - vi.resetAllMocks() - clearRepoPackIndexMaintenanceCache() - _resetGitAdmissionForTests(new GitAdmissionScheduler()) - stamp.mockResolvedValue('stable-directory') - probe.mockResolvedValue({ protected: false, packCountFloor: 64 }) - count.mockResolvedValue({ count: 1001, saturated: true }) - claimOwner.mockResolvedValue({ ok: true }) - releaseOwner.mockResolvedValue(undefined) - capture.mockImplementation(async (_binary, argv, options) => { - options.onChildTerminated?.() - if (argv[0] === 'config') { - throw Object.assign(new Error('unset'), { code: 1 }) - } - return { stdout: '', stderr: '' } - }) -}) - -afterEach(() => _resetGitAdmissionForTests()) - -function arm( - writer: 'multi-pack-index' | 'pack-refs', - isBusy: () => boolean = () => false, - quietPeriodMs = 1 -): RepoRefMaintenance { - const maintenance = new RepoRefMaintenance({ quietPeriodMs, isBusy }) - maintenance.arm(writerTarget(writer)) - return maintenance -} - -function writerTarget(writer: 'multi-pack-index' | 'pack-refs', repoPath = '/repo') { - const target = createLocalRepoRefMaintenanceTarget({ - key: `local::${repoPath}/.git`, - repoPath - }) - return writer === 'pack-refs' ? { ...target, maintainPackIndex: undefined } : target -} - -describe('maintenance writer admission cancellation', () => { - describe.each(['multi-pack-index', 'pack-refs'] as const)('%s re-arm admission', (writer) => { - it.each([ - 'fresh quiet period', - 'quiet timer rollover', - 'replacement eviction', - 'another repository' - ] as const)('checks queued admission after %s', async (replacement) => { - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) - const quietPeriodMs = 1000 - const blockers: { release: () => void }[] = [] - const saturate = async () => { - blockers.push( - ...(await Promise.all( - Array.from({ length: GENERAL_CAP }, () => - acquireGitAdmission({ args: ['status'], cwd: '/blocker', tier: 'background' }) - ) - )) - ) - } - count.mockResolvedValue({ count: 0, saturated: false }) - if (writer === 'multi-pack-index') { - probe.mockImplementationOnce(async () => { - await saturate() - return { protected: false, packCountFloor: 64 } - }) - } else { - count.mockImplementationOnce(async () => { - await saturate() - return { count: 1001, saturated: true } - }) - } - let busy = false - const maintenance = arm(writer, () => busy, quietPeriodMs) - const writerCalls = () => capture.mock.calls.filter(([, argv]) => argv[0] === writer) - try { - await vi.advanceTimersByTimeAsync(quietPeriodMs) - await vi.waitFor(() => expect(_gitAdmissionSnapshotForTests().queued).toBe(1)) - const oldAttempt = maintenance.whenAttemptSettled() - expect(writerCalls()).toHaveLength(0) - busy = true - maintenance.arm( - replacement === 'another repository' - ? { ...writerTarget(writer, '/other'), isOptedOut: async () => true } - : writerTarget(writer) - ) - if (replacement === 'replacement eviction') { - for (let index = 0; index < 64; index += 1) { - maintenance.arm({ - ...writerTarget(writer, `/other-${index}`), - isOptedOut: async () => true - }) - } - } else if (replacement === 'quiet timer rollover') { - await vi.advanceTimersByTimeAsync(quietPeriodMs) - } - busy = false - blockers.forEach((blocker) => blocker.release()) - await oldAttempt - expect(writerCalls()).toHaveLength(replacement === 'another repository' ? 1 : 0) - expect(_gitAdmissionSnapshotForTests().queued).toBe(0) - expect(_gitAdmissionSnapshotForTests().budgets.general?.baseUsed).toBe(0) - if (replacement === 'fresh quiet period' || replacement === 'quiet timer rollover') { - await vi.advanceTimersByTimeAsync(quietPeriodMs - 1) - expect(writerCalls()).toHaveLength(0) - if (writer === 'pack-refs') { - count.mockResolvedValueOnce({ count: 1001, saturated: true }) - } - await vi.advanceTimersByTimeAsync(1) - await maintenance.whenAttemptSettled() - expect(writerCalls()).toHaveLength(1) - } else if (replacement === 'replacement eviction') { - await vi.advanceTimersByTimeAsync(quietPeriodMs * 2) - await maintenance.whenAttemptSettled() - expect(writerCalls()).toHaveLength(0) - expect( - capture.mock.calls.filter( - ([, argv]) => argv[0] === 'config' && argv[1] === '--get-regexp' - ) - ).toHaveLength(1) - } - } finally { - maintenance.dispose() - blockers.forEach((blocker) => blocker.release()) - vi.useRealTimers() - } - }) - }) - - it.each(['multi-pack-index', 'pack-refs'] as const)( - 'rechecks %s activity after admission and still writes on the next idle attempt', - async (writer) => { - const blockers: { release: () => void }[] = [] - const saturate = async () => { - blockers.push( - ...(await Promise.all( - Array.from({ length: GENERAL_CAP }, () => - acquireGitAdmission({ args: ['status'], cwd: '/blocker', tier: 'background' }) - ) - )) - ) - } - count.mockResolvedValue({ count: 0, saturated: false }) - if (writer === 'multi-pack-index') { - probe.mockImplementationOnce(async () => { - await saturate() - return { protected: false, packCountFloor: 64 } - }) - } else { - count.mockImplementationOnce(async () => { - await saturate() - return { count: 1001, saturated: true } - }) - } - let busy = false - const maintenance = arm(writer, () => busy) - try { - await vi.waitFor(() => expect(_gitAdmissionSnapshotForTests().queued).toBe(1)) - busy = true - blockers.forEach((blocker) => blocker.release()) - await maintenance.whenAttemptSettled() - expect(capture.mock.calls.filter(([, argv]) => argv[0] === writer)).toHaveLength(0) - expect(_gitAdmissionSnapshotForTests().budgets.general?.baseUsed).toBe(0) - if (writer === 'multi-pack-index') { - expect(stamp).toHaveBeenCalledOnce() - } else { - expect(count).toHaveBeenCalledOnce() - } - busy = false - if (writer === 'pack-refs') { - count.mockResolvedValueOnce({ count: 1001, saturated: true }) - } - const target = createLocalRepoRefMaintenanceTarget({ - key: 'local::/repo/.git', - repoPath: '/repo' - }) - maintenance.arm( - writer === 'pack-refs' ? { ...target, maintainPackIndex: undefined } : target - ) - await vi.waitFor(() => - expect(capture.mock.calls.filter(([, argv]) => argv[0] === writer)).toHaveLength(1) - ) - await maintenance.whenAttemptSettled() - if (writer === 'multi-pack-index') { - expect(stamp).toHaveBeenCalledTimes(3) - } else { - expect(count).toHaveBeenCalledTimes(3) - } - } finally { - maintenance.dispose() - blockers.forEach((blocker) => blocker.release()) - } - } - ) - - it('releases a grant canceled before the child starts', async () => { - const controller = new AbortController() - const reason = new Error('Owner disposed between grant and spawn') - _resetGitAdmissionForTests( - new GitAdmissionScheduler({ - onAdmissionEvent: (event) => { - if (event.phase === 'grant') { - queueMicrotask(() => queueMicrotask(() => controller.abort(reason))) - } - } - }) - ) - await expect( - gitExecFileAsync(['multi-pack-index', 'write'], { - cwd: '/repo', - admissionTier: 'background', - admissionSignal: controller.signal - }) - ).rejects.toBe(reason) - expect(capture).not.toHaveBeenCalled() - expect(_gitAdmissionSnapshotForTests().budgets.general?.baseUsed).toBe(0) - }) - - it.each(['multi-pack-index', 'pack-refs'] as const)( - 'removes queued %s immediately on disposal and never starts it after slots reopen', - async (writer) => { - const blockers: { release: () => void }[] = [] - const saturate = async () => { - blockers.push( - ...(await Promise.all( - Array.from({ length: GENERAL_CAP }, () => - acquireGitAdmission({ args: ['status'], cwd: '/blocker', tier: 'background' }) - ) - )) - ) - } - if (writer === 'multi-pack-index') { - probe.mockImplementationOnce(async () => { - await saturate() - return { protected: false, packCountFloor: 64 } - }) - } else { - count.mockImplementationOnce(async () => { - await saturate() - return { count: 1001, saturated: true } - }) - } - const maintenance = arm(writer) - try { - await vi.waitFor(() => - expect(_gitAdmissionSnapshotForTests().queuedWaiters).toEqual([ - expect.objectContaining({ - args: - writer === 'pack-refs' - ? ['pack-refs', '--all', '--prune'] - : ['multi-pack-index', 'write'] - }) - ]) - ) - maintenance.dispose() - expect(_gitAdmissionSnapshotForTests().queued).toBe(0) - blockers.forEach((blocker) => blocker.release()) - await maintenance.whenAttemptSettled() - expect(capture.mock.calls.filter(([, argv]) => argv[0] === writer)).toHaveLength(0) - if (writer === 'pack-refs') { - expect(stopWatch).toHaveBeenCalledOnce() - expect(releaseOwner).toHaveBeenCalledOnce() - } - } finally { - maintenance.dispose() - blockers.forEach((blocker) => blocker.release()) - } - } - ) - - it.each(['multi-pack-index', 'pack-refs'] as const)( - 'lets live %s settle after owner disposal without sending a child abort signal', - async (writer) => { - let finishWriter: (() => void) | undefined - capture.mockImplementation(async (_binary, argv, options) => { - if (argv[0] === 'config') { - options.onChildTerminated?.() - throw Object.assign(new Error('unset'), { code: 1 }) - } - await new Promise((resolve) => { - finishWriter = resolve - }) - options.onChildTerminated?.() - return { stdout: '', stderr: '' } - }) - const maintenance = arm(writer) - try { - await vi.waitFor(() => expect(finishWriter).toBeTypeOf('function')) - maintenance.dispose() - const starts = capture.mock.calls.filter(([, argv]) => argv[0] === writer) - expect(starts).toHaveLength(1) - expect(starts[0]?.[2].signal).toBeUndefined() - expect(_gitAdmissionSnapshotForTests().budgets.general?.baseUsed).toBe(1) - if (writer === 'pack-refs') { - expect(releaseOwner).not.toHaveBeenCalled() - } - finishWriter?.() - await maintenance.whenAttemptSettled() - expect(_gitAdmissionSnapshotForTests().budgets.general?.baseUsed).toBe(0) - if (writer === 'pack-refs') { - expect(stopWatch).toHaveBeenCalledOnce() - expect(releaseOwner).toHaveBeenCalledOnce() - } - } finally { - maintenance.dispose() - finishWriter?.() - } - } - ) -}) diff --git a/src/main/git/remote-rebase.ts b/src/main/git/remote-rebase.ts index 88facf2a7a4..7d85d4508be 100644 --- a/src/main/git/remote-rebase.ts +++ b/src/main/git/remote-rebase.ts @@ -8,8 +8,8 @@ import { } from '../../shared/git/remotes/git-rebase-source' import type { GitRuntimeOptions } from './git-runtime-options' import { gitOptionsForWorktree } from './git-runtime-options' -import { withLocalGitCapabilityCacheForExecution } from './command-runner/git-capability-state' -import { gitExecFileAsync } from './runner' +import { withLocalGitCapabilityCacheForExecution } from './command-runner/host-routing/git-capability-state' +import { gitExecFileAsync } from './command-runner/git-exec-file' import { runWithGitReadCacheInvalidation } from './source-control/git-read-cache-invalidation' export async function gitPullRebaseFromBase( diff --git a/src/main/git/remote.test.ts b/src/main/git/remote.test.ts index 77d4fd07825..5953e2802c5 100644 --- a/src/main/git/remote.test.ts +++ b/src/main/git/remote.test.ts @@ -8,7 +8,7 @@ vi.mock('./command-runner/git-exec-file', async (importOriginal) => ({ ...(await importOriginal>()), gitExecFileAsync: gitExecFileAsyncMock })) -import { clearGitCapabilityStateForTests } from './command-runner/git-capability-state' +import { clearGitCapabilityStateForTests } from './command-runner/host-routing/git-capability-state' import { gitFastForward, gitPush } from './remote' describe('git remote operations', () => { diff --git a/src/main/git/remote.ts b/src/main/git/remote.ts index 99306df355e..13742a41440 100644 --- a/src/main/git/remote.ts +++ b/src/main/git/remote.ts @@ -12,7 +12,7 @@ import { withRepoRefMaintenancePaused } from './refs/maintenance/local-repo-ref-maintenance' import { validateGitPushTarget } from './push-target-validation' -import { gitExecFileAsync } from './runner' +import { gitExecFileAsync } from './command-runner/git-exec-file' import { fetchForkRemoteWithStaleRefspecRepair } from './refs/fork-remotes/fork-remote-stale-branch-refspec' import { runWithGitReadCacheInvalidation } from './source-control/git-read-cache-invalidation' import { runWithGitWorktreeOperationLock } from '../../shared/git/worktrees/git-worktree-operation-lock' diff --git a/src/main/git/repo-base-ref-search.ts b/src/main/git/repo-base-ref-search.ts index b4fc7d43f87..83a0093e328 100644 --- a/src/main/git/repo-base-ref-search.ts +++ b/src/main/git/repo-base-ref-search.ts @@ -10,7 +10,7 @@ import { isRemoteHeadRef } from '../../shared/source-control/hosted-review/hoste import { runSearchBaseRefsGit } from './repo-ref-search-command' export { buildSearchBaseRefsArgv } from './repo-ref-search-command' import { gitExecOptions, type LocalGitExecOptions } from './repo-default-base-ref' -import { gitExecFileAsync } from './runner' +import { gitExecFileAsync } from './command-runner/git-exec-file' import { isQualifiedBaseRef, resolveBaseRefSearchSelector } from './base-ref-search-selector' type RefSearchPatternGroup = 'all' | 'segmented' | 'branchRoot' diff --git a/src/main/git/repo-branch-conflict.ts b/src/main/git/repo-branch-conflict.ts index 22a863edb20..1bc041e274c 100644 --- a/src/main/git/repo-branch-conflict.ts +++ b/src/main/git/repo-branch-conflict.ts @@ -1,6 +1,6 @@ import { resolveConfiguredRemoteBranchName } from './repo-base-ref-search' import { gitExecOptions, type LocalGitExecOptions } from './repo-default-base-ref' -import { gitExecFileAsync } from './runner' +import { gitExecFileAsync } from './command-runner/git-exec-file' import { isSafeGitRefName } from '../../shared/git/status/git-status-upstream-ref' import { isShowRefNoMatchError } from '../../shared/git/refs/git-show-ref-no-match' import { diff --git a/src/main/git/repo-default-base-ref.ts b/src/main/git/repo-default-base-ref.ts index 280f33c526b..886e4d20fab 100644 --- a/src/main/git/repo-default-base-ref.ts +++ b/src/main/git/repo-default-base-ref.ts @@ -1,5 +1,5 @@ import type { GitAdmissionTier } from '../../shared/rpc-contract/git-admission-tier-params' -import { gitExecFileAsync } from './runner' +import { gitExecFileAsync } from './command-runner/git-exec-file' import { resolveDefaultBaseRefViaExec } from '../../shared/git/refs/git-default-base-ref' export type LocalGitExecOptions = { diff --git a/src/main/git/repo-detection-async.test.ts b/src/main/git/repo-detection-async.test.ts index 654da81ff3a..e7a92aff959 100644 --- a/src/main/git/repo-detection-async.test.ts +++ b/src/main/git/repo-detection-async.test.ts @@ -1,17 +1,10 @@ -import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' +import { mkdirSync, mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import * as runner from './runner' +import * as gitExecFileModule from './command-runner/git-exec-file' import { runProcess } from '@orca/process-host' -import { - getGitRepoRoot, - getGitRepoRootAsync, - inspectGitRepoForRegistration, - inspectGitRepoForRegistrationAsync, - isGitRepo, - isGitRepoAsync -} from './repo-detection' +import { getGitRepoRootAsync, isGitRepoAsync } from './repo-detection' let fixture: string async function git(cwd: string, args: string[]): Promise { @@ -29,74 +22,15 @@ afterEach(() => { rmSync(fixture, { recursive: true, force: true }) }) -async function expectSameDetection(path: string): Promise { - expect(await isGitRepoAsync(path)).toBe(isGitRepo(path)) - expect(await getGitRepoRootAsync(path)).toBe(getGitRepoRoot(path)) - expect(await inspectGitRepoForRegistrationAsync(path)).toEqual( - inspectGitRepoForRegistration(path) - ) -} - describe('asynchronous repository detection with real Git', () => { it('preserves genuine metadata fallback when asynchronous Git cannot answer', async () => { const repo = join(fixture, 'fallback repo') const nested = join(repo, 'packages') mkdirSync(nested, { recursive: true }) await git(repo, ['init', '--quiet']) - vi.spyOn(runner, 'gitExecFileAsync').mockRejectedValue(new Error('Git unavailable')) + vi.spyOn(gitExecFileModule, 'gitExecFileAsync').mockRejectedValue(new Error('Git unavailable')) expect(await isGitRepoAsync(nested)).toBe(true) expect(await getGitRepoRootAsync(nested)).toBe(repo.replaceAll('\\', '/')) expect(await isGitRepoAsync(join(repo, '.git'))).toBe(false) }) - - it.skipIf(process.platform === 'win32')( - 'preserves newlines, dollar signs and trailing spaces in roots and linked identity', - async () => { - const repo = join(fixture, 'repo\nwith dollar$ and trailing space ') - const nested = join(repo, 'nested\n') - mkdirSync(nested, { recursive: true }) - await git(repo, ['init', '--quiet']) - await git(repo, [ - '-c', - 'user.name=Orca Test', - '-c', - 'user.email=orca@example.invalid', - 'commit', - '--allow-empty', - '--quiet', - '-m', - 'fixture' - ]) - const linked = join(fixture, 'linked\n ') - await git(repo, ['worktree', 'add', '--quiet', '-b', 'edge-linked', linked]) - for (const path of [repo, nested, linked]) { - await expectSameDetection(path) - } - expect((await inspectGitRepoForRegistrationAsync(nested)).rootPath).toBe(realpathSync(repo)) - expect((await inspectGitRepoForRegistrationAsync(linked)).mainRepoPath).toBe( - realpathSync(repo) - ) - } - ) - - it('preserves symlink target identity and rejects its invalid nested marker without Git', async () => { - const repo = join(fixture, 'target') - const nested = join(repo, 'nested') - mkdirSync(nested, { recursive: true }) - await git(repo, ['init', '--quiet']) - const alias = join(fixture, 'alias') - symlinkSync(nested, alias, process.platform === 'win32' ? 'junction' : 'dir') - await expectSameDetection(alias) - vi.spyOn(runner, 'gitExecFileSync').mockImplementation(() => { - throw new Error('Git unavailable') - }) - vi.spyOn(runner, 'gitExecFileAsync').mockRejectedValue(new Error('Git unavailable')) - await expectSameDetection(alias) - expect((await inspectGitRepoForRegistrationAsync(alias)).rootPath).toBe( - realpathSync(repo).replaceAll('\\', '/') - ) - writeFileSync(join(nested, '.git'), 'gitdir: missing-metadata') - await expectSameDetection(alias) - expect(await isGitRepoAsync(alias)).toBe(false) - }) }) diff --git a/src/main/git/repo-detection-batching.test.ts b/src/main/git/repo-detection-batching.test.ts index 4de9d05db50..fb43878191d 100644 --- a/src/main/git/repo-detection-batching.test.ts +++ b/src/main/git/repo-detection-batching.test.ts @@ -1,9 +1,9 @@ import { execFileSync } from 'node:child_process' -import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync } from 'node:fs' +import { mkdirSync, mkdtempSync, realpathSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import * as runner from './runner' + import { getGitRepoRoot, getLinkedWorktreeMainRepoRoot, @@ -14,55 +14,6 @@ function git(cwd: string, args: string[]): string { return execFileSync('git', args, { cwd, encoding: 'utf8', stdio: 'pipe' }) } -describe('repository registration probe batching', () => { - let directory: string - let repo: string - - beforeEach(() => { - directory = mkdtempSync(join(tmpdir(), 'orca-repo-probe-count-')) - repo = join(directory, 'repo') - mkdirSync(repo) - git(repo, ['init', '-q']) - }) - - afterEach(() => { - vi.restoreAllMocks() - rmSync(directory, { recursive: true, force: true }) - }) - - it('reads root and linked-main metadata together when a symlink changes between probes', () => { - const linked = join(directory, 'linked') - const alias = join(directory, 'alias') - git(repo, [ - '-c', - 'user.name=Test', - '-c', - 'user.email=test@example.invalid', - 'commit', - '-qm', - 'seed', - '--allow-empty' - ]) - git(repo, ['worktree', 'add', '-q', '-b', 'linked', linked]) - symlinkSync(repo, alias, process.platform === 'win32' ? 'junction' : 'dir') - const execute = runner.gitExecFileSync - const probe = vi.spyOn(runner, 'gitExecFileSync').mockImplementation((args, options) => { - const output = execute(args, options) - if (probe.mock.calls.length === 1) { - rmSync(alias) - symlinkSync(linked, alias, process.platform === 'win32' ? 'junction' : 'dir') - } - return output - }) - expect(inspectGitRepoForRegistration(alias)).toEqual({ - isRepo: true, - rootPath: git(linked, ['rev-parse', '--show-toplevel']).trim().replace(/\\/g, '/'), - mainRepoPath: realpathSync(repo) - }) - expect(probe).toHaveBeenCalledTimes(2) - }) -}) - // Windows rejects control characters in directory names. describe.skipIf(process.platform === 'win32')('repository paths with newlines', () => { let directory: string diff --git a/src/main/git/repo-detection-command.test.ts b/src/main/git/repo-detection-command.test.ts index dc20b62b65b..98cc79e8396 100644 --- a/src/main/git/repo-detection-command.test.ts +++ b/src/main/git/repo-detection-command.test.ts @@ -1,5 +1,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import { gitExecFileAsync, gitExecFileSync } from './runner' +import { gitExecFileAsync } from './command-runner/git-exec-file' +import { gitExecFileSync } from './command-runner/git-exec-file-sync' import { gitRepoOutput, runGitRepoCommands, runGitRepoCommandsSync } from './repo-detection-command' vi.mock('./command-runner/git-exec-file', async (importOriginal) => ({ diff --git a/src/main/git/repo-detection-command.ts b/src/main/git/repo-detection-command.ts index 7808844aab6..a969eb55648 100644 --- a/src/main/git/repo-detection-command.ts +++ b/src/main/git/repo-detection-command.ts @@ -1,4 +1,5 @@ -import { gitExecFileAsync, gitExecFileSync } from './runner' +import { gitExecFileAsync } from './command-runner/git-exec-file' +import { gitExecFileSync } from './command-runner/git-exec-file-sync' type GitRepoCommand = { args: string[]; cwd: string } export type GitRepoCommands = Generator diff --git a/src/main/git/repo-ref-search-command.ts b/src/main/git/repo-ref-search-command.ts index da3f2cb9527..5adae86724b 100644 --- a/src/main/git/repo-ref-search-command.ts +++ b/src/main/git/repo-ref-search-command.ts @@ -4,9 +4,9 @@ import { isRepoSearchRefsScanLimit } from '../../shared/repo-search-limits' import { isSafeGitRefName } from '../../shared/git/status/git-status-upstream-ref' -import { getLocalGitCapabilityCache } from './command-runner/git-capability-state' +import { getLocalGitCapabilityCache } from './command-runner/host-routing/git-capability-state' import { gitExecOptions, type LocalGitExecOptions } from './repo-default-base-ref' -import { gitExecFileAsync } from './runner' +import { gitExecFileAsync } from './command-runner/git-exec-file' const REF_SEARCH_CANDIDATE_MULTIPLIER = 4 const REF_SEARCH_LEGACY_HEADROOM = 100 diff --git a/src/main/git/repo-remote-ref-search.ts b/src/main/git/repo-remote-ref-search.ts index 8df0340fd6d..35d843e10fc 100644 --- a/src/main/git/repo-remote-ref-search.ts +++ b/src/main/git/repo-remote-ref-search.ts @@ -1,5 +1,5 @@ import type { BaseRefSearchResult } from '../../shared/repo-types' -import { gitExecFileAsync } from './runner' +import { gitExecFileAsync } from './command-runner/git-exec-file' import { runSearchBaseRefsGit } from './repo-ref-search-command' import { normalizeRefSearchQuery, diff --git a/src/main/git/repo-search-ref-compat.test.ts b/src/main/git/repo-search-ref-compat.test.ts index 1e04079cc0e..ebf41cbdda8 100644 --- a/src/main/git/repo-search-ref-compat.test.ts +++ b/src/main/git/repo-search-ref-compat.test.ts @@ -14,7 +14,7 @@ vi.mock('./command-runner/git-exec-file-sync', async (importOriginal) => ({ gitExecFileSync: vi.fn() })) -import { clearGitCapabilityStateForTests } from './command-runner/git-capability-state' +import { clearGitCapabilityStateForTests } from './command-runner/host-routing/git-capability-state' import { searchBaseRefs } from './repo' describe('searchBaseRefs git compatibility', () => { diff --git a/src/main/git/repo-username.test.ts b/src/main/git/repo-username.test.ts index bcb9a5c296d..470f32ac249 100644 --- a/src/main/git/repo-username.test.ts +++ b/src/main/git/repo-username.test.ts @@ -1,5 +1,5 @@ import type * as GitExecFileModule from './command-runner/git-exec-file' -import type * as GhExecFileModule from './command-runner/gh-exec-file' +import type * as GhExecFileModule from './command-runner/hosted-cli/gh-exec-file' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const gitExecFileAsyncMock = vi.hoisted(() => vi.fn()) @@ -13,8 +13,10 @@ vi.mock('./command-runner/git-exec-file', async () => { } }) -vi.mock('./command-runner/gh-exec-file', async () => { - const actual = await vi.importActual('./command-runner/gh-exec-file') +vi.mock('./command-runner/hosted-cli/gh-exec-file', async () => { + const actual = await vi.importActual( + './command-runner/hosted-cli/gh-exec-file' + ) return { ...actual, ghExecFileAsync: ghExecFileAsyncMock diff --git a/src/main/git/repo.ts b/src/main/git/repo.ts index 56c5ce101a5..846f3aec75d 100644 --- a/src/main/git/repo.ts +++ b/src/main/git/repo.ts @@ -8,7 +8,7 @@ import { gitExecOptions, type LocalGitExecOptions } from './repo-default-base-ref' -import { gitExecFileAsync } from './runner' +import { gitExecFileAsync } from './command-runner/git-exec-file' export { isGitRepo, diff --git a/src/main/git/review-head-remote-identity.ts b/src/main/git/review-head-remote-identity.ts index cc392fe6366..ef42f848a9e 100644 --- a/src/main/git/review-head-remote-identity.ts +++ b/src/main/git/review-head-remote-identity.ts @@ -1,4 +1,4 @@ -import { gitExecFileAsync } from './runner' +import { gitExecFileAsync } from './command-runner/git-exec-file' import { reviewHeadRemoteRefComponent } from '../../shared/review-head-tracking-ref' type LocalGitExecOptions = { diff --git a/src/main/git/runner-buffer-cancellation.test.ts b/src/main/git/runner-buffer-cancellation.test.ts index 516a67e9adc..2157759e64d 100644 --- a/src/main/git/runner-buffer-cancellation.test.ts +++ b/src/main/git/runner-buffer-cancellation.test.ts @@ -7,10 +7,10 @@ vi.mock('node:child_process', () => ({ spawn: vi.fn() })) -import { gitExecFileAsyncBuffer } from './runner' -import { GitAdmissionScheduler } from '../../shared/git/admission/git-admission-scheduler' -import { _resetGitAdmissionForTests } from './command-runner/git-subprocess-admission' -import { configureWindowsHostGitEnvironmentReadiness } from './command-runner/windows-host-git-environment' +import { gitExecFileAsyncBuffer } from './command-runner/git-exec-file' + +import { _resetGitAdmissionForTests } from './command-runner/admission/git-subprocess-admission' +import { configureWindowsHostGitEnvironmentReadiness } from './command-runner/host-routing/windows-host-git-environment' beforeEach(() => execFileMock.mockReset()) afterEach(() => { @@ -19,27 +19,6 @@ afterEach(() => { }) describe('buffered Git cancellation', () => { - it('removes a canceled queued read without waiting for the active child', async () => { - const scheduler = new GitAdmissionScheduler({ generalCap: 1, generalHeadroom: 0 }) - _resetGitAdmissionForTests(scheduler) - const grant = await scheduler.acquire({ args: ['show'], cwd: '/repo' }) - try { - const controller = new AbortController() - const read = gitExecFileAsyncBuffer(['show', 'HEAD:file'], { - cwd: '/repo', - signal: controller.signal - }) - const rejected = expect(read).rejects.toMatchObject({ name: 'AbortError' }) - await vi.waitFor(() => expect(scheduler.snapshot().queued).toBe(1)) - controller.abort() - await rejected - expect(scheduler.snapshot().queued).toBe(0) - expect(execFileMock).not.toHaveBeenCalled() - } finally { - grant.release() - } - }) - it('cancels Windows environment readiness without launching Git', async () => { const platform = process.platform Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) diff --git a/src/main/git/runner-buffer-stdin.test.ts b/src/main/git/runner-buffer-stdin.test.ts index 90964a40898..6a73428380f 100644 --- a/src/main/git/runner-buffer-stdin.test.ts +++ b/src/main/git/runner-buffer-stdin.test.ts @@ -2,7 +2,7 @@ import { mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it } from 'vitest' -import { gitExecFileAsync, gitExecFileAsyncBuffer } from './runner' +import { gitExecFileAsync, gitExecFileAsyncBuffer } from './command-runner/git-exec-file' const roots: string[] = [] afterEach(async () => { diff --git a/src/main/git/runner-command-exec.test.ts b/src/main/git/runner-command-exec.test.ts index ad0cf9f28c3..df52f5e4908 100644 --- a/src/main/git/runner-command-exec.test.ts +++ b/src/main/git/runner-command-exec.test.ts @@ -12,13 +12,11 @@ vi.mock('node:child_process', () => ({ execFileSync: execFileSyncMock, spawn: spawnMock })) -import { - commandExecFileAsync, - gitExecFileAsync, - glabExecFileAsync, - gitStreamStdout -} from './runner' -import { _resetGitAdmissionForTests } from './command-runner/git-subprocess-admission' +import { commandExecFileAsync } from './command-runner/process-capture/command-exec-file' +import { gitExecFileAsync } from './command-runner/git-exec-file' +import { glabExecFileAsync } from './command-runner/hosted-cli/glab-exec-file' +import { gitStreamStdout } from './command-runner/git-stream-stdout' +import { _resetGitAdmissionForTests } from './command-runner/admission/git-subprocess-admission' afterEach(() => _resetGitAdmissionForTests()) diff --git a/src/main/git/runner-gh-account-binding.test.ts b/src/main/git/runner-gh-account-binding.test.ts index 72509f53316..e3bfd5157b3 100644 --- a/src/main/git/runner-gh-account-binding.test.ts +++ b/src/main/git/runner-gh-account-binding.test.ts @@ -40,7 +40,7 @@ vi.mock('../github/gh-account-token', async (importOriginal) => { } }) -import { ghExecFileAsync } from './runner' +import { ghExecFileAsync } from './command-runner/hosted-cli/gh-exec-file' import { _resetGhRateLimitBreaker, recordGhPrimaryRateLimit } from './gh-rate-limit-breaker' /** Spawns a child that settles with `stdout`, capturing the env the runner handed it. */ diff --git a/src/main/git/runner-gh-host-args.test.ts b/src/main/git/runner-gh-host-args.test.ts index 00685c56f7f..f5a33fea8ce 100644 --- a/src/main/git/runner-gh-host-args.test.ts +++ b/src/main/git/runner-gh-host-args.test.ts @@ -1,6 +1,9 @@ import { describe, expect, it } from 'vitest' -import { applyGhHostToArgs, collectGhArgvHostSignals } from './command-runner/gh-host-args' +import { + applyGhHostToArgs, + collectGhArgvHostSignals +} from './command-runner/hosted-cli/gh-host-args' describe('applyGhHostToArgs', () => { it('does not rewrite free-text flag values that merely start with -R', () => { diff --git a/src/main/git/runner-gh-rate-limit-breaker.test.ts b/src/main/git/runner-gh-rate-limit-breaker.test.ts index 7551b5d5cf1..6aa9d28c6dc 100644 --- a/src/main/git/runner-gh-rate-limit-breaker.test.ts +++ b/src/main/git/runner-gh-rate-limit-breaker.test.ts @@ -13,8 +13,8 @@ vi.mock('child_process', () => ({ })) import { fakeSpawnReturning } from '../../shared/__fixtures__/fake-spawned-child' -import { ghExecFileAsync } from './runner' -import { _resetGhRateLimitBreaker, getGhRateLimitBlockedUntilMs } from './gh-rate-limit-breaker' +import { ghExecFileAsync } from './command-runner/hosted-cli/gh-exec-file' +import { _resetGhRateLimitBreaker } from './gh-rate-limit-breaker' const PRIMARY_RATE_LIMIT_STDERR = 'gh: API rate limit exceeded for user ID 1775218. Please wait. (HTTP 403)' @@ -23,10 +23,6 @@ function mockGhFailure(stderr: string): void { spawnMock.mockImplementation(fakeSpawnReturning({ stderr, code: 1 })) } -function mockGhSuccess(stdout: string): void { - spawnMock.mockImplementation(fakeSpawnReturning({ stdout })) -} - beforeEach(() => { execFileMock.mockReset() spawnMock.mockReset() @@ -49,68 +45,4 @@ describe('ghExecFileAsync rate-limit breaker', () => { ).rejects.toMatchObject({ ghRateLimitBlocked: true }) expect(spawnMock).toHaveBeenCalledTimes(1) }) - - it('keeps other GitHub hosts and WSL runtimes working when github.com is blocked', async () => { - mockGhFailure(PRIMARY_RATE_LIMIT_STDERR) - await expect(ghExecFileAsync(['api', 'repos/a/b/pulls'])).rejects.toThrow() - - // Route this request to an independent Enterprise host. - mockGhSuccess('[]') - await expect( - ghExecFileAsync(['api', 'repos/a/b/pulls'], { host: 'github.acme-corp.com' }) - ).resolves.toMatchObject({ stdout: '[]' }) - await expect( - ghExecFileAsync(['pr', 'list', '--repo', 'a/b'], { host: 'github.acme-corp.com' }) - ).resolves.toMatchObject({ stdout: '[]' }) - await expect( - ghExecFileAsync(['api', 'repos/a/b/pulls'], { - env: { ...process.env, GH_HOST: 'github.acme-corp.com' } - }) - ).resolves.toMatchObject({ stdout: '[]' }) - const originalPlatform = process.platform - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - try { - await expect( - ghExecFileAsync(['api', 'repos/a/b/pulls'], { wslDistro: 'Ubuntu' }) - ).resolves.toMatchObject({ stdout: '[]' }) - } finally { - Object.defineProperty(process, 'platform', { - configurable: true, - value: originalPlatform - }) - } - expect(spawnMock).toHaveBeenCalledTimes(5) - }) - - it('trips the graphql bucket on a GraphQL rate limit and leaves REST calls running', async () => { - mockGhFailure('GraphQL: API rate limit already exceeded for user ID 1775218.') - await expect( - ghExecFileAsync(['pr', 'view', '12', '--repo', 'a/b', '--json', 'number']) - ).rejects.toThrow('rate limit') - expect(getGhRateLimitBlockedUntilMs('graphql')).not.toBeNull() - expect(getGhRateLimitBlockedUntilMs('core')).toBeNull() - - await expect( - ghExecFileAsync(['issue', 'close', '5', '--repo', 'a/b'], { idempotent: false }) - ).rejects.toMatchObject({ ghRateLimitBlocked: true }) - expect(spawnMock).toHaveBeenCalledTimes(1) - - mockGhSuccess('[]') - await expect(ghExecFileAsync(['api', 'repos/a/b/pulls'])).resolves.toMatchObject({ - stdout: '[]' - }) - expect(spawnMock).toHaveBeenCalledTimes(2) - }) - - it('never blocks the exempt rate_limit probe', async () => { - mockGhFailure(PRIMARY_RATE_LIMIT_STDERR) - await expect(ghExecFileAsync(['api', 'repos/a/b/pulls'])).rejects.toThrow() - mockGhSuccess('{"resources":{}}') - await expect( - ghExecFileAsync(['api', '--hostname', 'github.com', 'rate_limit']) - ).resolves.toMatchObject({ - stdout: '{"resources":{}}' - }) - expect(spawnMock).toHaveBeenCalledTimes(2) - }) }) diff --git a/src/main/git/runner-network-ssh-policy.test.ts b/src/main/git/runner-network-ssh-policy.test.ts index 5a53e5a659f..d68e5995102 100644 --- a/src/main/git/runner-network-ssh-policy.test.ts +++ b/src/main/git/runner-network-ssh-policy.test.ts @@ -8,9 +8,9 @@ vi.mock('node:child_process', () => ({ spawn: vi.fn() })) -import { gitExecFileAsync } from './runner' +import { gitExecFileAsync } from './command-runner/git-exec-file' import { GitAdmissionScheduler } from '../../shared/git/admission/git-admission-scheduler' -import { _resetGitAdmissionForTests } from './command-runner/git-subprocess-admission' +import { _resetGitAdmissionForTests } from './command-runner/admission/git-subprocess-admission' class MockChildProcess extends EventEmitter { stdout = new EventEmitter() diff --git a/src/main/git/runner-windows-host-environment.test.ts b/src/main/git/runner-windows-host-environment.test.ts index fe893e7f0e6..11f866c93af 100644 --- a/src/main/git/runner-windows-host-environment.test.ts +++ b/src/main/git/runner-windows-host-environment.test.ts @@ -14,13 +14,12 @@ vi.mock('node:child_process', () => ({ import { awaitWindowsHostGitEnvironmentReady, - configureWindowsHostGitEnvironmentReadiness, - gitExecFileAsync, - gitExecFileAsyncBuffer, - gitSpawnAfterWindowsEnvironmentReady, - gitStreamStdout -} from './runner' -import { _resetGitAdmissionForTests } from './command-runner/git-subprocess-admission' + configureWindowsHostGitEnvironmentReadiness +} from './command-runner/host-routing/windows-host-git-environment' +import { gitExecFileAsync, gitExecFileAsyncBuffer } from './command-runner/git-exec-file' +import { gitSpawnAfterWindowsEnvironmentReady } from './command-runner/git-spawn' +import { gitStreamStdout } from './command-runner/git-stream-stdout' +import { _resetGitAdmissionForTests } from './command-runner/admission/git-subprocess-admission' type MockChildProcess = EventEmitter & { stdout: EventEmitter @@ -74,67 +73,6 @@ describe('Windows host Git environment readiness', () => { } }) - it('waits for each native operation and refreshes a snapshotted PATH', async () => { - await withPlatform('win32', async () => { - const ready = deferred() - const waitUntilReady = vi.fn(() => ready.promise) - const child = createMockChildProcess(1234) - execFileMock.mockImplementation((_cmd, _args, _options, callback) => { - callback(null, 'ok', '') - return child - }) - configureWindowsHostGitEnvironmentReadiness(waitUntilReady) - process.env.Path = 'hydrating-path' - - const firstExec = gitExecFileAsync(['status'], { - cwd: String.raw`C:\repo`, - env: { Path: 'stale-path' } - }) - - expect(waitUntilReady).toHaveBeenCalledOnce() - expect(execFileMock).not.toHaveBeenCalled() - process.env.Path = 'hydrated-path' - ready.resolve() - await expect(firstExec).resolves.toEqual({ stdout: 'ok', stderr: '' }) - expect(execFileMock.mock.calls[0]?.[2]?.env?.Path).toBe('hydrated-path') - - await expect(gitExecFileAsync(['status'], { cwd: String.raw`C:\repo` })).resolves.toEqual({ - stdout: 'ok', - stderr: '' - }) - expect(waitUntilReady).toHaveBeenCalledTimes(2) - }) - }) - - it('waits before native spawned Git and refreshes a snapshotted PATH', async () => { - await withPlatform('win32', async () => { - const ready = deferred() - const waitUntilReady = vi.fn(() => ready.promise) - const child = createMockChildProcess(1234) - spawnMock.mockReturnValue(child) - execFileMock.mockImplementation((_cmd, _args, _options, callback) => { - callback(Object.assign(new Error('missing SSH config'), { code: 1 }), '', '') - return child - }) - configureWindowsHostGitEnvironmentReadiness(waitUntilReady) - process.env.Path = 'hydrating-path' - - const spawned = gitSpawnAfterWindowsEnvironmentReady(['clone', 'url', 'repo'], { - cwd: String.raw`C:\repo`, - env: { Path: 'stale-path' }, - stdio: ['ignore', 'ignore', 'pipe'] - }) - - expect(waitUntilReady).toHaveBeenCalledOnce() - expect(spawnMock).not.toHaveBeenCalled() - process.env.Path = 'hydrated-path' - ready.resolve() - - await expect(spawned).resolves.toBe(child) - expect(spawnMock.mock.calls[0]?.[2]?.env?.Path).toBe('hydrated-path') - }) - }) - it('does not gate spawned Git routed through WSL on the Windows host profile', async () => { await withPlatform('win32', async () => { const waitUntilReady = vi.fn(() => new Promise(() => {})) diff --git a/src/main/git/runner-wsl-direct-read.test.ts b/src/main/git/runner-wsl-direct-read.test.ts index 35cdcca65c6..9983ff87210 100644 --- a/src/main/git/runner-wsl-direct-read.test.ts +++ b/src/main/git/runner-wsl-direct-read.test.ts @@ -16,10 +16,11 @@ vi.mock('../observability/instrumentation', () => ({ withGitSpan: (_attributes: unknown, run: () => unknown) => run() })) vi.mock('../diagnostics/main-thread-churn-probe', () => ({ recordSubprocessSpawn: vi.fn() })) -import { gitExecFileAsync, gitExecFileAsyncBuffer, gitStreamStdout } from './runner' -import { GitAdmissionScheduler } from '../../shared/git/admission/git-admission-scheduler' -import { _resetGitAdmissionForTests } from './command-runner/git-subprocess-admission' -import type { GitAdmissionEvent } from '../../shared/git/admission/git-admission-state' +import { gitExecFileAsync, gitExecFileAsyncBuffer } from './command-runner/git-exec-file' +import { gitStreamStdout } from './command-runner/git-stream-stdout' + +import { _resetGitAdmissionForTests } from './command-runner/admission/git-subprocess-admission' + import { recordHostAutocrlf, resetWslWindowsCheckoutGitConfigForTests, @@ -33,8 +34,8 @@ import { import { prepareWslLinkedWorktreeGitRouting, resetWslLinkedWorktreeGitRoutingForTests -} from './command-runner/wsl-linked-worktree-git-routing' -import type { WslLinkedWorktreeRoutingFileSystem } from './command-runner/wsl-linked-worktree-git-route-probe' +} from './command-runner/host-routing/wsl-linked-worktree-git-routing' +import type { WslLinkedWorktreeRoutingFileSystem } from './command-runner/host-routing/wsl-linked-worktree-git-route-probe' afterEach(() => _resetGitAdmissionForTests()) @@ -186,56 +187,6 @@ describe('WSL direct Git reads', () => { }) }) - it('waits for direct Git to close before retrying through the login shell', async () => { - await withPlatform('win32', async () => { - const admissionEvents: GitAdmissionEvent[] = [] - _resetGitAdmissionForTests( - new GitAdmissionScheduler({ onAdmissionEvent: (event) => admissionEvents.push(event) }) - ) - seedWslGitReadEnvironmentForTests(DISTRO, LOGIN_ENVIRONMENT) - let directChild!: ReturnType - execFileMock.mockImplementationOnce((_command, _args, _options, callback) => { - const child = createMockChild() - directChild = child - queueMicrotask(() => { - callback?.( - Object.assign(new Error('exit 127'), { code: 127 }), - '', - '/usr/bin/env: No such file or directory' - ) - }) - return child - }) - execFileMock.mockImplementationOnce((_command, _args, _options, callback) => { - const child = createMockChild() - queueMicrotask(() => { - child.emit('close', 0, null) - callback?.(null, 'ok', '') - }) - return child - }) - - const result = gitExecFileAsync(['status', '--short'], { - cwd: String.raw`C:\repo`, - preferWslDirectGit: true, - wslDistro: DISTRO - }) - - await vi.waitFor(() => expect(directChild).toBeDefined()) - await Promise.resolve() - expect(execFileMock).toHaveBeenCalledTimes(1) - directChild.emit('close', 127, null) - await expect(result).resolves.toEqual({ stdout: 'ok', stderr: '' }) - - expect(execFileMock.mock.calls[0]?.[1]).toContain('--exec') - expect(execFileMock.mock.calls[1]?.[1]?.slice(3, 5)).toEqual(['sh', '-lc']) - expect(admissionEvents.map(({ phase, waiterId }) => [phase, waiterId])).toEqual([ - ['grant', 0], - ['release', 0] - ]) - }) - }) - it('does not retry a failed direct stream after delivering output', async () => { await withPlatform('win32', async () => { seedWslGitReadEnvironmentForTests(DISTRO, LOGIN_ENVIRONMENT) diff --git a/src/main/git/runner-wsl-gh-fallback.test.ts b/src/main/git/runner-wsl-gh-fallback.test.ts index c347a2f43a7..b948d257c7c 100644 --- a/src/main/git/runner-wsl-gh-fallback.test.ts +++ b/src/main/git/runner-wsl-gh-fallback.test.ts @@ -1,12 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type * as BackgroundDistroGate from '../wsl/discovery/wsl-background-distro-gate' -import { - createFakeSpawnedChild, - fakeSpawnDispatch, - fakeSpawnReturning -} from '../../shared/__fixtures__/fake-spawned-child' +import { fakeSpawnDispatch, fakeSpawnReturning } from '../../shared/__fixtures__/fake-spawned-child' import type * as WslModule from '../wsl/discovery/distro-catalog' -import { windowsSystem32Binary } from '@orca/process-host/windows-system-binary' const { execFileSyncMock, spawnMock, getDefaultWslDistroMock } = vi.hoisted(() => ({ execFileSyncMock: vi.fn(), @@ -30,7 +25,9 @@ vi.mock('../wsl/discovery/distro-catalog', async (importOriginal) => ({ ...(await importOriginal()), getDefaultWslDistro: getDefaultWslDistroMock })) -import { ghExecFileAsync, glabExecFileAsync, setDefaultWslDistroOverride } from './runner' +import { ghExecFileAsync } from './command-runner/hosted-cli/gh-exec-file' +import { glabExecFileAsync } from './command-runner/hosted-cli/glab-exec-file' +import { setDefaultWslDistroOverride } from './command-runner/host-routing/wsl-command-resolution' import { _resetGhRateLimitBreaker } from './gh-rate-limit-breaker' const PRIMARY_RATE_LIMIT_STDERR = @@ -179,72 +176,6 @@ describe('ghExecFileAsync WSL fallback', () => { expect(spawnMock).toHaveBeenCalledTimes(1) }) - it('times out the default-WSL glab fallback and waits for full tree cleanup', async () => { - vi.useFakeTimers() - getDefaultWslDistroMock.mockReturnValue('Ubuntu') - const wslChild = createFakeSpawnedChild(2400) - const taskkill = createFakeSpawnedChild(3600) - spawnMock - .mockImplementationOnce(fakeSpawnReturning(spawnEnoent('glab'))) - // Keep the child unsettled until taskkill reports completion. - .mockImplementationOnce(() => wslChild) - .mockImplementation(() => taskkill) - - const promise = glabExecFileAsync(['auth', 'status'], { timeout: 1000 }) - const rejection = expect(promise).rejects.toThrow('wsl.exe timed out.') - let rejected = false - void promise.catch(() => { - rejected = true - }) - - await vi.advanceTimersByTimeAsync(999) - expect(spawnMock).toHaveBeenCalledTimes(2) - await vi.advanceTimersByTimeAsync(1) - expect(spawnMock).toHaveBeenCalledWith( - windowsSystem32Binary('taskkill.exe'), - ['/pid', '2400', '/t', '/f'], - expect.objectContaining({ stdio: 'ignore', windowsHide: true }) - ) - await Promise.resolve() - expect(rejected).toBe(false) - - taskkill.emit('close', 0) - await rejection - expect(wslChild.kill).not.toHaveBeenCalled() - }) - - it('aborts the default-WSL glab fallback with full process-tree cleanup', async () => { - getDefaultWslDistroMock.mockReturnValue('Ubuntu') - const wslChild = createFakeSpawnedChild(2400) - const taskkill = createFakeSpawnedChild(3600) - spawnMock - .mockImplementationOnce(fakeSpawnReturning(spawnEnoent('glab'))) - .mockImplementationOnce(() => wslChild) - .mockImplementation(() => taskkill) - const controller = new AbortController() - - const promise = glabExecFileAsync(['auth', 'status'], { signal: controller.signal }) - const rejection = expect(promise).rejects.toMatchObject({ name: 'AbortError' }) - await vi.waitFor(() => expect(spawnMock).toHaveBeenCalledTimes(2)) - controller.abort() - - expect(spawnMock).toHaveBeenNthCalledWith( - 2, - 'wsl.exe', - ['-d', 'Ubuntu', '--exec', 'bash', '-c', "'glab' 'auth' 'status'"], - expect.not.objectContaining({ signal: controller.signal }) - ) - expect(spawnMock).toHaveBeenCalledWith( - windowsSystem32Binary('taskkill.exe'), - ['/pid', '2400', '/t', '/f'], - expect.objectContaining({ stdio: 'ignore', windowsHide: true }) - ) - taskkill.emit('close', 0) - - await rejection - expect(wslChild.kill).not.toHaveBeenCalled() - }) - it('does not wake the default WSL distro for host-only GitLab diagnostics', async () => { getDefaultWslDistroMock.mockReturnValue('Ubuntu') spawnMock diff --git a/src/main/git/runner-wsl-linked-gitdir-timeout.test.ts b/src/main/git/runner-wsl-linked-gitdir-timeout.test.ts deleted file mode 100644 index 8af227578ae..00000000000 --- a/src/main/git/runner-wsl-linked-gitdir-timeout.test.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { EventEmitter } from 'node:events' -import type * as FsPromises from 'node:fs/promises' -import { afterEach, describe, expect, it, vi } from 'vitest' - -const { execFileMock, statMock, readFileMock } = vi.hoisted(() => ({ - execFileMock: vi.fn(), - statMock: vi.fn(), - readFileMock: vi.fn() -})) - -vi.mock('node:child_process', () => ({ - execFile: execFileMock, - execFileSync: vi.fn(), - spawn: vi.fn() -})) - -vi.mock('node:fs/promises', async (importOriginal) => ({ - ...(await importOriginal()), - stat: statMock, - readFile: readFileMock -})) - -import { gitExecFileAsync } from './runner' -import { _resetGitAdmissionForTests } from './command-runner/git-subprocess-admission' - -afterEach(() => _resetGitAdmissionForTests()) -import { - resetWslLinkedWorktreeGitRoutingForTests, - WSL_LINKED_WORKTREE_ROUTE_PROBE_TIMEOUT_MS -} from './command-runner/wsl-linked-worktree-git-routing' - -function createMockChild(): EventEmitter & { pid: number; kill: ReturnType } { - const child = new EventEmitter() as EventEmitter & { - pid: number - kill: ReturnType - } - child.pid = 1234 - child.kill = vi.fn() - return child -} - -async function withWindowsPlatform(run: () => Promise): Promise { - const original = process.platform - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - try { - await run() - } finally { - Object.defineProperty(process, 'platform', { configurable: true, value: original }) - } -} - -afterEach(() => { - vi.useRealTimers() - vi.restoreAllMocks() - resetWslLinkedWorktreeGitRoutingForTests() -}) - -describe('WSL linked-worktree routing probe timeout', () => { - it('retries discovery on the next production Git call', async () => { - vi.useFakeTimers() - await withWindowsPlatform(async () => { - statMock - .mockImplementationOnce(() => new Promise(() => {})) - .mockResolvedValue({ isDirectory: () => false, isFile: () => true }) - readFileMock.mockResolvedValue('gitdir: C:/main/.git/worktrees/linked\n') - execFileMock.mockImplementation((command, _args, _options, callback) => { - const child = createMockChild() - queueMicrotask(() => { - if (command === 'wsl.exe') { - callback?.( - Object.assign(new Error('not a git repository'), { code: 128 }), - '', - 'fatal: not a git repository' - ) - } else { - callback?.(null, 'host git recovered\n', '') - } - }) - return child - }) - - const first = gitExecFileAsync(['status', '--short'], { - cwd: String.raw`C:\repo`, - wslDistro: 'Ubuntu' - }) - const firstFailure = expect(first).rejects.toThrow('not a git repository') - await vi.advanceTimersByTimeAsync(WSL_LINKED_WORKTREE_ROUTE_PROBE_TIMEOUT_MS) - await firstFailure - - await expect( - gitExecFileAsync(['status', '--short'], { - cwd: String.raw`C:\repo`, - wslDistro: 'Ubuntu' - }) - ).resolves.toEqual({ stdout: 'host git recovered\n', stderr: '' }) - - expect(statMock).toHaveBeenCalledTimes(2) - // A WSL read also warms the direct-git environment probe in the background; - // it is not part of the routing sequence under test. - const routedCommands = execFileMock.mock.calls - .filter(([, args]) => !String((args as string[])?.at(-1)).includes('^GIT_')) - .map(([command]) => command) - expect(routedCommands).toEqual(['wsl.exe', 'git']) - }) - }) -}) diff --git a/src/main/git/runner-wsl-linked-gitdir-windows.test.ts b/src/main/git/runner-wsl-linked-gitdir-windows.test.ts index 67e700d6ca7..b82ffb79201 100644 --- a/src/main/git/runner-wsl-linked-gitdir-windows.test.ts +++ b/src/main/git/runner-wsl-linked-gitdir-windows.test.ts @@ -2,10 +2,11 @@ import { execFileSync } from 'node:child_process' import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' -import { gitExecFileAsync, gitExecFileAsyncBuffer, gitStreamStdout } from './runner' +import { gitExecFileAsync, gitExecFileAsyncBuffer } from './command-runner/git-exec-file' +import { gitStreamStdout } from './command-runner/git-stream-stdout' import { toLinuxPath } from '../../shared/wsl-paths' import { listWorktrees } from './worktrees/catalog/worktree-scan-cache' -import { resetWslLinkedWorktreeGitRoutingForTests } from './command-runner/wsl-linked-worktree-git-routing' +import { resetWslLinkedWorktreeGitRoutingForTests } from './command-runner/host-routing/wsl-linked-worktree-git-routing' const distro = process.env.ORCA_TEST_WSL_DISTRO?.trim() const fixtureRoots: string[] = [] diff --git a/src/main/git/runner-wsl-login-shell-capture.test.ts b/src/main/git/runner-wsl-login-shell-capture.test.ts index 23eb93cba1a..534efd76586 100644 --- a/src/main/git/runner-wsl-login-shell-capture.test.ts +++ b/src/main/git/runner-wsl-login-shell-capture.test.ts @@ -17,8 +17,8 @@ vi.mock('../observability/instrumentation', () => ({ })) vi.mock('../diagnostics/main-thread-churn-probe', () => ({ recordSubprocessSpawn: vi.fn() })) -import { gitExecFileAsync, gitExecFileAsyncBuffer } from './runner' -import { _resetGitAdmissionForTests } from './command-runner/git-subprocess-admission' +import { gitExecFileAsync, gitExecFileAsyncBuffer } from './command-runner/git-exec-file' +import { _resetGitAdmissionForTests } from './command-runner/admission/git-subprocess-admission' afterEach(() => _resetGitAdmissionForTests()) import { resetWslGitReadEnvironmentForTests } from './wsl-git-read-environment' diff --git a/src/main/git/runner-wsl-network-ssh-policy.test.ts b/src/main/git/runner-wsl-network-ssh-policy.test.ts index 167fa4fc3de..01161e1bcc2 100644 --- a/src/main/git/runner-wsl-network-ssh-policy.test.ts +++ b/src/main/git/runner-wsl-network-ssh-policy.test.ts @@ -8,9 +8,9 @@ vi.mock('node:child_process', () => ({ spawn: vi.fn() })) -import { gitExecFileAsync } from './runner' +import { gitExecFileAsync } from './command-runner/git-exec-file' import { GitAdmissionScheduler } from '../../shared/git/admission/git-admission-scheduler' -import { _resetGitAdmissionForTests } from './command-runner/git-subprocess-admission' +import { _resetGitAdmissionForTests } from './command-runner/admission/git-subprocess-admission' const originalPlatform = process.platform const WSL_CWD = String.raw`\\wsl.localhost\Ubuntu\home\alice\repo` diff --git a/src/main/git/runner.ts b/src/main/git/runner.ts deleted file mode 100644 index 01ec6e6ac1b..00000000000 --- a/src/main/git/runner.ts +++ /dev/null @@ -1,33 +0,0 @@ -/** Stable git/gh/glab execution entry point; implementations live in command-runner. */ -// Lightweight consumers can import exec-error directly to avoid runner dependencies. -export { extractExecError, parseRetryAfterMs } from './exec-error' - -export { setDefaultWslDistroOverride } from './command-runner/wsl-command-resolution' -export { - awaitWindowsHostGitEnvironmentReady, - configureWindowsHostGitEnvironmentReadiness -} from './command-runner/windows-host-git-environment' -export { DEFAULT_GIT_MAX_BUFFER } from './command-runner/git-exec-options' - -export { - gitOptionalLocksDisabledEnv, - nonInteractiveGitEnv, - promptGuardGitEnv, - promptGuardShellEnv, - untranslatedGitOutputEnv -} from './command-runner/git-process-env' -export { gitExecFileAsync, gitExecFileAsyncBuffer } from './command-runner/git-exec-file' -export { gitExecFileSync } from './command-runner/git-exec-file-sync' -export { commandExecFileAsync } from './command-runner/command-exec-file' -export { gitStreamStdout, type GitStreamResult } from './command-runner/git-stream-stdout' -export { - gitSpawn, - gitSpawnAfterWindowsEnvironmentReady, - withGitAdmission -} from './command-runner/git-spawn' -export { isTransientGhError } from './command-runner/gh-retry-policy' -export { applyGhHostToArgs } from './command-runner/gh-host-args' -export { ghExecFileAsync, ghExecFileWithScopeAsync } from './command-runner/gh-exec-file' -export { glabExecFileAsync, redirectPortedHostnameToEnv } from './command-runner/glab-exec-file' -export { wslAwareSpawn } from './command-runner/wsl-aware-spawn' -export { translateWslOutputPaths } from './command-runner/wsl-path-translation' diff --git a/src/main/git/source-control/branch-change-entries.ts b/src/main/git/source-control/branch-change-entries.ts index cd3a7d0daeb..870a89b33bb 100644 --- a/src/main/git/source-control/branch-change-entries.ts +++ b/src/main/git/source-control/branch-change-entries.ts @@ -2,7 +2,7 @@ import type { GitBranchChangeEntry } from '../../../shared/git/diff/git-diff-com import { gitChangeListArgs, parseGitChangeList } from '../../../shared/git/diff/git-change-list' import type { GitRuntimeOptions } from '../git-runtime-options' import { gitOptionsForWorktree } from '../git-runtime-options' -import { gitExecFileAsync } from '../runner' +import { gitExecFileAsync } from '../command-runner/git-exec-file' import { MAX_GIT_SHOW_BYTES } from './git-show-max-bytes' export async function loadBranchChanges( diff --git a/src/main/git/source-control/commit-changes.ts b/src/main/git/source-control/commit-changes.ts index a52a9d77a2a..9c3b8a2521d 100644 --- a/src/main/git/source-control/commit-changes.ts +++ b/src/main/git/source-control/commit-changes.ts @@ -1,6 +1,6 @@ import type { GitRuntimeOptions } from '../git-runtime-options' import { gitOptionsForWorktree } from '../git-runtime-options' -import { gitExecFileAsync } from '../runner' +import { gitExecFileAsync } from '../command-runner/git-exec-file' import { detectConflictOperation } from './git-conflict-operation' import { invalidateGitReadCaches } from './git-read-cache-invalidation' diff --git a/src/main/git/source-control/commit-compare.ts b/src/main/git/source-control/commit-compare.ts index 418df0c5995..8474c7e75e0 100644 --- a/src/main/git/source-control/commit-compare.ts +++ b/src/main/git/source-control/commit-compare.ts @@ -2,7 +2,7 @@ import type { GitCommitCompareResult } from '../../../shared/git/diff/git-diff-c import { parseGitRevListFirstParentOid } from '../../../shared/git/refs/git-rev-list-output' import type { GitRuntimeOptions } from '../git-runtime-options' import { gitOptionsForWorktree } from '../git-runtime-options' -import { gitExecFileAsync } from '../runner' +import { gitExecFileAsync } from '../command-runner/git-exec-file' import { loadCommitChanges } from './branch-change-entries' import { resolveRefOid } from './compare-ref-oids' diff --git a/src/main/git/source-control/compare-ref-oids.ts b/src/main/git/source-control/compare-ref-oids.ts index e43bcdf3625..a5f030ca65c 100644 --- a/src/main/git/source-control/compare-ref-oids.ts +++ b/src/main/git/source-control/compare-ref-oids.ts @@ -1,6 +1,6 @@ import type { GitRuntimeOptions } from '../git-runtime-options' import { gitOptionsForWorktree } from '../git-runtime-options' -import { gitExecFileAsync } from '../runner' +import { gitExecFileAsync } from '../command-runner/git-exec-file' export async function resolveCompareRef( worktreePath: string, diff --git a/src/main/git/source-control/discard-changes.ts b/src/main/git/source-control/discard-changes.ts index 5d6c59fff58..0bb6b04f565 100644 --- a/src/main/git/source-control/discard-changes.ts +++ b/src/main/git/source-control/discard-changes.ts @@ -6,7 +6,7 @@ import { import { partitionTrackedPathSpecs } from '../../../shared/git/paths/git-tracked-pathspecs' import type { GitRuntimeOptions } from '../git-runtime-options' import { gitOptionsForWorktree } from '../git-runtime-options' -import { gitExecFileAsync } from '../runner' +import { gitExecFileAsync } from '../command-runner/git-exec-file' import { invalidateGitReadCaches } from './git-read-cache-invalidation' import { bulkPathspecCommands, literalPathspec } from './git-pathspec' import { encodeGitPathspecs } from '../../../shared/git/paths/git-pathspec-stdin' diff --git a/src/main/git/source-control/drive-checkout-suspect-status.ts b/src/main/git/source-control/drive-checkout-suspect-status.ts index b3f248c74ee..c12f3f5faf5 100644 --- a/src/main/git/source-control/drive-checkout-suspect-status.ts +++ b/src/main/git/source-control/drive-checkout-suspect-status.ts @@ -8,8 +8,9 @@ import { findCoveringLocalWatchRoot, observeLocalWatcherEvents } from '../../ipc/filesystem/watchers/local-watcher-event-observers' -import { gitOptionalLocksDisabledEnv, gitStreamStdout } from '../runner' -import { usesHostGitForWslLinkedWorktree } from '../command-runner/wsl-linked-worktree-git-routing' +import { gitOptionalLocksDisabledEnv } from '../command-runner/git-environment/git-process-env' +import { gitStreamStdout } from '../command-runner/git-stream-stdout' +import { usesHostGitForWslLinkedWorktree } from '../command-runner/host-routing/wsl-linked-worktree-git-routing' import { withWslWindowsCheckoutGitConfig, wslWindowsCheckoutKey diff --git a/src/main/git/source-control/drive-checkout-suspect-writes.ts b/src/main/git/source-control/drive-checkout-suspect-writes.ts index e92c56c88fb..dcf3d2d6983 100644 --- a/src/main/git/source-control/drive-checkout-suspect-writes.ts +++ b/src/main/git/source-control/drive-checkout-suspect-writes.ts @@ -1,6 +1,6 @@ import type { GitRuntimeOptions } from '../git-runtime-options' import { gitOptionsForWorktree } from '../git-runtime-options' -import { gitExecFileAsync } from '../runner' +import { gitExecFileAsync } from '../command-runner/git-exec-file' import { driveCheckoutSuspectsWithin } from './drive-checkout-suspect-status' import { bulkPathspecCommands } from './git-pathspec' diff --git a/src/main/git/source-control/effective-upstream-status-probe.ts b/src/main/git/source-control/effective-upstream-status-probe.ts index fbaf888eaa7..244c713061f 100644 --- a/src/main/git/source-control/effective-upstream-status-probe.ts +++ b/src/main/git/source-control/effective-upstream-status-probe.ts @@ -6,7 +6,7 @@ import { import { splitRemoteBranchName } from '../../../shared/git/remotes/git-remote-branch-name' import type { GitRuntimeOptions } from '../git-runtime-options' import { gitReadOptionsForWorktree } from '../git-runtime-options' -import { gitExecFileAsync } from '../runner' +import { gitExecFileAsync } from '../command-runner/git-exec-file' import { MAX_EFFECTIVE_UPSTREAM_NEGATIVE_CACHE_ENTRIES, effectiveUpstreamStatusInFlight, diff --git a/src/main/git/source-control/git-blob-read.ts b/src/main/git/source-control/git-blob-read.ts index f0916ae90a7..23d59d0de72 100644 --- a/src/main/git/source-control/git-blob-read.ts +++ b/src/main/git/source-control/git-blob-read.ts @@ -4,7 +4,7 @@ import { isMissingGitBlobPath } from '../../../shared/git/diff/git-blob-absence' import { readGitCommandFailureStderr } from '../../../shared/git/commands/git-command-failure-text' import type { GitRuntimeOptions } from '../git-runtime-options' import { gitReadOptionsForWorktree } from '../git-runtime-options' -import { gitExecFileAsyncBuffer } from '../runner' +import { gitExecFileAsyncBuffer } from '../command-runner/git-exec-file' import { isMaxBufferOverflowError } from '../max-buffer-overflow' import { MAX_GIT_SHOW_BYTES } from './git-show-max-bytes' import { literalPathspec } from './git-pathspec' diff --git a/src/main/git/source-control/git-conflict-operation.ts b/src/main/git/source-control/git-conflict-operation.ts index dde06f08a52..af08f38383d 100644 --- a/src/main/git/source-control/git-conflict-operation.ts +++ b/src/main/git/source-control/git-conflict-operation.ts @@ -3,7 +3,7 @@ import * as path from 'node:path' import type { GitConflictOperation } from '../../../shared/git/status/git-status-types' import type { GitRuntimeOptions } from '../git-runtime-options' import { gitOptionsForWorktree } from '../git-runtime-options' -import { gitExecFileAsync } from '../runner' +import { gitExecFileAsync } from '../command-runner/git-exec-file' import { runWithGitReadCacheInvalidation } from './git-read-cache-invalidation' import { resolveGitDir } from './resolve-git-dir' diff --git a/src/main/git/source-control/git-pathspec.ts b/src/main/git/source-control/git-pathspec.ts index 6184ad02ce7..cabcef7f412 100644 --- a/src/main/git/source-control/git-pathspec.ts +++ b/src/main/git/source-control/git-pathspec.ts @@ -2,10 +2,8 @@ import { commandLineLength, MAX_COMMAND_LINE_CHARS } from '../../../shared/windows-command-line-budget' -import { - resolveGitCommandWithoutProbe, - wslDistroForCommand -} from '../command-runner/git-command-resolution' +import { resolveGitCommandWithoutProbe } from '../command-runner/host-routing/git-command-resolution' +import { wslDistroForCommand } from '../../../shared/wsl-paths' import { WINDOWS_CHECKOUT_GIT_CONFIG_ARGS } from '../wsl-windows-checkout-git-config' import type { GitRuntimeOptions } from '../git-runtime-options' diff --git a/src/main/git/source-control/staged-commit-context.ts b/src/main/git/source-control/staged-commit-context.ts index 4b02aab0f48..0add380bd02 100644 --- a/src/main/git/source-control/staged-commit-context.ts +++ b/src/main/git/source-control/staged-commit-context.ts @@ -1,7 +1,7 @@ import type { CommitMessageDraftContext } from '../../../shared/source-control/ai/generation/commit-message-generation' import type { GitRuntimeOptions } from '../git-runtime-options' import { gitOptionsForWorktree } from '../git-runtime-options' -import { gitExecFileAsync } from '../runner' +import { gitExecFileAsync } from '../command-runner/git-exec-file' import { describeMaxBufferOverflowError, isMaxBufferOverflowError } from '../max-buffer-overflow' import { MAX_STAGED_COMMIT_CONTEXT_BYTES } from './git-show-max-bytes' diff --git a/src/main/git/source-control/staging.ts b/src/main/git/source-control/staging.ts index 1943df440a8..455743bfd70 100644 --- a/src/main/git/source-control/staging.ts +++ b/src/main/git/source-control/staging.ts @@ -1,6 +1,6 @@ import type { GitRuntimeOptions } from '../git-runtime-options' import { gitOptionsForWorktree } from '../git-runtime-options' -import { gitExecFileAsync } from '../runner' +import { gitExecFileAsync } from '../command-runner/git-exec-file' import { invalidateGitReadCaches } from './git-read-cache-invalidation' import { gitReportedPath, literalPathspec } from './git-pathspec' import { encodeGitPathspecs } from '../../../shared/git/paths/git-pathspec-stdin' diff --git a/src/main/git/source-control/stamped-git-config.ts b/src/main/git/source-control/stamped-git-config.ts index 6e5dafab7b1..c59ef273a3b 100644 --- a/src/main/git/source-control/stamped-git-config.ts +++ b/src/main/git/source-control/stamped-git-config.ts @@ -5,9 +5,9 @@ import { BoundedMap } from '../../../shared/bounded-map' import { resolveWorktreeHostPath } from '../../../shared/git/metadata/git-metadata-path' import { InFlightPromiseDedupe } from '../../../shared/in-flight-promise-dedupe' import { iterateNulDelimitedFields } from '../../../shared/nul-delimited-fields' -import { wslDistroForCommand } from '../command-runner/git-command-resolution' +import { wslDistroForCommand } from '../../../shared/wsl-paths' import { gitReadOptionsForWorktree, type GitRuntimeOptions } from '../git-runtime-options' -import { gitExecFileAsync } from '../runner' +import { gitExecFileAsync } from '../command-runner/git-exec-file' import { readStampWithinDeadline, type StampProbes } from './deadline-bounded-stamp' import { resolveGitCommonDir, resolveGitDir } from './resolve-git-dir' import { diff --git a/src/main/git/source-control/status-branch-line-total-input.ts b/src/main/git/source-control/status-branch-line-total-input.ts index 660804c2727..e5fcd4bc884 100644 --- a/src/main/git/source-control/status-branch-line-total-input.ts +++ b/src/main/git/source-control/status-branch-line-total-input.ts @@ -9,7 +9,8 @@ import { } from '../../../shared/git/status/git-branch-line-total' import { type GitRuntimeOptions, gitReadOptionsForWorktree } from '../git-runtime-options' -import { gitExecFileAsync, gitOptionalLocksDisabledEnv } from '../runner' +import { gitExecFileAsync } from '../command-runner/git-exec-file' +import { gitOptionalLocksDisabledEnv } from '../command-runner/git-environment/git-process-env' import { resolveWorktreeFilesystemPath } from './worktree-filesystem-path' import type { GetStatusOptions } from './get-status-options' diff --git a/src/main/git/source-control/status-diff.test.ts b/src/main/git/source-control/status-diff.test.ts index 6efb87276ca..3529b005198 100644 --- a/src/main/git/source-control/status-diff.test.ts +++ b/src/main/git/source-control/status-diff.test.ts @@ -1,7 +1,6 @@ -import type * as RunnerModule from '../runner' import type * as GitExecFileModule from '../command-runner/git-exec-file' import type * as GitStreamStdoutModule from '../command-runner/git-stream-stdout' -import type * as GitProcessEnvModule from '../command-runner/git-process-env' +import type * as GitProcessEnvModule from '../command-runner/git-environment/git-process-env' import { beforeEach, describe, expect, it, vi } from 'vitest' import type * as BoundedFileReader from '../../../shared/file-content/node-bounded-file-reader' import path from 'node:path' @@ -9,7 +8,9 @@ import path from 'node:path' import { createBoundedFileReaderModuleMock, createFsPromisesModuleMock, - createGitRunnerModuleMock + createGitExecFileModuleMock, + createGitStreamStdoutModuleMock, + createGitProcessEnvModuleMock } from './status-test-harness' const { @@ -34,38 +35,20 @@ const { existsSyncMock: vi.fn() })) -vi.mock('../runner', () => - createGitRunnerModuleMock({ - gitExecFileAsyncMock, - gitExecFileAsyncBufferMock, - gitStreamOptionsMock - }) -) +vi.mock('../command-runner/git-exec-file', async (importOriginal) => ({ + ...(await importOriginal()), + ...createGitExecFileModuleMock({ gitExecFileAsyncMock, gitExecFileAsyncBufferMock }) +})) -vi.mock('../command-runner/git-exec-file', async (importOriginal) => { - const runnerMocks = await vi.importMock('../runner') - return { - ...(await importOriginal()), - gitExecFileAsync: runnerMocks.gitExecFileAsync, - gitExecFileAsyncBuffer: runnerMocks.gitExecFileAsyncBuffer - } -}) +vi.mock('../command-runner/git-stream-stdout', async (importOriginal) => ({ + ...(await importOriginal()), + ...createGitStreamStdoutModuleMock({ gitExecFileAsyncMock, gitStreamOptionsMock }) +})) -vi.mock('../command-runner/git-stream-stdout', async (importOriginal) => { - const runnerMocks = await vi.importMock('../runner') - return { - ...(await importOriginal()), - gitStreamStdout: runnerMocks.gitStreamStdout - } -}) - -vi.mock('../command-runner/git-process-env', async (importOriginal) => { - const runnerMocks = await vi.importMock('../runner') - return { - ...(await importOriginal()), - gitOptionalLocksDisabledEnv: runnerMocks.gitOptionalLocksDisabledEnv - } -}) +vi.mock('../command-runner/git-environment/git-process-env', async (importOriginal) => ({ + ...(await importOriginal()), + ...createGitProcessEnvModuleMock() +})) vi.mock('fs/promises', () => createFsPromisesModuleMock({ lstatMock, realpathMock, readFileMock, statMock, rmMock }) diff --git a/src/main/git/source-control/status-line-stats-host-paths.test.ts b/src/main/git/source-control/status-line-stats-host-paths.test.ts index 1f2981b56c2..fa775b98f3e 100644 --- a/src/main/git/source-control/status-line-stats-host-paths.test.ts +++ b/src/main/git/source-control/status-line-stats-host-paths.test.ts @@ -55,7 +55,7 @@ vi.mock('../command-runner/git-exec-file', async (importOriginal) => ({ gitExecFileAsyncBuffer: vi.fn() })) -vi.mock('../command-runner/git-process-env', async (importOriginal) => ({ +vi.mock('../command-runner/git-environment/git-process-env', async (importOriginal) => ({ ...(await importOriginal>()), gitOptionalLocksDisabledEnv: (env: NodeJS.ProcessEnv = process.env) => env })) diff --git a/src/main/git/source-control/status-line-stats.ts b/src/main/git/source-control/status-line-stats.ts index 508447f64a4..788b59f295b 100644 --- a/src/main/git/source-control/status-line-stats.ts +++ b/src/main/git/source-control/status-line-stats.ts @@ -8,7 +8,8 @@ import { } from '../../../shared/git/status/git-uncommitted-line-stats' import type { GitRuntimeOptions } from '../git-runtime-options' import { gitReadOptionsForWorktree } from '../git-runtime-options' -import { gitExecFileAsync, gitOptionalLocksDisabledEnv } from '../runner' +import { gitExecFileAsync } from '../command-runner/git-exec-file' +import { gitOptionalLocksDisabledEnv } from '../command-runner/git-environment/git-process-env' import { resolveWorktreeFilesystemPath } from './worktree-filesystem-path' import { settledNumstatCache } from './git-read-cache-invalidation' import { readStampedGitConfig, type StampedGitConfig } from './stamped-git-config' diff --git a/src/main/git/source-control/status-porcelain-stream.ts b/src/main/git/source-control/status-porcelain-stream.ts index f9ef343c5dd..0ad274bcb35 100644 --- a/src/main/git/source-control/status-porcelain-stream.ts +++ b/src/main/git/source-control/status-porcelain-stream.ts @@ -1,6 +1,7 @@ import { BoundedMap } from '../../../shared/bounded-map' import { StatusPorcelainParser } from '../../../shared/git/status/git-status-porcelain-parser' -import { gitOptionalLocksDisabledEnv, gitStreamStdout } from '../runner' +import { gitOptionalLocksDisabledEnv } from '../command-runner/git-environment/git-process-env' +import { gitStreamStdout } from '../command-runner/git-stream-stdout' import type { GetStatusOptions } from './get-status-options' import { listUntrackedDirectoryFiles, readUntrackedScan } from './status-untracked-directories' diff --git a/src/main/git/source-control/status-submodule.test.ts b/src/main/git/source-control/status-submodule.test.ts index c7f8f15790a..fa2049f73c0 100644 --- a/src/main/git/source-control/status-submodule.test.ts +++ b/src/main/git/source-control/status-submodule.test.ts @@ -1,14 +1,15 @@ -import type * as RunnerModule from '../runner' import type * as GitExecFileModule from '../command-runner/git-exec-file' import type * as GitStreamStdoutModule from '../command-runner/git-stream-stdout' -import type * as GitProcessEnvModule from '../command-runner/git-process-env' +import type * as GitProcessEnvModule from '../command-runner/git-environment/git-process-env' import { beforeEach, describe, expect, it, vi } from 'vitest' import type * as BoundedFileReader from '../../../shared/file-content/node-bounded-file-reader' import path from 'node:path' import { createBoundedFileReaderModuleMock, createFsPromisesModuleMock, - createGitRunnerModuleMock + createGitExecFileModuleMock, + createGitStreamStdoutModuleMock, + createGitProcessEnvModuleMock } from './status-test-harness' const { @@ -33,38 +34,20 @@ const { existsSyncMock: vi.fn() })) -vi.mock('../runner', () => - createGitRunnerModuleMock({ - gitExecFileAsyncMock, - gitExecFileAsyncBufferMock, - gitStreamOptionsMock - }) -) +vi.mock('../command-runner/git-exec-file', async (importOriginal) => ({ + ...(await importOriginal()), + ...createGitExecFileModuleMock({ gitExecFileAsyncMock, gitExecFileAsyncBufferMock }) +})) -vi.mock('../command-runner/git-exec-file', async (importOriginal) => { - const runnerMocks = await vi.importMock('../runner') - return { - ...(await importOriginal()), - gitExecFileAsync: runnerMocks.gitExecFileAsync, - gitExecFileAsyncBuffer: runnerMocks.gitExecFileAsyncBuffer - } -}) +vi.mock('../command-runner/git-stream-stdout', async (importOriginal) => ({ + ...(await importOriginal()), + ...createGitStreamStdoutModuleMock({ gitExecFileAsyncMock, gitStreamOptionsMock }) +})) -vi.mock('../command-runner/git-stream-stdout', async (importOriginal) => { - const runnerMocks = await vi.importMock('../runner') - return { - ...(await importOriginal()), - gitStreamStdout: runnerMocks.gitStreamStdout - } -}) - -vi.mock('../command-runner/git-process-env', async (importOriginal) => { - const runnerMocks = await vi.importMock('../runner') - return { - ...(await importOriginal()), - gitOptionalLocksDisabledEnv: runnerMocks.gitOptionalLocksDisabledEnv - } -}) +vi.mock('../command-runner/git-environment/git-process-env', async (importOriginal) => ({ + ...(await importOriginal()), + ...createGitProcessEnvModuleMock() +})) vi.mock('fs/promises', () => createFsPromisesModuleMock({ lstatMock, realpathMock, readFileMock, statMock, rmMock }) diff --git a/src/main/git/source-control/status-test-harness.ts b/src/main/git/source-control/status-test-harness.ts index 0ceb169a149..3d62cb019a2 100644 --- a/src/main/git/source-control/status-test-harness.ts +++ b/src/main/git/source-control/status-test-harness.ts @@ -3,9 +3,13 @@ import type * as BoundedFileReader from '../../../shared/file-content/node-bound type MockFn = Mock -export type GitRunnerMocks = { +export type GitExecFileMocks = { gitExecFileAsyncMock: MockFn gitExecFileAsyncBufferMock: MockFn +} + +export type GitStreamStdoutMocks = { + gitExecFileAsyncMock: MockFn gitStreamOptionsMock: MockFn } @@ -19,10 +23,17 @@ export type FsPromisesMocks = { accessMock?: MockFn } -export function createGitRunnerModuleMock(mocks: GitRunnerMocks): Record { +export function createGitExecFileModuleMock(mocks: GitExecFileMocks): Record { return { gitExecFileAsync: mocks.gitExecFileAsyncMock, - gitExecFileAsyncBuffer: mocks.gitExecFileAsyncBufferMock, + gitExecFileAsyncBuffer: mocks.gitExecFileAsyncBufferMock + } +} + +export function createGitStreamStdoutModuleMock( + mocks: GitStreamStdoutMocks +): Record { + return { // Feed queued exec responses into the status stream, preserving existing argv-based mocks. gitStreamStdout: async ( args: string[], @@ -32,7 +43,12 @@ export function createGitRunnerModuleMock(mocks: GitRunnerMocks): Record { + return { gitOptionalLocksDisabledEnv: (env: NodeJS.ProcessEnv = process.env) => ({ ...env, GIT_OPTIONAL_LOCKS: '0' diff --git a/src/main/git/source-control/status-untracked-directories.ts b/src/main/git/source-control/status-untracked-directories.ts index bf58de7f2dd..18681b5a25b 100644 --- a/src/main/git/source-control/status-untracked-directories.ts +++ b/src/main/git/source-control/status-untracked-directories.ts @@ -1,4 +1,5 @@ -import { gitOptionalLocksDisabledEnv, gitStreamStdout } from '../runner' +import { gitOptionalLocksDisabledEnv } from '../command-runner/git-environment/git-process-env' +import { gitStreamStdout } from '../command-runner/git-stream-stdout' import { readStampedGitConfig } from './stamped-git-config' import type { GetStatusOptions } from './get-status-options' import { bulkPathspecCommands } from './git-pathspec' diff --git a/src/main/git/source-control/submodule-gitlink-oid.ts b/src/main/git/source-control/submodule-gitlink-oid.ts index e0cc4530ba9..fcfe6bf0907 100644 --- a/src/main/git/source-control/submodule-gitlink-oid.ts +++ b/src/main/git/source-control/submodule-gitlink-oid.ts @@ -1,6 +1,7 @@ import type { GitRuntimeOptions } from '../git-runtime-options' import { gitOptionsForWorktree } from '../git-runtime-options' -import { gitExecFileAsync, gitOptionalLocksDisabledEnv } from '../runner' +import { gitExecFileAsync } from '../command-runner/git-exec-file' +import { gitOptionalLocksDisabledEnv } from '../command-runner/git-environment/git-process-env' import { literalPathspec } from './git-pathspec' export async function readGitlinkOidFromTree( diff --git a/src/main/git/source-control/submodule-paths.ts b/src/main/git/source-control/submodule-paths.ts index 2f0260f1fde..1e6ca5fe21a 100644 --- a/src/main/git/source-control/submodule-paths.ts +++ b/src/main/git/source-control/submodule-paths.ts @@ -1,7 +1,8 @@ import * as path from 'node:path' import type { GitRuntimeOptions } from '../git-runtime-options' import { gitOptionsForWorktree } from '../git-runtime-options' -import { gitExecFileAsync, gitOptionalLocksDisabledEnv } from '../runner' +import { gitExecFileAsync } from '../command-runner/git-exec-file' +import { gitOptionalLocksDisabledEnv } from '../command-runner/git-environment/git-process-env' import { gitRuntimeOptionsKey } from './git-runtime-options-cache-key' import { iterateNulDelimitedFields } from '../../../shared/nul-delimited-fields' diff --git a/src/main/git/source-control/submodule-restore-recurse.ts b/src/main/git/source-control/submodule-restore-recurse.ts index b72334cd8b7..58e601ec518 100644 --- a/src/main/git/source-control/submodule-restore-recurse.ts +++ b/src/main/git/source-control/submodule-restore-recurse.ts @@ -2,7 +2,7 @@ import type { GitStatusEntry } from '../../../shared/git/status/git-status-types import { isWorktreeUndiscardableGitlink } from '../../../shared/source-control/listing/source-control-discard-all-sequence' import type { GitRuntimeOptions } from '../git-runtime-options' import { gitReadOptionsForWorktree } from '../git-runtime-options' -import { gitExecFileAsync } from '../runner' +import { gitExecFileAsync } from '../command-runner/git-exec-file' /** Plain `git restore` recurses into submodules when submodule.recurse is on, so those gitlinks stay discardable. */ export async function markRecursiveSubmoduleRestores( diff --git a/src/main/git/source-control/submodule-status.ts b/src/main/git/source-control/submodule-status.ts index 0870519ebb5..d2e5a35e6aa 100644 --- a/src/main/git/source-control/submodule-status.ts +++ b/src/main/git/source-control/submodule-status.ts @@ -6,7 +6,8 @@ import { import { gitChangeListArgs, parseGitChangeList } from '../../../shared/git/diff/git-change-list' import type { GitRuntimeOptions } from '../git-runtime-options' import { gitOptionsForWorktree } from '../git-runtime-options' -import { gitExecFileAsync, gitOptionalLocksDisabledEnv } from '../runner' +import { gitExecFileAsync } from '../command-runner/git-exec-file' +import { gitOptionalLocksDisabledEnv } from '../command-runner/git-environment/git-process-env' import type { GetStatusOptions } from './get-status-options' import { getStatus } from './status-read' import { resolveSubmoduleWorktreePath } from './submodule-paths' diff --git a/src/main/git/source-control/textconv-driver.ts b/src/main/git/source-control/textconv-driver.ts index 3f1136d7f98..1c4898f2ce6 100644 --- a/src/main/git/source-control/textconv-driver.ts +++ b/src/main/git/source-control/textconv-driver.ts @@ -4,7 +4,7 @@ import { } from '../../../shared/file-preview/file-preview-kind' import type { GitRuntimeOptions } from '../git-runtime-options' import { gitReadOptionsForWorktree } from '../git-runtime-options' -import { gitExecFileAsync } from '../runner' +import { gitExecFileAsync } from '../command-runner/git-exec-file' /** Image/PDF diffs preview the stored bytes, so a diff driver must not replace them. */ export function isImageOrPdfPreviewPath(filePath: string): boolean { diff --git a/src/main/git/task-repository-eligibility.ts b/src/main/git/task-repository-eligibility.ts index b91c9616aeb..d25ff3ca392 100644 --- a/src/main/git/task-repository-eligibility.ts +++ b/src/main/git/task-repository-eligibility.ts @@ -5,7 +5,7 @@ import { parseGitHubRemoteIdentity } from '../github/github-remote-identity-pars import { getGlabKnownHosts, getGlabPartialHosts } from '../gitlab/projects/gitlab-known-host-probe' import { parseGitLabProjectRef } from '../gitlab/projects/project-ref-parser' import { REMOTE_URL_PROBE_TIMEOUT_MS } from './remotes/remote-url-probe' -import { gitExecFileAsync } from './runner' +import { gitExecFileAsync } from './command-runner/git-exec-file' import type { RemoteRefLocalGitOptions } from './remotes/remote-ref-probe-cache' /** Call only after the requested provider found no usable source; unknown is never exclusion evidence. */ diff --git a/src/main/git/worktrees/catalog/worktree-created-description-real-git.test.ts b/src/main/git/worktrees/catalog/worktree-created-description-real-git.test.ts index 06e5c6a1168..349608f2288 100644 --- a/src/main/git/worktrees/catalog/worktree-created-description-real-git.test.ts +++ b/src/main/git/worktrees/catalog/worktree-created-description-real-git.test.ts @@ -8,7 +8,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { clearGitCapabilityStateForTests, getLocalGitCapabilityCache -} from '../../command-runner/git-capability-state' +} from '../../command-runner/host-routing/git-capability-state' import { describeCreatedWorktree } from './worktree-listing' const execFileAsync = promisify(execFile) diff --git a/src/main/git/worktrees/catalog/worktree-git-capabilities.test.ts b/src/main/git/worktrees/catalog/worktree-git-capabilities.test.ts index 11802a3d696..2beda96af0c 100644 --- a/src/main/git/worktrees/catalog/worktree-git-capabilities.test.ts +++ b/src/main/git/worktrees/catalog/worktree-git-capabilities.test.ts @@ -14,12 +14,12 @@ vi.mock('../../command-runner/git-exec-file-sync', async (importOriginal) => ({ gitExecFileSync: vi.fn() })) -vi.mock('../../command-runner/wsl-path-translation', async (importOriginal) => ({ +vi.mock('../../command-runner/host-routing/wsl-path-translation', async (importOriginal) => ({ ...(await importOriginal>()), translateWslOutputPaths: (output: string) => output })) -import { clearGitCapabilityStateForTests } from '../../command-runner/git-capability-state' +import { clearGitCapabilityStateForTests } from '../../command-runner/host-routing/git-capability-state' import { listWorktrees } from './worktree-scan-cache' const WORKTREE_LIST_OUTPUT = `worktree /repo diff --git a/src/main/git/worktrees/catalog/worktree-graph-listing.test.ts b/src/main/git/worktrees/catalog/worktree-graph-listing.test.ts index 7284de99a17..62291b64f38 100644 --- a/src/main/git/worktrees/catalog/worktree-graph-listing.test.ts +++ b/src/main/git/worktrees/catalog/worktree-graph-listing.test.ts @@ -22,7 +22,7 @@ vi.mock('../../command-runner/git-exec-file-sync', async (importOriginal) => ({ gitExecFileSync: gitExecFileSyncMock })) -vi.mock('../../command-runner/wsl-path-translation', async (importOriginal) => ({ +vi.mock('../../command-runner/host-routing/wsl-path-translation', async (importOriginal) => ({ ...(await importOriginal>()), translateWslOutputPaths: translateWslOutputPathsMock })) diff --git a/src/main/git/worktrees/catalog/worktree-list-porcelain.test.ts b/src/main/git/worktrees/catalog/worktree-list-porcelain.test.ts index 2a7c390d8f8..69a5a31558b 100644 --- a/src/main/git/worktrees/catalog/worktree-list-porcelain.test.ts +++ b/src/main/git/worktrees/catalog/worktree-list-porcelain.test.ts @@ -31,7 +31,7 @@ vi.mock('../../command-runner/git-exec-file-sync', async (importOriginal) => ({ gitExecFileSync: gitExecFileSyncMock })) -vi.mock('../../command-runner/wsl-path-translation', async (importOriginal) => ({ +vi.mock('../../command-runner/host-routing/wsl-path-translation', async (importOriginal) => ({ ...(await importOriginal>()), translateWslOutputPaths: translateWslOutputPathsMock })) diff --git a/src/main/git/worktrees/catalog/worktree-list-reader-cancellation.test.ts b/src/main/git/worktrees/catalog/worktree-list-reader-cancellation.test.ts index acd3494e2a8..6bbb2ce01d6 100644 --- a/src/main/git/worktrees/catalog/worktree-list-reader-cancellation.test.ts +++ b/src/main/git/worktrees/catalog/worktree-list-reader-cancellation.test.ts @@ -17,7 +17,7 @@ vi.mock('../../command-runner/git-exec-file', async (importOriginal) => ({ gitExecFileAsync: gitExec })) -vi.mock('../../command-runner/wsl-path-translation', async (importOriginal) => ({ +vi.mock('../../command-runner/host-routing/wsl-path-translation', async (importOriginal) => ({ ...(await importOriginal>()), translateWslOutputPaths: (output: string) => output })) @@ -25,7 +25,7 @@ vi.mock('../../../../shared/git/worktrees/git-worktree-admin', () => ({ annotateWorktreeLocksFromAdmin: async (_repoPath: string, rows: GitWorktreeInfo[]) => rows })) -import { clearGitCapabilityStateForTests } from '../../command-runner/git-capability-state' +import { clearGitCapabilityStateForTests } from '../../command-runner/host-routing/git-capability-state' import { readWorktreeList } from './worktree-list-reader' function porcelainRow(worktreePath: string, markers: string[] = []): string { diff --git a/src/main/git/worktrees/catalog/worktree-list-reader.ts b/src/main/git/worktrees/catalog/worktree-list-reader.ts index b2b2e94c34d..3d698a022f5 100644 --- a/src/main/git/worktrees/catalog/worktree-list-reader.ts +++ b/src/main/git/worktrees/catalog/worktree-list-reader.ts @@ -11,7 +11,7 @@ import { isUnsupportedRevParsePathFormatError, isUnsupportedWorktreeListZError } from '../../../../shared/git/worktrees/git-worktree-command-capabilities' -import { withLocalGitCapabilityCacheForExecution } from '../../command-runner/git-capability-state' +import { withLocalGitCapabilityCacheForExecution } from '../../command-runner/host-routing/git-capability-state' import { parseWorktreeList } from '../../../../shared/git/worktrees/git-worktree-porcelain-parser' import type { GitWorktreeExecOptions } from '../worktree-operation-options' import { diff --git a/src/main/git/worktrees/catalog/worktree-path-comparison.ts b/src/main/git/worktrees/catalog/worktree-path-comparison.ts index f4e3ab1cb09..6005d8e4111 100644 --- a/src/main/git/worktrees/catalog/worktree-path-comparison.ts +++ b/src/main/git/worktrees/catalog/worktree-path-comparison.ts @@ -2,7 +2,7 @@ import { posix, win32 } from 'node:path' import { isWindowsAbsolutePathLike } from '../../../../shared/cross-platform-path' import { foldWslUncPathCaseInsensitiveParts } from '../../../../shared/wsl-paths' import type { GitWorktreeExecOptions } from '../worktree-operation-options' -import { translateWslOutputPaths } from '../../command-runner/wsl-path-translation' +import { translateWslOutputPaths } from '../../command-runner/host-routing/wsl-path-translation' /** Path syntax determines case folding: preserve POSIX and WSL ext4 tails even on Windows to avoid merging checkouts. */ export function canonicalWorktreePath(pathValue: string, platform = process.platform): string { diff --git a/src/main/git/worktrees/catalog/worktree-scan-cache.ts b/src/main/git/worktrees/catalog/worktree-scan-cache.ts index db33e4875ec..fb7aa1473c9 100644 --- a/src/main/git/worktrees/catalog/worktree-scan-cache.ts +++ b/src/main/git/worktrees/catalog/worktree-scan-cache.ts @@ -7,7 +7,7 @@ import { } from './worktree-listing' import type { GitWorktreeExecOptions } from '../worktree-operation-options' import { WORKTREE_LIST_TIMEOUT_MS } from '../worktree-operation-options' -import { resolveGitAdmissionTier } from '../../command-runner/git-operation-executor' +import { resolveGitAdmissionTier } from '../../command-runner/admission/git-operation-executor' const inFlightWorktreeScans = new Map>() diff --git a/src/main/git/command-runner/checkout-workers-git-args.ts b/src/main/git/worktrees/creation/checkout-workers-git-args.ts similarity index 88% rename from src/main/git/command-runner/checkout-workers-git-args.ts rename to src/main/git/worktrees/creation/checkout-workers-git-args.ts index 51b47ebd779..f6d75b709e7 100644 --- a/src/main/git/command-runner/checkout-workers-git-args.ts +++ b/src/main/git/worktrees/creation/checkout-workers-git-args.ts @@ -1,9 +1,9 @@ -import { gitExecFileAsync } from './git-exec-file' +import { gitExecFileAsync } from '../../command-runner/git-exec-file' import { getErrorCode, gitExecOptions, type GitWorktreeExecOptions -} from '../worktrees/worktree-operation-options' +} from '../worktree-operation-options' // Git checks out with one worker by default; 0 means one per core (Git 2.32+; older Git ignores the key). const PARALLEL_CHECKOUT_GIT_ARGS = ['-c', 'checkout.workers=0'] as const diff --git a/src/main/git/worktrees/creation/worktree-add-local-base-refresh.test.ts b/src/main/git/worktrees/creation/worktree-add-local-base-refresh.test.ts index a7aa2da16bc..bea59c9948d 100644 --- a/src/main/git/worktrees/creation/worktree-add-local-base-refresh.test.ts +++ b/src/main/git/worktrees/creation/worktree-add-local-base-refresh.test.ts @@ -24,13 +24,13 @@ vi.mock('../../command-runner/git-exec-file-sync', async (importOriginal) => ({ gitExecFileSync: gitExecFileSyncMock })) -vi.mock('../../command-runner/wsl-path-translation', async (importOriginal) => ({ +vi.mock('../../command-runner/host-routing/wsl-path-translation', async (importOriginal) => ({ ...(await importOriginal>()), translateWslOutputPaths: translateWslOutputPathsMock })) // Keep the ordered runner queues; worktree-checkout-progress-real-git covers the checkout.workers read. -vi.mock('../../command-runner/checkout-workers-git-args', () => ({ +vi.mock('./checkout-workers-git-args', () => ({ checkoutWorkersGitArgs: async () => [] })) diff --git a/src/main/git/worktrees/creation/worktree-add-pending-removal.test.ts b/src/main/git/worktrees/creation/worktree-add-pending-removal.test.ts index c08689a5b20..a45c2af7ff2 100644 --- a/src/main/git/worktrees/creation/worktree-add-pending-removal.test.ts +++ b/src/main/git/worktrees/creation/worktree-add-pending-removal.test.ts @@ -18,7 +18,7 @@ vi.mock('../../command-runner/git-exec-file-sync', async (importOriginal) => ({ gitExecFileSync: gitExecFileSyncMock })) -vi.mock('../../command-runner/wsl-path-translation', async (importOriginal) => ({ +vi.mock('../../command-runner/host-routing/wsl-path-translation', async (importOriginal) => ({ ...(await importOriginal>()), translateWslOutputPaths: translateWslOutputPathsMock })) diff --git a/src/main/git/worktrees/creation/worktree-add.ts b/src/main/git/worktrees/creation/worktree-add.ts index dee5d5fc274..02ffb4d41f7 100644 --- a/src/main/git/worktrees/creation/worktree-add.ts +++ b/src/main/git/worktrees/creation/worktree-add.ts @@ -5,11 +5,11 @@ import type { LocalBaseRefUpdateSuggestion } from '../../../../shared/worktree/base-ref-drift-types' import { windowsLongPathGitArgs } from '../../../../shared/windows-long-path-git-args' -import { checkoutWorkersGitArgs } from '../../command-runner/checkout-workers-git-args' +import { checkoutWorkersGitArgs } from './checkout-workers-git-args' import { withRepoRefMaintenancePaused } from '../../refs/maintenance/local-repo-ref-maintenance' import { gitExecFileAsync } from '../../command-runner/git-exec-file' import { runWithGitReadCacheInvalidation } from '../../source-control/git-read-cache-invalidation' -import { invalidateWslLinkedWorktreeGitRouting } from '../../command-runner/wsl-linked-worktree-git-routing' +import { invalidateWslLinkedWorktreeGitRouting } from '../../command-runner/host-routing/wsl-linked-worktree-git-routing' import { getLocalBaseRefUpdateSuggestionForWorktreeCreate, parseRemoteTrackingLocalBaseRef, diff --git a/src/main/git/worktrees/creation/worktree-base-refresh-contention.test.ts b/src/main/git/worktrees/creation/worktree-base-refresh-contention.test.ts index 80bc0a630d4..b4a651fc6cd 100644 --- a/src/main/git/worktrees/creation/worktree-base-refresh-contention.test.ts +++ b/src/main/git/worktrees/creation/worktree-base-refresh-contention.test.ts @@ -10,7 +10,7 @@ vi.mock('../../command-runner/git-exec-file', async (importOriginal) => ({ gitExecFileAsync: gitExecFileAsyncMock })) -vi.mock('../../command-runner/wsl-path-translation', async (importOriginal) => ({ +vi.mock('../../command-runner/host-routing/wsl-path-translation', async (importOriginal) => ({ ...(await importOriginal>()), translateWslOutputPaths: (output: string) => output })) diff --git a/src/main/git/worktrees/creation/worktree-base-refresh.ts b/src/main/git/worktrees/creation/worktree-base-refresh.ts index 721d015f428..42860123029 100644 --- a/src/main/git/worktrees/creation/worktree-base-refresh.ts +++ b/src/main/git/worktrees/creation/worktree-base-refresh.ts @@ -13,7 +13,7 @@ import { type LocalBaseBranchGit } from '../../../../shared/worktree/local-base-branch-fast-forward' import { gitExecFileAsync } from '../../command-runner/git-exec-file' -import { translateWslOutputPaths } from '../../command-runner/wsl-path-translation' +import { translateWslOutputPaths } from '../../command-runner/host-routing/wsl-path-translation' import { runWithGitReadCacheInvalidation } from '../../source-control/git-read-cache-invalidation' import type { AddWorktreeOptions, GitWorktreeExecOptions } from '../worktree-operation-options' diff --git a/src/main/git/worktrees/creation/worktree-create-git-executor.ts b/src/main/git/worktrees/creation/worktree-create-git-executor.ts index a2ae07bc713..668d7434813 100644 --- a/src/main/git/worktrees/creation/worktree-create-git-executor.ts +++ b/src/main/git/worktrees/creation/worktree-create-git-executor.ts @@ -1,4 +1,4 @@ -import { createGitOperationExecutor } from '../../command-runner/git-operation-executor' +import { createGitOperationExecutor } from '../../command-runner/admission/git-operation-executor' export const worktreeCreateGit = createGitOperationExecutor('interactive') diff --git a/src/main/git/worktrees/creation/worktree-create-preparation.ts b/src/main/git/worktrees/creation/worktree-create-preparation.ts index a4f51be50b6..e2318c2293b 100644 --- a/src/main/git/worktrees/creation/worktree-create-preparation.ts +++ b/src/main/git/worktrees/creation/worktree-create-preparation.ts @@ -1,7 +1,7 @@ import { runStandalonePreparation } from './worktree-preparation-standalone' import { performPreparedWorktreeFinalization } from './worktree-preparation-finalization-work' import { windowsLongPathGitArgs } from '../../../../shared/windows-long-path-git-args' -import { checkoutWorkersGitArgs } from '../../command-runner/checkout-workers-git-args' +import { checkoutWorkersGitArgs } from './checkout-workers-git-args' import { resolveWorktreeAddBaseRef } from '../../../../shared/worktree/base-ref' import type { AddWorktreeOptions, diff --git a/src/main/git/worktrees/creation/worktree-preparation-add.test.ts b/src/main/git/worktrees/creation/worktree-preparation-add.test.ts index 30754d605e5..818ca96c4dd 100644 --- a/src/main/git/worktrees/creation/worktree-preparation-add.test.ts +++ b/src/main/git/worktrees/creation/worktree-preparation-add.test.ts @@ -28,9 +28,9 @@ import { addLockedWorktreePreparation } from './worktree-preparation-add' import { clearGitCapabilityStateForTests, getLocalGitCapabilityCache -} from '../../command-runner/git-capability-state' +} from '../../command-runner/host-routing/git-capability-state' import { WorktreePreparationLockOwnershipError } from './worktree-preparation-lock' -import { resetWslLinkedWorktreeGitRoutingForTests } from '../../command-runner/wsl-linked-worktree-git-routing' +import { resetWslLinkedWorktreeGitRoutingForTests } from '../../command-runner/host-routing/wsl-linked-worktree-git-routing' const reason = 'orca-create-preparation:v1:123:atomic' const unsupported = Object.assign(new Error("error: unknown option 'reason'"), { code: 129 }) diff --git a/src/main/git/worktrees/creation/worktree-preparation-add.ts b/src/main/git/worktrees/creation/worktree-preparation-add.ts index 55c8f66e11b..3e6cc7046b8 100644 --- a/src/main/git/worktrees/creation/worktree-preparation-add.ts +++ b/src/main/git/worktrees/creation/worktree-preparation-add.ts @@ -4,7 +4,7 @@ import { isUnsupportedWorktreeAddLockReasonError } from '../../../../shared/git/ import { resolveWorktreeHostPath } from '../../../../shared/git/metadata/git-metadata-path' import { windowsLongPathGitArgs } from '../../../../shared/windows-long-path-git-args' import { toHostFilesystemPath } from '../../../filesystem/host-tree-removal' -import { withLocalGitCapabilityCacheForExecution } from '../../command-runner/git-capability-state' +import { withLocalGitCapabilityCacheForExecution } from '../../command-runner/host-routing/git-capability-state' import { gitExecFileAsync } from '../../command-runner/git-exec-file' import { getErrorCode, @@ -22,7 +22,7 @@ import { verifyWorktreePreparationLock, WorktreePreparationLockOwnershipError } from './worktree-preparation-lock' -import { invalidateWslLinkedWorktreeGitRouting } from '../../command-runner/wsl-linked-worktree-git-routing' +import { invalidateWslLinkedWorktreeGitRouting } from '../../command-runner/host-routing/wsl-linked-worktree-git-routing' async function isAbsent(worktreePath: string, options: GitWorktreeExecOptions): Promise { const hostPath = resolveWorktreeHostPath(worktreePath, options) diff --git a/src/main/git/worktrees/creation/worktree-preparation-base-oid.test.ts b/src/main/git/worktrees/creation/worktree-preparation-base-oid.test.ts index e39121c40db..b6127f220ec 100644 --- a/src/main/git/worktrees/creation/worktree-preparation-base-oid.test.ts +++ b/src/main/git/worktrees/creation/worktree-preparation-base-oid.test.ts @@ -21,7 +21,7 @@ vi.mock('./worktree-base-refresh', async (importOriginal) => ({ vi.mock('../../source-control/git-read-cache-invalidation', () => ({ runWithGitReadCacheInvalidation: (run: () => unknown) => run() })) -vi.mock('../../command-runner/wsl-linked-worktree-git-routing', () => ({ +vi.mock('../../command-runner/host-routing/wsl-linked-worktree-git-routing', () => ({ invalidateWslLinkedWorktreeGitRouting: vi.fn() })) diff --git a/src/main/git/worktrees/creation/worktree-preparation-discard.ts b/src/main/git/worktrees/creation/worktree-preparation-discard.ts index 0e750c75b17..322af87c4b5 100644 --- a/src/main/git/worktrees/creation/worktree-preparation-discard.ts +++ b/src/main/git/worktrees/creation/worktree-preparation-discard.ts @@ -26,7 +26,7 @@ import { verifyWorktreePreparationLockAtPath, WorktreePreparationLockOwnershipError } from './worktree-preparation-lock' -import { invalidateWslLinkedWorktreeGitRouting } from '../../command-runner/wsl-linked-worktree-git-routing' +import { invalidateWslLinkedWorktreeGitRouting } from '../../command-runner/host-routing/wsl-linked-worktree-git-routing' export function gitCleanupOptions( cwd: string, diff --git a/src/main/git/worktrees/creation/worktree-preparation-fallback-cleanup-real-git.test.ts b/src/main/git/worktrees/creation/worktree-preparation-fallback-cleanup-real-git.test.ts index a45c1e01678..aae73588661 100644 --- a/src/main/git/worktrees/creation/worktree-preparation-fallback-cleanup-real-git.test.ts +++ b/src/main/git/worktrees/creation/worktree-preparation-fallback-cleanup-real-git.test.ts @@ -8,7 +8,7 @@ import { createWorktreePreparationLockReason } from '../../../../shared/worktree import { clearGitCapabilityStateForTests, getLocalGitCapabilityCache -} from '../../command-runner/git-capability-state' +} from '../../command-runner/host-routing/git-capability-state' import * as runner from '../../command-runner/git-exec-file' import { prepareWorktreeCreateCheckout } from './worktree-create-preparation' import { diff --git a/src/main/git/worktrees/creation/worktree-preparation-finalization-work.ts b/src/main/git/worktrees/creation/worktree-preparation-finalization-work.ts index 25d8169354d..eeb968453b0 100644 --- a/src/main/git/worktrees/creation/worktree-preparation-finalization-work.ts +++ b/src/main/git/worktrees/creation/worktree-preparation-finalization-work.ts @@ -1,5 +1,5 @@ import { windowsLongPathGitArgs } from '../../../../shared/windows-long-path-git-args' -import { checkoutWorkersGitArgs } from '../../command-runner/checkout-workers-git-args' +import { checkoutWorkersGitArgs } from './checkout-workers-git-args' import type { AddWorktreeOptions } from '../worktree-operation-options' import { gitExecOptions, resolveWorktreeAddTimeoutMs } from '../worktree-operation-options' import { @@ -12,7 +12,7 @@ import { bumpWorktreeScanGeneration as notifyPreparedWorktreeMutation } from '.. import type { WorktreePreparationOperation } from './worktree-preparation-operation' import { gitExecFileAsync } from '../../command-runner/git-exec-file' import { runWithGitReadCacheInvalidation } from '../../source-control/git-read-cache-invalidation' -import { invalidateWslLinkedWorktreeGitRouting } from '../../command-runner/wsl-linked-worktree-git-routing' +import { invalidateWslLinkedWorktreeGitRouting } from '../../command-runner/host-routing/wsl-linked-worktree-git-routing' import { unlockWorktreePreparationAtPath, verifyWorktreePreparationLock, diff --git a/src/main/git/worktrees/creation/worktree-preparation-tip-refresh.ts b/src/main/git/worktrees/creation/worktree-preparation-tip-refresh.ts index a2807200bc0..9394f40c304 100644 --- a/src/main/git/worktrees/creation/worktree-preparation-tip-refresh.ts +++ b/src/main/git/worktrees/creation/worktree-preparation-tip-refresh.ts @@ -1,6 +1,6 @@ import type { WorktreePreparationOperation } from './worktree-preparation-operation' import { windowsLongPathGitArgs } from '../../../../shared/windows-long-path-git-args' -import { checkoutWorkersGitArgs } from '../../command-runner/checkout-workers-git-args' +import { checkoutWorkersGitArgs } from './checkout-workers-git-args' import { withRepoRefMaintenancePaused } from '../../refs/maintenance/local-repo-ref-maintenance' import { gitExecFileAsync } from '../../command-runner/git-exec-file' import { runWithGitReadCacheInvalidation } from '../../source-control/git-read-cache-invalidation' diff --git a/src/main/git/worktrees/creation/worktree-sparse-add.ts b/src/main/git/worktrees/creation/worktree-sparse-add.ts index 4dffa3eabe7..f8f25a9e8a8 100644 --- a/src/main/git/worktrees/creation/worktree-sparse-add.ts +++ b/src/main/git/worktrees/creation/worktree-sparse-add.ts @@ -1,5 +1,5 @@ import { windowsLongPathGitArgs } from '../../../../shared/windows-long-path-git-args' -import { checkoutWorkersGitArgs } from '../../command-runner/checkout-workers-git-args' +import { checkoutWorkersGitArgs } from './checkout-workers-git-args' import { gitExecFileAsync } from '../../command-runner/git-exec-file' import { addWorktree, unsetWorktreeCreationBase } from './worktree-add' import type { diff --git a/src/main/git/worktrees/movement/worktree-move.test.ts b/src/main/git/worktrees/movement/worktree-move.test.ts index fd10acde868..92835fc8f12 100644 --- a/src/main/git/worktrees/movement/worktree-move.test.ts +++ b/src/main/git/worktrees/movement/worktree-move.test.ts @@ -22,7 +22,7 @@ vi.mock('../../command-runner/git-exec-file-sync', async (importOriginal) => ({ gitExecFileSync: gitExecFileSyncMock })) -vi.mock('../../command-runner/wsl-path-translation', async (importOriginal) => ({ +vi.mock('../../command-runner/host-routing/wsl-path-translation', async (importOriginal) => ({ ...(await importOriginal>()), translateWslOutputPaths: translateWslOutputPathsMock })) diff --git a/src/main/git/worktrees/movement/worktree-move.ts b/src/main/git/worktrees/movement/worktree-move.ts index 7b171f920bc..239dbbb4ab8 100644 --- a/src/main/git/worktrees/movement/worktree-move.ts +++ b/src/main/git/worktrees/movement/worktree-move.ts @@ -1,6 +1,6 @@ import { gitExecFileAsync } from '../../command-runner/git-exec-file' import { runWithGitReadCacheInvalidation } from '../../source-control/git-read-cache-invalidation' -import { invalidateWslLinkedWorktreeGitRouting } from '../../command-runner/wsl-linked-worktree-git-routing' +import { invalidateWslLinkedWorktreeGitRouting } from '../../command-runner/host-routing/wsl-linked-worktree-git-routing' import { bumpWorktreeScanGeneration } from '../catalog/worktree-scan-cache' import { invalidateSparseCheckoutState } from '../sparse-checkout/worktree-sparse-checkout-cache' diff --git a/src/main/git/worktrees/removal/remove-worktree-branch-cleanup.test.ts b/src/main/git/worktrees/removal/remove-worktree-branch-cleanup.test.ts index def779b6e45..96dfb425e2e 100644 --- a/src/main/git/worktrees/removal/remove-worktree-branch-cleanup.test.ts +++ b/src/main/git/worktrees/removal/remove-worktree-branch-cleanup.test.ts @@ -32,7 +32,7 @@ vi.mock('../../command-runner/git-exec-file-sync', async (importOriginal) => ({ gitExecFileSync: gitExecFileSyncMock })) -vi.mock('../../command-runner/wsl-path-translation', async (importOriginal) => ({ +vi.mock('../../command-runner/host-routing/wsl-path-translation', async (importOriginal) => ({ ...(await importOriginal>()), translateWslOutputPaths: translateWslOutputPathsMock })) diff --git a/src/main/git/worktrees/removal/remove-worktree-clean-preflight.test.ts b/src/main/git/worktrees/removal/remove-worktree-clean-preflight.test.ts index dda7218a1d7..b891958bae4 100644 --- a/src/main/git/worktrees/removal/remove-worktree-clean-preflight.test.ts +++ b/src/main/git/worktrees/removal/remove-worktree-clean-preflight.test.ts @@ -27,7 +27,7 @@ vi.mock('../../command-runner/git-exec-file-sync', async (importOriginal) => ({ gitExecFileSync: gitExecFileSyncMock })) -vi.mock('../../command-runner/wsl-path-translation', async (importOriginal) => ({ +vi.mock('../../command-runner/host-routing/wsl-path-translation', async (importOriginal) => ({ ...(await importOriginal>()), translateWslOutputPaths: translateWslOutputPathsMock })) diff --git a/src/main/git/worktrees/removal/remove-worktree-test-harness.ts b/src/main/git/worktrees/removal/remove-worktree-test-harness.ts index f6163547587..397ad5c1ae5 100644 --- a/src/main/git/worktrees/removal/remove-worktree-test-harness.ts +++ b/src/main/git/worktrees/removal/remove-worktree-test-harness.ts @@ -1,6 +1,6 @@ import { expect, type Mock } from 'vitest' -import { clearGitCapabilityStateForTests } from '../../command-runner/git-capability-state' +import { clearGitCapabilityStateForTests } from '../../command-runner/host-routing/git-capability-state' import { _resetWorktreeScanCacheForTests } from '../catalog/worktree-scan-cache' import { __resetSparseCheckoutStateCacheForTests } from '../sparse-checkout/worktree-sparse-checkout-cache' diff --git a/src/main/git/worktrees/removal/remove-worktree.test.ts b/src/main/git/worktrees/removal/remove-worktree.test.ts index 77d7da1c19d..eba05bac7e1 100644 --- a/src/main/git/worktrees/removal/remove-worktree.test.ts +++ b/src/main/git/worktrees/removal/remove-worktree.test.ts @@ -31,7 +31,7 @@ vi.mock('../../command-runner/git-exec-file-sync', async (importOriginal) => ({ gitExecFileSync: gitExecFileSyncMock })) -vi.mock('../../command-runner/wsl-path-translation', async (importOriginal) => ({ +vi.mock('../../command-runner/host-routing/wsl-path-translation', async (importOriginal) => ({ ...(await importOriginal>()), translateWslOutputPaths: translateWslOutputPathsMock })) diff --git a/src/main/git/worktrees/removal/worktree-branch-removal.ts b/src/main/git/worktrees/removal/worktree-branch-removal.ts index d95262bb9d9..0bfa47ba576 100644 --- a/src/main/git/worktrees/removal/worktree-branch-removal.ts +++ b/src/main/git/worktrees/removal/worktree-branch-removal.ts @@ -5,7 +5,7 @@ import { type GitBranchCleanupExecOptions } from '../../../../shared/git/branches/git-branch-cleanup' import type { RemoveWorktreeResult } from '../../../../shared/worktree/create-types' -import { withLocalGitCapabilityCacheForExecution } from '../../command-runner/git-capability-state' +import { withLocalGitCapabilityCacheForExecution } from '../../command-runner/host-routing/git-capability-state' import { withRepoRefMaintenancePaused } from '../../refs/maintenance/local-repo-ref-maintenance' import { gitExecFileAsync } from '../../command-runner/git-exec-file' import { createLocalGitObjectQuarantine } from '../../local-git-object-quarantine' diff --git a/src/main/git/worktrees/removal/worktree-prune-guard.test.ts b/src/main/git/worktrees/removal/worktree-prune-guard.test.ts index ebff63ae9fd..3deecabfb43 100644 --- a/src/main/git/worktrees/removal/worktree-prune-guard.test.ts +++ b/src/main/git/worktrees/removal/worktree-prune-guard.test.ts @@ -34,7 +34,7 @@ vi.mock('../../../../shared/wsl-paths', async (importOriginal) => ({ ...(await importOriginal>()), wslDistroForCommand: wslDistroForCommandMock })) -vi.mock('../../command-runner/wsl-linked-worktree-git-routing', () => ({ +vi.mock('../../command-runner/host-routing/wsl-linked-worktree-git-routing', () => ({ usesHostGitForWslLinkedWorktree: () => false })) vi.mock('../../wsl-drive-checkout-git-routing', () => ({ diff --git a/src/main/git/worktrees/removal/worktree-prune-guard.ts b/src/main/git/worktrees/removal/worktree-prune-guard.ts index 10696a93e71..1fb819c64f2 100644 --- a/src/main/git/worktrees/removal/worktree-prune-guard.ts +++ b/src/main/git/worktrees/removal/worktree-prune-guard.ts @@ -10,7 +10,7 @@ import { import type { GitExecOptions } from '../../command-runner/git-exec-options' import { gitExecFileAsync } from '../../command-runner/git-exec-file' import { pendingWslDriveCheckoutGitRouting } from '../../wsl-drive-checkout-git-routing' -import { usesHostGitForWslLinkedWorktree } from '../../command-runner/wsl-linked-worktree-git-routing' +import { usesHostGitForWslLinkedWorktree } from '../../command-runner/host-routing/wsl-linked-worktree-git-routing' /** Marks only the locks this module writes, so it never removes a user's own lock. */ export const PRUNE_GUARD_LOCK_REASON = diff --git a/src/main/git/worktrees/removal/worktree-removal.ts b/src/main/git/worktrees/removal/worktree-removal.ts index 8799659ead8..7fe0c1fb934 100644 --- a/src/main/git/worktrees/removal/worktree-removal.ts +++ b/src/main/git/worktrees/removal/worktree-removal.ts @@ -1,5 +1,5 @@ import { lstat } from 'node:fs/promises' -import { gitEnvWithoutYesNoPrompt } from '../../command-runner/git-no-prompt-env' +import { gitEnvWithoutYesNoPrompt } from '../../command-runner/git-environment/git-no-prompt-env' import { pruneGitWorktrees } from './worktree-prune-guard' import type { RemoveWorktreeResult } from '../../../../shared/worktree/create-types' import { assertWorktreeUnlockedForRemoval } from '../../../../shared/worktree/removal' @@ -10,7 +10,7 @@ import { parseWslPath } from '../../../wsl/filesystem/unc-path-access' import { gitExecFileAsync } from '../../command-runner/git-exec-file' import { runWithGitReadCacheInvalidation } from '../../source-control/git-read-cache-invalidation' import { deleteBranchAfterWorktreeRemoval } from './worktree-branch-removal' -import { invalidateWslLinkedWorktreeGitRouting } from '../../command-runner/wsl-linked-worktree-git-routing' +import { invalidateWslLinkedWorktreeGitRouting } from '../../command-runner/host-routing/wsl-linked-worktree-git-routing' import { type RemoveWorktreeOptions, diff --git a/src/main/git/worktrees/removal/worktree-remove-branch-deletion.test.ts b/src/main/git/worktrees/removal/worktree-remove-branch-deletion.test.ts index c2f90bba427..0ecaa9b0af5 100644 --- a/src/main/git/worktrees/removal/worktree-remove-branch-deletion.test.ts +++ b/src/main/git/worktrees/removal/worktree-remove-branch-deletion.test.ts @@ -18,7 +18,7 @@ vi.mock('../../command-runner/git-exec-file-sync', async (importOriginal) => ({ gitExecFileSync: gitExecFileSyncMock })) -vi.mock('../../command-runner/wsl-path-translation', async (importOriginal) => ({ +vi.mock('../../command-runner/host-routing/wsl-path-translation', async (importOriginal) => ({ ...(await importOriginal>()), translateWslOutputPaths: translateWslOutputPathsMock })) diff --git a/src/main/git/worktrees/testing/worktree-test-harness.ts b/src/main/git/worktrees/testing/worktree-test-harness.ts index 9c00fc06739..c0a7a9ca27b 100644 --- a/src/main/git/worktrees/testing/worktree-test-harness.ts +++ b/src/main/git/worktrees/testing/worktree-test-harness.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, vi } from 'vitest' -import { clearGitCapabilityStateForTests } from '../../command-runner/git-capability-state' +import { clearGitCapabilityStateForTests } from '../../command-runner/host-routing/git-capability-state' import { __resetSparseCheckoutStateCacheForTests } from '../sparse-checkout/worktree-sparse-checkout-cache' export function registerWorktreeSuiteHooks(): void { diff --git a/src/main/git/wsl-drive-checkout-git-routing.ts b/src/main/git/wsl-drive-checkout-git-routing.ts index 658820dbaa8..c61cb7ff8dc 100644 --- a/src/main/git/wsl-drive-checkout-git-routing.ts +++ b/src/main/git/wsl-drive-checkout-git-routing.ts @@ -1,9 +1,9 @@ -import type { GitAdmissionTier } from './command-runner/git-exec-options' +import type { GitAdmissionTier } from '../../shared/rpc-contract/git-admission-tier-params' import { isWslLinkedWorktreeGitRoutingCandidate, prepareWslLinkedWorktreeGitRouting, usesHostGitForWslLinkedWorktree -} from './command-runner/wsl-linked-worktree-git-routing' +} from './command-runner/host-routing/wsl-linked-worktree-git-routing' import { pendingWslWindowsCheckoutGitConfig } from './wsl-windows-checkout-git-probe' /** Settle checkout ownership and Windows-Git config before synchronous routing; null means no drive-checkout command. */ diff --git a/src/main/git/wsl-windows-checkout-git-probe.ts b/src/main/git/wsl-windows-checkout-git-probe.ts index c70f78faa1e..34c3dae745f 100644 --- a/src/main/git/wsl-windows-checkout-git-probe.ts +++ b/src/main/git/wsl-windows-checkout-git-probe.ts @@ -3,10 +3,10 @@ import { win32 } from 'node:path' import { runProcess } from '@orca/process-host' import { resolveSelectedLocalCommand } from '../ipc/command-path/command-path-resolver' import { runWslProcess, type WslResult, type WslSpec } from '../wsl/execution/wsl-runner' -import { translateArgForWsl } from './command-runner/wsl-path-translation' -import { acquireGitAdmission } from './command-runner/git-subprocess-admission' -import { nonInteractiveGitEnv } from './command-runner/git-process-env' -import type { GitAdmissionTier } from './command-runner/git-exec-options' +import { translateArgForWsl } from './command-runner/host-routing/wsl-path-translation' +import { acquireGitAdmission } from './command-runner/admission/git-subprocess-admission' +import { nonInteractiveGitEnv } from './command-runner/git-environment/git-process-env' +import type { GitAdmissionTier } from '../../shared/rpc-contract/git-admission-tier-params' import { isWslDirectGitReadCommand } from '../../shared/git/commands/git-command-classification' import { classifyLineEndingSample, diff --git a/src/main/github/auth-diagnose.test.ts b/src/main/github/auth-diagnose.test.ts index 7fe72ccc14a..2852c9c4ce4 100644 --- a/src/main/github/auth-diagnose.test.ts +++ b/src/main/github/auth-diagnose.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it, vi } from 'vitest' const { ghExecFileAsyncMock } = vi.hoisted(() => ({ ghExecFileAsyncMock: vi.fn() })) -vi.mock('../git/command-runner/gh-exec-file', async (importOriginal) => ({ +vi.mock('../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ ...(await importOriginal>()), ghExecFileAsync: ghExecFileAsyncMock })) diff --git a/src/main/github/auth-diagnose.ts b/src/main/github/auth-diagnose.ts index a07e9a362ed..e7d6c87c760 100644 --- a/src/main/github/auth-diagnose.ts +++ b/src/main/github/auth-diagnose.ts @@ -1,5 +1,5 @@ // Environment tokens override keyring credentials and cannot be refreshed through gh auth refresh. -import { ghExecFileAsync } from '../git/runner' +import { ghExecFileAsync } from '../git/command-runner/hosted-cli/gh-exec-file' import type { GhAuthDiagnostic, GhAuthAccount } from '../../shared/github/auth-types' // ProjectV2 and surrounding repository/organization queries require these scopes. diff --git a/src/main/github/client-merge-queue-auto-merge.test.ts b/src/main/github/client-merge-queue-auto-merge.test.ts index 3a547623a1f..3ef7b0a48e1 100644 --- a/src/main/github/client-merge-queue-auto-merge.test.ts +++ b/src/main/github/client-merge-queue-auto-merge.test.ts @@ -1,5 +1,5 @@ import type * as GitExecFileModule from '../git/command-runner/git-exec-file' -import type * as GhExecFileModule from '../git/command-runner/gh-exec-file' +import type * as GhExecFileModule from '../git/command-runner/hosted-cli/gh-exec-file' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type * as GithubApiRepositoryModule from './github-api-repository' import type * as GitHubEnterpriseRepositoryModule from './github-enterprise-repository' @@ -10,14 +10,13 @@ const { clientMocks, moduleMocks } = await vi.hoisted(async () => { }) vi.mock('./gh-utils', () => moduleMocks.ghUtilsModuleMock(clientMocks)) -vi.mock('../git/runner', () => moduleMocks.gitRunnerModuleMock(clientMocks)) vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ ...(await importOriginal()), gitExecFileAsync: clientMocks.gitExecFileAsyncMock })) -vi.mock('../git/command-runner/gh-exec-file', async (importOriginal) => ({ +vi.mock('../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ ...(await importOriginal()), ghExecFileAsync: clientMocks.ghExecFileAsyncMock })) @@ -40,7 +39,7 @@ vi.mock('./github-api-repository', async (importOriginal) => ) ) import { getWorkItemByOwnerRepo } from './client/fetch/get-work-item' -import { mergePR } from './client/merge/merge-pr' + import { resolveReviewThread } from './client/update/resolve-review-thread' import { setPRAutoMerge } from './client/merge/pr-auto-merge' import { _getMergeQueueCacheSizeForTests } from './client/detect/repository-merge-metadata-cache' @@ -51,7 +50,6 @@ import { const { resolvePRRepositoryCandidatesMock, - gitExecFileAsyncMock, rateLimitGuardMock, noteRateLimitSpendMock, acquireMock @@ -98,148 +96,6 @@ describe('GitHub GraphQL rate-limit guard', () => { ).toBe(false) }) - it('rejects auto-merge for GitHub-registered stacks', async () => { - metadataRequests.mockResolvedValueOnce({ - stdout: JSON.stringify({ - number: 202, - title: 'Stack API', - state: 'open', - head: { ref: 'stack/api', sha: 'head-oid' }, - base: { ref: 'stack/models', sha: 'models-sha' }, - stack: { - number: 51, - position: 2, - size: 2, - base: { ref: 'main', sha: 'main-sha' } - } - }) - }) - - await expect( - setPRAutoMerge('/repo-root', 202, true, 'squash', undefined, { - owner: 'stablyai', - repo: 'orca', - host: 'github.com' - }) - ).resolves.toMatchObject({ - ok: false, - error: 'GitHub does not support auto-merge for stacked pull requests.' - }) - expect(metadataRequests).toHaveBeenCalledTimes(1) - }) - - it('preserves a provider rejection when eligibility changes before enabling auto-merge', async () => { - const providerError = - 'gh: Pull request Pull request is in unstable status (enablePullRequestAutoMerge)' - metadataRequests - .mockResolvedValueOnce({ stdout: JSON.stringify({ stack: null }) }) - .mockResolvedValueOnce({ - stdout: JSON.stringify({ id: 'PR_kwDO123', headRefOid: 'head-oid' }) - }) - .mockRejectedValueOnce(new Error(providerError)) - - await expect( - setPRAutoMerge('/repo-root', 7, true, 'squash', undefined, { - owner: 'stablyai', - repo: 'orca', - host: 'github.com' - }) - ).resolves.toMatchObject({ - ok: false, - error: `Failed to enable auto-merge for pull request: ${providerError}` - }) - expect( - metadataRequests.mock.calls.some(([args]) => args[0] === 'pr' && args[1] === 'merge') - ).toBe(false) - }) - - it('blocks direct merge when GitHub reports required approval', async () => { - metadataRequests - .mockResolvedValueOnce({ stdout: JSON.stringify({ stack: null }) }) - .mockResolvedValueOnce({ - stdout: JSON.stringify({ - number: 7, - title: 'PR', - state: 'OPEN', - url: 'https://github.com/stablyai/orca/pull/7', - statusCheckRollup: [], - updatedAt: '2026-04-01T00:00:00Z', - isDraft: false, - mergeable: 'MERGEABLE', - reviewDecision: 'REVIEW_REQUIRED', - mergeStateStatus: 'CLEAN', - autoMergeRequest: null, - baseRefName: 'main', - baseRefOid: 'base-oid', - headRefOid: 'head-oid' - }) - }) - - await expect( - mergePR('/repo-root', 7, 'squash', undefined, { - owner: 'stablyai', - repo: 'orca', - host: 'github.com' - }) - ).resolves.toEqual({ - ok: false, - error: 'This pull request requires review approval before it can be merged.' - }) - - expect(metadataRequests).toHaveBeenCalledTimes(3) - expect(metadataRequests.mock.calls[2]?.[0]).toContain('graphql') - }) - - it('detects merge queues once per base branch and blocks direct merges', async () => { - const prView = { - number: 7, - title: 'PR', - state: 'OPEN', - url: 'https://github.com/stablyai/orca/pull/7', - statusCheckRollup: [], - updatedAt: '2026-04-01T00:00:00Z', - isDraft: false, - mergeable: 'MERGEABLE', - reviewDecision: 'APPROVED', - mergeStateStatus: 'CLEAN', - autoMergeRequest: null, - baseRefName: 'true', - baseRefOid: 'base-oid', - headRefOid: 'head-oid' - } - metadataRequests - .mockResolvedValueOnce({ stdout: JSON.stringify({ stack: null }) }) - .mockResolvedValueOnce({ stdout: JSON.stringify(prView) }) - .mockResolvedValueOnce({ - stdout: JSON.stringify({ data: { repository: { mergeQueue: { id: 'MQ_kw' } } } }) - }) - .mockResolvedValueOnce({ stdout: JSON.stringify({ stack: null }) }) - .mockResolvedValueOnce({ stdout: JSON.stringify(prView) }) - - await expect( - mergePR('/repo-root', 7, 'squash', undefined, { - owner: 'stablyai', - repo: 'orca', - host: 'github.com' - }) - ).resolves.toEqual({ - ok: false, - error: - 'This pull request must be merged through GitHub merge queue. Use Merge when ready instead.' - }) - await expect( - mergePR('/repo-root', 7, 'squash', undefined, { owner: 'stablyai', repo: 'orca' }) - ).resolves.toMatchObject({ ok: false }) - - expect(metadataRequests.mock.calls.filter((call) => call[0].includes('graphql'))).toHaveLength( - 1 - ) - expect(metadataRequests.mock.calls[2]?.[0]).toEqual( - expect.arrayContaining(['-f', 'owner=stablyai', '-f', 'repo=orca', '-f', 'branch=true']) - ) - expect(metadataRequests.mock.calls[2]?.[0]).not.toContain('-F') - }) - it('rejects explicit work-item lookups outside configured repository candidates', async () => { resolvePRRepositoryCandidatesMock.mockResolvedValueOnce({ candidates: [{ owner: 'acme', repo: 'widgets', host: 'github.com' }], @@ -292,50 +148,6 @@ describe('GitHub GraphQL rate-limit guard', () => { expect(metadataRequests.mock.calls[0]?.[0]).toEqual(['api', 'repos/other/tools/pulls/7']) }) - it('returns conflicting file details instead of running gh merge when PR is dirty', async () => { - metadataRequests - .mockResolvedValueOnce({ stdout: JSON.stringify({ stack: null }) }) - .mockResolvedValueOnce({ - stdout: JSON.stringify({ - number: 7, - title: 'PR', - state: 'OPEN', - url: 'https://github.com/stablyai/orca/pull/7', - statusCheckRollup: [], - updatedAt: '2026-04-01T00:00:00Z', - isDraft: false, - mergeable: 'CONFLICTING', - baseRefName: 'main', - baseRefOid: 'base-oid', - headRefOid: 'head-oid' - }) - }) - gitExecFileAsyncMock - .mockResolvedValueOnce({ stdout: '/repo-root/.git\n' }) - .mockResolvedValueOnce({ stdout: '' }) - .mockResolvedValueOnce({ stdout: 'latest-base-oid\n' }) - .mockResolvedValueOnce({ stdout: 'merge-base-oid\n' }) - .mockResolvedValueOnce({ stdout: '3\n' }) - .mockResolvedValueOnce({ stdout: 'result-tree-oid\u0000src/conflict.ts\u0000' }) - - await expect( - mergePR('/repo-root', 7, 'squash', undefined, { - owner: 'stablyai', - repo: 'orca', - host: 'github.com' - }) - ).resolves.toEqual({ - ok: false, - error: - 'This pull request has merge conflicts and cannot be merged yet.\n' + - '3 commits behind main (base commit: latest-).\n\n' + - 'Conflicting files:\n' + - '- src/conflict.ts' - }) - - expect(metadataRequests).toHaveBeenCalledTimes(2) - }) - it('blocks review-thread resolve mutations before spawning gh when GraphQL is low', async () => { rateLimitGuardMock.mockReturnValue({ blocked: true, diff --git a/src/main/github/client-pr-conversation-requests.test.ts b/src/main/github/client-pr-conversation-requests.test.ts index ddff53aaa9d..baf45c38c54 100644 --- a/src/main/github/client-pr-conversation-requests.test.ts +++ b/src/main/github/client-pr-conversation-requests.test.ts @@ -1,5 +1,5 @@ import type * as GitExecFileModule from '../git/command-runner/git-exec-file' -import type * as GhExecFileModule from '../git/command-runner/gh-exec-file' +import type * as GhExecFileModule from '../git/command-runner/hosted-cli/gh-exec-file' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type * as GithubApiRepositoryModule from './github-api-repository' import type * as GitHubEnterpriseRepositoryModule from './github-enterprise-repository' @@ -10,14 +10,13 @@ const { clientMocks, moduleMocks } = await vi.hoisted(async () => { }) vi.mock('./gh-utils', () => moduleMocks.ghUtilsModuleMock(clientMocks)) -vi.mock('../git/runner', () => moduleMocks.gitRunnerModuleMock(clientMocks)) vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ ...(await importOriginal()), gitExecFileAsync: clientMocks.gitExecFileAsyncMock })) -vi.mock('../git/command-runner/gh-exec-file', async (importOriginal) => ({ +vi.mock('../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ ...(await importOriginal()), ghExecFileAsync: clientMocks.ghExecFileAsyncMock })) @@ -40,18 +39,11 @@ vi.mock('./github-api-repository', async (importOriginal) => import { getPRComments } from './client/fetch/get-pr-comments' import { resetGraphQLRateLimitGuardMocks } from './client-test-harness' -const { ghExecFileAsyncMock, rateLimitGuardMock } = clientMocks +const { ghExecFileAsyncMock } = clientMocks const repository = { owner: 'acme', repo: 'widgets', host: 'github.com' } const options = { prRepo: repository } -const comment = { - id: 'IC_10', - databaseId: 10, - author: null, - body: 'Conversation', - createdAt: '2026-04-01T00:00:00Z', - url: 'https://example.test/comment' -} + function response(pr: unknown, errors?: unknown): { stdout: string } { return { stdout: JSON.stringify({ data: { repository: { pullRequest: pr } }, errors }, (_key, value) => @@ -66,52 +58,6 @@ describe('PR conversation request reuse', () => { beforeEach(() => resetGraphQLRateLimitGuardMocks(clientMocks)) afterEach(() => vi.restoreAllMocks()) - it.each([false, true])( - 'preserves quota failures when REST recovery is needed (GraphQL blocked: %s)', - async (graphQLBlocked) => { - rateLimitGuardMock.mockImplementation((bucket) => - bucket === 'core' || graphQLBlocked - ? { blocked: true, remaining: 0, limit: 5000, resetAt: 1800000000 } - : { blocked: false } - ) - ghExecFileAsyncMock.mockResolvedValue( - response({ comments: { nodes: [comment] }, reviews: null, reviewThreads: { nodes: [] } }) - ) - await expect(getPRComments('/repo', 7, options)).rejects.toThrow('GitHub core rate limit') - expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(graphQLBlocked ? 0 : 1) - } - ) - - it('recovers only the failed GraphQL source from nonzero-exit partial data', async () => { - const partial = response( - { comments: { nodes: [comment] }, reviews: null, reviewThreads: { nodes: [] } }, - [{ message: 'Review unavailable', path: ['repository', 'pullRequest', 'reviews'] }] - ) - ghExecFileAsyncMock - .mockRejectedValueOnce(Object.assign(new Error('GraphQL error'), partial)) - .mockResolvedValueOnce({ stdout: 'me' }) - .mockResolvedValueOnce({ - stdout: JSON.stringify([ - { - id: 11, - user: null, - body: 'Review summary', - submitted_at: '2026-04-01T00:01:00Z', - html_url: 'https://example.test/review' - } - ]) - }) - const comments = await getPRComments('/repo', 7, { ...options, noCache: true }) - expect(comments.map((c) => c.body)).toEqual(['Conversation', 'Review summary']) - expect(ghExecFileAsyncMock.mock.calls[2][0]).toEqual([ - 'api', - '-H', - 'Accept: application/vnd.github.full+json', - 'repos/acme/widgets/pulls/7/reviews?per_page=100' - ]) - expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(3) - }) - it('retains the successful REST source when GraphQL and the other REST source fail', async () => { ghExecFileAsyncMock.mockImplementation(async (args: string[]) => { if (args.includes('graphql')) { @@ -168,383 +114,4 @@ describe('PR conversation request reuse', () => { ['me', true] ]) }) - it.each([0, 100, 1000])( - 'gets image maps in the existing conversation request (%s bodies)', - async (n) => { - const body = - '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' - const imageComments = Array.from({ length: n }, (_, i) => ({ - ...comment, - id: `IMAGE_${i}`, - databaseId: i, - body, - bodyHTML: - '', - path: 'file.ts' - })) - const threads = Array.from({ length: n / 100 }, (_, i) => ({ - id: `THREAD_${i}`, - isResolved: false, - line: 1, - startLine: null, - originalLine: 1, - originalStartLine: null, - comments: { nodes: imageComments.slice(i * 100, (i + 1) * 100) } - })) - ghExecFileAsyncMock.mockResolvedValueOnce( - response({ - comments: { nodes: [comment] }, - reviews: { nodes: [] }, - reviewThreads: { nodes: threads } - }) - ) - const result = await getPRComments('/repo', 7, { ...options, noCache: true }) - // One request owns all selected bodies, independent of their image population. - expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(1) - expect(result.filter((c) => c.path === 'file.ts')).toHaveLength(n) - if (n === 0) { - return - } - expect(result.find((c) => c.id === 0)?.bodyImageUrls).toEqual({ - 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': - 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST' - }) - expect(result.find((c) => c.id === 0)?.body).toBe(body) - } - ) - - it.each([false, true])( - 'holds the existing permit until the paired command settles (reject: %s)', - async (reject) => { - let settle!: (result: { stdout: string }) => void - let fail!: (error: Error) => void - const pending = new Promise<{ stdout: string }>((resolve, reject) => { - settle = resolve - fail = reject - }) - let started!: () => void - const commandStarted = new Promise((resolve) => { - started = resolve - }) - ghExecFileAsyncMock.mockImplementationOnce(() => { - started() - return pending - }) - const read = getPRComments('/repo', 7, { ...options, noCache: true }) - await commandStarted - expect(clientMocks.acquireMock).toHaveBeenCalledTimes(1) - expect(clientMocks.releaseMock).not.toHaveBeenCalled() - const raw = response({ - comments: { nodes: [comment] }, - reviews: { nodes: [] }, - reviewThreads: { nodes: [] } - }) - if (reject) { - fail(Object.assign(new Error('Partial GraphQL response'), raw)) - } else { - settle(raw) - } - const result = await read - expect(result).toMatchObject([{ body: 'Conversation' }]) - expect(clientMocks.releaseMock).toHaveBeenCalledTimes(1) - expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(1) - expect(result[0].bodyImageUrls).toBeUndefined() - } - ) - - it('keeps usable raw fields and siblings when optional HTML errors, without a fallback request', async () => { - const body = - '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' - const html = - '' - const partial = response( - { - comments: { nodes: [{ ...comment, body, bodyHTML: html }] }, - reviews: { nodes: [] }, - reviewThreads: { - nodes: [ - { - id: 'THREAD', - isResolved: false, - line: 1, - startLine: null, - originalLine: 1, - originalStartLine: null, - comments: { - nodes: [ - { ...comment, databaseId: 11, body, bodyHTML: html, path: 'file.ts' }, - { ...comment, databaseId: 12, body, bodyHTML: html, path: 'file.ts' } - ] - } - } - ] - } - }, - [ - { path: ['repository', 'pullRequest', 'comments', 'nodes', 0, 'bodyHTML'] }, - { - path: [ - 'repository', - 'pullRequest', - 'reviewThreads', - 'nodes', - 0, - 'comments', - 'nodes', - 0, - 'bodyHTML' - ] - } - ] - ) - ghExecFileAsyncMock.mockRejectedValueOnce(Object.assign(new Error('GraphQL error'), partial)) - const result = await getPRComments('/repo', 7, { ...options, noCache: true }) - expect(result.map((c) => c.body)).toEqual([body, body, body]) - expect(result.find((c) => c.id === 10)?.bodyImageUrls).toBeUndefined() - expect(result.find((c) => c.id === 11)?.bodyImageUrls).toBeUndefined() - expect(result.find((c) => c.id === 12)?.bodyImageUrls).toEqual({ - 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': - 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST' - }) - expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(1) - }) - it('pages independent sources and nested replies without rereading completed sources', async () => { - const thread = { - id: 'T1', - isResolved: true, - line: 4, - startLine: null, - originalLine: 4, - originalStartLine: null, - rootHunk: { nodes: [{ diffHunk: '@@ -1 +1 @@\n-old\n+new' }] }, - comments: { - nodes: [{ ...comment, id: 'ROOT', databaseId: 11, path: 'a.ts' }], - pageInfo: { hasNextPage: true, endCursor: 'reply-1' } - } - } - ghExecFileAsyncMock.mockImplementation(async (args: string[]) => { - if (args.includes('threadId=T1')) { - return { - stdout: JSON.stringify({ - data: { - node: { - ...thread, - comments: { - nodes: [{ ...comment, id: 'REPLY', databaseId: 12, body: 'Reply', path: 'a.ts' }], - pageInfo: { hasNextPage: false, endCursor: null } - } - } - } - }) - } - } - if (args.includes('cursor=comment-1')) { - return response({ - comments: { nodes: [{ ...comment, id: 'IC_13', databaseId: 13, body: 'Newest' }] } - }) - } - return response({ - comments: { nodes: [comment], pageInfo: { hasNextPage: true, endCursor: 'comment-1' } }, - reviews: { nodes: [] }, - reviewThreads: { nodes: [thread] } - }) - }) - const result = await getPRComments('/repo', 7, { ...options, noCache: true }) - expect(result.map((c) => c.id)).toEqual([10, 13, 11, 12]) - expect(result.find((c) => c.id === 11)).toMatchObject({ - threadId: 'T1', - isResolved: true, - path: 'a.ts', - line: 4, - diffHunk: '-old\n+new' - }) - expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(3) - const continuation = ghExecFileAsyncMock.mock.calls[1][0].join(' ') - expect(continuation).not.toContain('reviewThreads(') - expect(continuation).not.toContain('reviews(') - }) - - it.each(['failure', 'repeated cursor'])( - 'rejects an incomplete conversation after %s', - async (mode) => { - const first = response({ - comments: { nodes: [comment], pageInfo: { hasNextPage: true, endCursor: 'same' } }, - reviews: { nodes: [] }, - reviewThreads: { nodes: [] } - }) - ghExecFileAsyncMock.mockResolvedValueOnce(first) - if (mode === 'failure') { - ghExecFileAsyncMock.mockRejectedValueOnce(new Error('offline')) - } else { - ghExecFileAsyncMock.mockResolvedValueOnce(first) - } - await expect(getPRComments('/repo', 7, { ...options, noCache: true })).rejects.toThrow( - /pagination|cursor/ - ) - } - ) - - it.each([10, 100])( - 'stops sibling admission after a hard REST failure with %s remaining pages', - async (remaining) => { - let releaseSibling!: (value: { stdout: string }) => void - let rejectPage!: (error: Error) => void - const sibling = new Promise<{ stdout: string }>((resolve) => { - releaseSibling = resolve - }) - const failed = new Promise<{ stdout: string }>((_resolve, reject) => { - rejectPage = reject - }) - const fullPage = (page: number) => - JSON.stringify( - Array.from({ length: 100 }, (_, i) => ({ - id: (page - 1) * 100 + i, - body: 'Review', - user: null, - submitted_at: '2026-04-01T00:00:00Z', - created_at: '2026-04-01T00:00:00Z', - html_url: 'https://example.test/review' - })) - ) - ghExecFileAsyncMock.mockImplementation(async (args: string[]) => { - if (args.includes('graphql')) { - return response(null) - } - if (args.includes('user')) { - return { stdout: 'me' } - } - const endpoint = args.at(-1) ?? '' - const page = Number(new URL(endpoint, 'https://github.com').searchParams.get('page') ?? 1) - if (page === 2) { - return endpoint.includes('/issues/') ? failed : sibling - } - return { stdout: page <= remaining + 2 ? fullPage(page) : '[]' } - }) - let settled = false - const read = getPRComments('/repo', 7, { ...options, noCache: true }) - const outcome = read.then( - () => { - settled = true - }, - () => { - settled = true - } - ) - await vi.waitFor(() => - expect( - ghExecFileAsyncMock.mock.calls.filter(([args]) => args.at(-1)?.includes('&page=2')) - ).toHaveLength(2) - ) - rejectPage(new Error('offline')) - await new Promise((resolve) => setImmediate(resolve)) - expect(settled).toBe(false) - expect(clientMocks.releaseMock).not.toHaveBeenCalled() - releaseSibling({ stdout: fullPage(2) }) - await expect(read).rejects.toThrow('pagination') - await outcome - expect(clientMocks.releaseMock).toHaveBeenCalledTimes(1) - expect( - ghExecFileAsyncMock.mock.calls.filter(([args]) => args.at(-1)?.includes('page=3')) - ).toHaveLength(0) - } - ) - - it('pages raw REST review rows even when the first 100 bodies are hidden', async () => { - const review = (id: number, body: string) => ({ - id, - body, - user: null, - submitted_at: '2026-04-01T00:00:00Z', - html_url: 'https://example.test/review' - }) - ghExecFileAsyncMock.mockImplementation(async (args: string[]) => { - if (args.includes('graphql')) { - return response({ comments: { nodes: [] }, reviews: null, reviewThreads: { nodes: [] } }) - } - if (args.includes('user')) { - return { stdout: 'me' } - } - return { - stdout: JSON.stringify( - args.at(-1)?.includes('&page=2') - ? [review(101, 'Latest summary')] - : Array.from({ length: 100 }, (_, i) => review(i, '')) - ) - } - }) - await expect(getPRComments('/repo', 7, { ...options, noCache: true })).resolves.toMatchObject([ - { id: 101, body: 'Latest summary' } - ]) - expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(4) - }) - it.each([100, 1000])( - 'walks %s independent conversation rows and replies with output-derived page counts', - async (count) => { - const connection = (nodes: unknown[], page: number) => ({ - nodes, - pageInfo: { - hasNextPage: page * 100 < count, - endCursor: page * 100 < count ? String(page + 1) : null - } - }) - const comments = (source: string, page: number) => - Array.from({ length: 100 }, (_, i) => ({ - ...comment, - id: `${source}-${(page - 1) * 100 + i}`, - databaseId: - (source === 'comments' ? 0 : source === 'reviews' ? 10000 : 20000) + - (page - 1) * 100 + - i, - ...(source === 'reply' ? { path: 'a.ts' } : {}) - })) - const thread = (index: number) => ({ - id: `T${index}`, - isResolved: false, - line: 4, - startLine: null, - originalLine: 4, - originalStartLine: null, - comments: - index === 0 - ? connection(comments('reply', 1), 1) - : { - nodes: [{ ...comment, id: `C${index}`, databaseId: 30000 + index, path: 'a.ts' }], - pageInfo: { hasNextPage: false, endCursor: null } - } - }) - const threads = (page: number) => - connection( - Array.from({ length: 100 }, (_, i) => thread((page - 1) * 100 + i)), - page - ) - ghExecFileAsyncMock.mockImplementation(async (args: string[]) => { - const page = Number(args.find((arg) => arg.startsWith('cursor='))?.slice(7) ?? 1) - if (args.includes('threadId=T0')) { - return { - stdout: JSON.stringify({ - data: { node: { ...thread(0), comments: connection(comments('reply', page), page) } } - }) - } - } - if (page === 1) { - return response({ - comments: connection(comments('comments', 1), 1), - reviews: connection(comments('reviews', 1), 1), - reviewThreads: threads(1) - }) - } - const query = args.find((arg) => arg.startsWith('query=')) ?? '' - return response( - query.includes('reviewThreads(first:') - ? { reviewThreads: threads(page) } - : query.includes('reviews(first:') - ? { reviews: connection(comments('reviews', page), page) } - : { comments: connection(comments('comments', page), page) } - ) - }) - const result = await getPRComments('/repo', 7, { ...options, noCache: true }) - expect(result).toHaveLength(count * 4 - 1) - expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(1 + 4 * (count / 100 - 1)) - } - ) }) diff --git a/src/main/github/client-pr-fallback-number.test.ts b/src/main/github/client-pr-fallback-number.test.ts deleted file mode 100644 index 11888eae4e9..00000000000 --- a/src/main/github/client-pr-fallback-number.test.ts +++ /dev/null @@ -1,178 +0,0 @@ -import type * as GitExecFileModule from '../git/command-runner/git-exec-file' -import type * as GhExecFileModule from '../git/command-runner/gh-exec-file' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as GithubApiRepositoryModule from './github-api-repository' -import type * as GitHubEnterpriseRepositoryModule from './github-enterprise-repository' - -const { clientMocks, moduleMocks } = await vi.hoisted(async () => { - const moduleMocks = await import('./client-test-mocks') - return { clientMocks: moduleMocks.createGitHubClientMocks(), moduleMocks } -}) - -vi.mock('./gh-utils', () => moduleMocks.ghUtilsModuleMock(clientMocks)) -vi.mock('../git/runner', () => moduleMocks.gitRunnerModuleMock(clientMocks)) - -vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ - ...(await importOriginal()), - gitExecFileAsync: clientMocks.gitExecFileAsyncMock -})) - -vi.mock('../git/command-runner/gh-exec-file', async (importOriginal) => ({ - ...(await importOriginal()), - ghExecFileAsync: clientMocks.ghExecFileAsyncMock -})) -vi.mock('./local-git-config-signature', () => - moduleMocks.localGitConfigSignatureModuleMock(clientMocks) -) -vi.mock('./github-enterprise-repository', async (importOriginal) => - moduleMocks.githubEnterpriseRepositoryModuleMock( - await importOriginal() - ) -) -vi.mock('./rate-limit', () => moduleMocks.rateLimitModuleMock(clientMocks)) -vi.mock('./github-api-repository', async (importOriginal) => - moduleMocks.githubApiRepositoryModuleMock( - clientMocks, - await importOriginal() - ) -) - -import { getPRForBranchOutcome } from './client/lookup/pr-for-branch-outcome' -import { resetPRForBranchMocks, mockPRLookupRoutes } from './client-test-harness' - -const { ghExecFileAsyncMock, resolvePRRepositoryCandidatesMock } = clientMocks - -const unexpectedRequests: string[][] = [] -function metadataCalls() { - return ghExecFileAsyncMock.mock.calls.filter( - ([args]) => - args[0] === 'pr' || - (args[0] === 'api' && args[1]?.startsWith('repos/') && args[1].includes('/pulls?')) - ) -} - -function mockLookupRoutes( - routes: Parameters[1], - unavailableChecks = false -): void { - mockPRLookupRoutes(clientMocks, routes, unavailableChecks, unexpectedRequests) -} - -describe('getPRForBranch', () => { - afterEach(() => { - expect(unexpectedRequests).toEqual([]) - }) - beforeEach(() => { - unexpectedRequests.length = 0 - resetPRForBranchMocks(clientMocks) - }) - - it('lets fallback PR number recovery win after fallback branch queries throw', async () => { - resolvePRRepositoryCandidatesMock.mockResolvedValueOnce({ - candidates: [{ owner: 'stablyai', repo: 'orca' }], - headRepo: null - }) - mockLookupRoutes([ - [ - 'list:stablyai/orca:feature/test', - async () => { - throw new Error('HTTP 429: API rate limit exceeded') - } - ], - [ - 'repos/stablyai/orca/pulls?head=stablyai%3Afeature%2Ftest&state=all&per_page=10', - async () => { - throw new Error('HTTP 502: Bad Gateway') - } - ], - [ - 'view:stablyai/orca:42', - async () => ({ - stdout: JSON.stringify({ - number: 42, - title: 'Fallback number recovered PR', - state: 'OPEN', - url: 'https://github.com/stablyai/orca/pull/42', - statusCheckRollup: [], - updatedAt: '2026-03-28T00:00:00Z', - isDraft: false, - mergeable: 'MERGEABLE', - baseRefName: 'main', - headRefName: 'feature/test', - baseRefOid: 'base-oid', - headRefOid: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb' - }) - }) - ] - ]) - - const outcome = await getPRForBranchOutcome('/repo-root', 'feature/test', null, null, 42) - - expect(outcome).toMatchObject({ - kind: 'found', - pr: { - number: 42, - title: 'Fallback number recovered PR' - } - }) - expect(metadataCalls()[2]).toEqual([ - [ - 'pr', - 'view', - '42', - '--repo', - 'stablyai/orca', - '--json', - 'number,title,state,url,updatedAt,isDraft,mergeable,reviewDecision,mergeStateStatus,autoMergeRequest,baseRefName,headRefName,baseRefOid,headRefOid,headRepositoryOwner,headRepository,isCrossRepository' - ], - { cwd: '/repo-root' } - ]) - }) - - it('keeps a pending fallback branch error when a later candidate cleanly misses', async () => { - resolvePRRepositoryCandidatesMock.mockResolvedValueOnce({ - candidates: [ - { owner: 'stablyai', repo: 'orca' }, - { owner: 'fork', repo: 'orca' } - ], - headRepo: null - }) - mockLookupRoutes([ - [ - 'list:stablyai/orca:feature/test', - async () => { - throw new Error('HTTP 429: API rate limit exceeded') - } - ], - [ - 'repos/stablyai/orca/pulls?head=stablyai%3Afeature%2Ftest&state=all&per_page=10', - async () => ({ stdout: JSON.stringify([]) }) - ], - ['list:fork/orca:feature/test', async () => ({ stdout: JSON.stringify([]) })] - ]) - - const outcome = await getPRForBranchOutcome('/repo-root', 'feature/test') - - expect(outcome).toMatchObject({ - kind: 'upstream-error', - errorType: 'rate_limited' - }) - expect(metadataCalls()[2]).toEqual([ - [ - 'pr', - 'list', - '--repo', - 'fork/orca', - '--head', - 'feature/test', - '--state', - 'all', - '--limit', - '10', - '--json', - 'number,title,state,url,updatedAt,isDraft,mergeable,baseRefName,headRefName,baseRefOid,headRefOid,headRepositoryOwner,headRepository,isCrossRepository' - ], - { cwd: '/repo-root' } - ]) - }) -}) diff --git a/src/main/github/client-pr-linked-lookup.test.ts b/src/main/github/client-pr-linked-lookup.test.ts deleted file mode 100644 index 7d095407183..00000000000 --- a/src/main/github/client-pr-linked-lookup.test.ts +++ /dev/null @@ -1,94 +0,0 @@ -import type * as GitExecFileModule from '../git/command-runner/git-exec-file' -import type * as GhExecFileModule from '../git/command-runner/gh-exec-file' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as GithubApiRepositoryModule from './github-api-repository' -import type * as GitHubEnterpriseRepositoryModule from './github-enterprise-repository' - -const { clientMocks, moduleMocks } = await vi.hoisted(async () => { - const moduleMocks = await import('./client-test-mocks') - return { clientMocks: moduleMocks.createGitHubClientMocks(), moduleMocks } -}) - -vi.mock('./gh-utils', () => moduleMocks.ghUtilsModuleMock(clientMocks)) -vi.mock('../git/runner', () => moduleMocks.gitRunnerModuleMock(clientMocks)) - -vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ - ...(await importOriginal()), - gitExecFileAsync: clientMocks.gitExecFileAsyncMock -})) - -vi.mock('../git/command-runner/gh-exec-file', async (importOriginal) => ({ - ...(await importOriginal()), - ghExecFileAsync: clientMocks.ghExecFileAsyncMock -})) -vi.mock('./local-git-config-signature', () => - moduleMocks.localGitConfigSignatureModuleMock(clientMocks) -) -vi.mock('./github-enterprise-repository', async (importOriginal) => - moduleMocks.githubEnterpriseRepositoryModuleMock( - await importOriginal() - ) -) -vi.mock('./rate-limit', () => moduleMocks.rateLimitModuleMock(clientMocks)) -vi.mock('./github-api-repository', async (importOriginal) => - moduleMocks.githubApiRepositoryModuleMock( - clientMocks, - await importOriginal() - ) -) - -import { getPRForBranch } from './client/lookup/get-pr-for-branch' -import { installIndependentCheckFixtures, resetPRForBranchMocks } from './client-test-harness' - -const { getOwnerRepoMock } = clientMocks - -const metadataRequests = vi.fn() -const unexpectedChecks: string[][] = [] -afterEach(() => expect(unexpectedChecks).toEqual([])) - -describe('getPRForBranch', () => { - beforeEach(() => { - resetPRForBranchMocks(clientMocks) - installIndependentCheckFixtures(clientMocks, metadataRequests, unexpectedChecks) - }) - - it('does not fall back to branch discovery when linked PR metadata is stale', async () => { - getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' }) - metadataRequests.mockRejectedValueOnce(new Error('HTTP 404: Not Found')).mockResolvedValueOnce({ - stdout: JSON.stringify([ - { - number: 42, - title: 'Branch PR', - state: 'OPEN', - url: 'https://github.com/acme/widgets/pull/42', - statusCheckRollup: [], - updatedAt: '2026-03-28T00:00:00Z', - isDraft: false, - mergeable: 'MERGEABLE', - baseRefName: 'main', - headRefName: 'feature/test', - baseRefOid: 'base-oid', - headRefOid: 'head-oid' - } - ]) - }) - - const pr = await getPRForBranch('/repo-root', 'feature/test', 99) - - expect(metadataRequests).toHaveBeenNthCalledWith( - 1, - [ - 'pr', - 'view', - '99', - '--repo', - 'acme/widgets', - '--json', - 'number,title,state,url,updatedAt,isDraft,mergeable,reviewDecision,mergeStateStatus,autoMergeRequest,baseRefName,headRefName,baseRefOid,headRefOid,headRepositoryOwner,headRepository,isCrossRepository' - ], - { cwd: '/repo-root' } - ) - expect(metadataRequests).toHaveBeenCalledTimes(1) - expect(pr).toBeNull() - }) -}) diff --git a/src/main/github/client-pr-rest-revalidation.test.ts b/src/main/github/client-pr-rest-revalidation.test.ts index debd54ff22a..0b02e1e1e2e 100644 --- a/src/main/github/client-pr-rest-revalidation.test.ts +++ b/src/main/github/client-pr-rest-revalidation.test.ts @@ -1,5 +1,5 @@ import type * as GitExecFileModule from '../git/command-runner/git-exec-file' -import type * as GhExecFileModule from '../git/command-runner/gh-exec-file' +import type * as GhExecFileModule from '../git/command-runner/hosted-cli/gh-exec-file' import { beforeEach, describe, expect, it, vi } from 'vitest' import type * as GithubApiRepositoryModule from './github-api-repository' import type * as GitHubEnterpriseRepositoryModule from './github-enterprise-repository' @@ -10,14 +10,13 @@ const { clientMocks, moduleMocks } = await vi.hoisted(async () => { }) vi.mock('./gh-utils', () => moduleMocks.ghUtilsModuleMock(clientMocks)) -vi.mock('../git/runner', () => moduleMocks.gitRunnerModuleMock(clientMocks)) vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ ...(await importOriginal()), gitExecFileAsync: clientMocks.gitExecFileAsyncMock })) -vi.mock('../git/command-runner/gh-exec-file', async (importOriginal) => ({ +vi.mock('../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ ...(await importOriginal()), ghExecFileAsync: clientMocks.ghExecFileAsyncMock })) @@ -38,39 +37,14 @@ vi.mock('./github-api-repository', async (importOriginal) => ) import { getFallbackPRListForBranch, getRestPRForBranch } from './client/lookup/pr-branch-lookup' -import { getPRForBranchOutcome } from './client/lookup/pr-for-branch-outcome' + import { resetPRForBranchMocks } from './client-test-harness' -const { ghExecFileAsyncMock, getOwnerRepoMock, noteRateLimitSpendMock } = clientMocks +const { ghExecFileAsyncMock } = clientMocks describe('PR lookup conditional REST reads', () => { beforeEach(() => resetPRForBranchMocks(clientMocks)) - it('refreshes a missing branch immediately at zero primary cost when GitHub confirms it is unchanged', async () => { - getOwnerRepoMock.mockResolvedValue({ owner: 'acme', repo: 'widgets' }) - ghExecFileAsyncMock - .mockResolvedValueOnce({ stdout: 'HTTP/2.0 200 OK\nEtag: "v1"\r\n\r\n[]' }) - .mockRejectedValueOnce( - Object.assign(new Error('gh: HTTP 304'), { stdout: 'HTTP/2.0 304 Not Modified\n\n' }) - ) - expect((await getPRForBranchOutcome('/repo', 'feature/missing')).kind).toBe('no-pr') - expect((await getPRForBranchOutcome('/repo', 'feature/missing')).kind).toBe('no-pr') - expect(ghExecFileAsyncMock.mock.calls.map(([args]) => args)).toEqual([ - [ - 'api', - 'repos/acme/widgets/pulls?head=acme%3Afeature%2Fmissing&state=all&per_page=10', - '--include' - ], - [ - 'api', - 'repos/acme/widgets/pulls?head=acme%3Afeature%2Fmissing&state=all&per_page=10', - '--include', - '-H', - 'If-None-Match: "v1"' - ] - ]) - expect(noteRateLimitSpendMock.mock.calls).toEqual([['core']]) - }) it('revalidates both mixed and active discovery responses before falling back to history', async () => { const repo = { owner: 'acme', repo: 'widgets', host: 'github.com' } const old = Array.from({ length: 10 }, (_, i) => ({ diff --git a/src/main/github/client-rate-limit-block.test.ts b/src/main/github/client-rate-limit-block.test.ts index 1100a174c87..53c3d30b313 100644 --- a/src/main/github/client-rate-limit-block.test.ts +++ b/src/main/github/client-rate-limit-block.test.ts @@ -1,5 +1,5 @@ import type * as GitExecFileModule from '../git/command-runner/git-exec-file' -import type * as GhExecFileModule from '../git/command-runner/gh-exec-file' +import type * as GhExecFileModule from '../git/command-runner/hosted-cli/gh-exec-file' import { beforeEach, describe, expect, it, vi } from 'vitest' import type * as GithubApiRepositoryModule from './github-api-repository' import type * as GitHubEnterpriseRepositoryModule from './github-enterprise-repository' @@ -10,14 +10,13 @@ const { clientMocks, moduleMocks } = await vi.hoisted(async () => { }) vi.mock('./gh-utils', () => moduleMocks.ghUtilsModuleMock(clientMocks)) -vi.mock('../git/runner', () => moduleMocks.gitRunnerModuleMock(clientMocks)) vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ ...(await importOriginal()), gitExecFileAsync: clientMocks.gitExecFileAsyncMock })) -vi.mock('../git/command-runner/gh-exec-file', async (importOriginal) => ({ +vi.mock('../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ ...(await importOriginal()), ghExecFileAsync: clientMocks.ghExecFileAsyncMock })) @@ -70,11 +69,6 @@ describe('getGitHubPRLookupRateLimitBlock', () => { _resetOwnerRepoCache() }) - it('reports no block while every lookup bucket has budget', async () => { - await expect(getGitHubPRLookupRateLimitBlock('/repo-root')).resolves.toBeNull() - expect(getRateLimitMock).toHaveBeenCalled() - }) - it('reports a block when either lookup bucket is exhausted', async () => { rateLimitGuardMock.mockImplementation(((bucket: string) => bucket === 'graphql' diff --git a/src/main/github/client-stack-merge-guard.test.ts b/src/main/github/client-stack-merge-guard.test.ts index ec9d96e7fce..f21503882c4 100644 --- a/src/main/github/client-stack-merge-guard.test.ts +++ b/src/main/github/client-stack-merge-guard.test.ts @@ -1,5 +1,5 @@ import type * as GitExecFileModule from '../git/command-runner/git-exec-file' -import type * as GhExecFileModule from '../git/command-runner/gh-exec-file' +import type * as GhExecFileModule from '../git/command-runner/hosted-cli/gh-exec-file' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type * as GithubApiRepositoryModule from './github-api-repository' import type * as GitHubEnterpriseRepositoryModule from './github-enterprise-repository' @@ -10,14 +10,13 @@ const { clientMocks, moduleMocks } = await vi.hoisted(async () => { }) vi.mock('./gh-utils', () => moduleMocks.ghUtilsModuleMock(clientMocks)) -vi.mock('../git/runner', () => moduleMocks.gitRunnerModuleMock(clientMocks)) vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ ...(await importOriginal()), gitExecFileAsync: clientMocks.gitExecFileAsyncMock })) -vi.mock('../git/command-runner/gh-exec-file', async (importOriginal) => ({ +vi.mock('../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ ...(await importOriginal()), ghExecFileAsync: clientMocks.ghExecFileAsyncMock })) @@ -42,8 +41,6 @@ import { resetGraphQLRateLimitGuardMocks } from './client-test-harness' -const { acquireMock, releaseMock } = clientMocks - const metadataRequests = vi.fn() const unexpectedChecks: string[][] = [] afterEach(() => expect(unexpectedChecks).toEqual([])) @@ -91,346 +88,4 @@ describe('GitHub GraphQL rate-limit guard', () => { metadataRequests.mock.calls.some(([args]) => args[0] === 'pr' && args[1] === 'merge') ).toBe(false) }) - - const stackMetadataUnavailableError = - 'Could not verify GitHub pull request stack metadata. Refresh and try again.' - - it.each([ - { - failure: 'local transport failure', - repoPath: '/repo-root', - connectionId: undefined, - probeResponse: new Error('stack metadata unavailable'), - expectedError: stackMetadataUnavailableError, - expectedDiagnostic: 'stack metadata unavailable', - expectedOptions: { cwd: '/repo-root', host: 'github.com' } - }, - { - failure: 'GitHub Enterprise transport failure', - repoPath: '/repo-root', - connectionId: undefined, - probeResponse: new Error('enterprise stack metadata unavailable'), - expectedError: stackMetadataUnavailableError, - expectedDiagnostic: 'enterprise stack metadata unavailable', - expectedOptions: { cwd: '/repo-root', host: 'github.enterprise.test' } - }, - { - failure: 'unparsable probe response over SSH', - repoPath: '/remote/repo-root', - connectionId: 'ssh-1', - probeResponse: { stdout: '' }, - expectedError: stackMetadataUnavailableError, - expectedDiagnostic: 'invalid JSON response', - expectedOptions: { host: 'github.com' } - }, - { - failure: 'valid JSON with a non-object payload', - repoPath: '/repo-root', - connectionId: undefined, - probeResponse: { stdout: 'null' }, - expectedError: stackMetadataUnavailableError, - expectedDiagnostic: 'invalid response shape', - expectedOptions: { cwd: '/repo-root', host: 'github.com' } - }, - { - failure: 'valid JSON with an array payload', - repoPath: '/repo-root', - connectionId: undefined, - probeResponse: { stdout: '[]' }, - expectedError: stackMetadataUnavailableError, - expectedDiagnostic: 'invalid response shape', - expectedOptions: { cwd: '/repo-root', host: 'github.com' } - }, - { - failure: 'present primitive stack metadata', - repoPath: '/repo-root', - connectionId: undefined, - probeResponse: { - stdout: JSON.stringify({ - number: 202, - head: { sha: validStackHeadSha }, - stack: true - }) - }, - expectedError: stackMetadataUnavailableError, - expectedDiagnostic: 'malformed stack', - expectedOptions: { cwd: '/repo-root', host: 'github.com' } - }, - { - failure: 'malformed stack response', - repoPath: '/repo-root', - connectionId: undefined, - probeResponse: { - stdout: JSON.stringify({ - number: 202, - head: { sha: validStackHeadSha }, - stack: { - number: 51, - position: 2, - size: '2', - base: { ref: 'main', sha: validStackBaseSha } - } - }) - }, - expectedError: stackMetadataUnavailableError, - expectedDiagnostic: 'malformed stack', - expectedOptions: { cwd: '/repo-root', host: 'github.com' } - }, - { - failure: 'incoherent stack position', - repoPath: '/repo-root', - connectionId: undefined, - probeResponse: { - stdout: JSON.stringify({ - number: 202, - head: { sha: validStackHeadSha }, - stack: { - number: 51, - position: 3, - size: 2, - base: { ref: 'main', sha: validStackBaseSha } - } - }) - }, - expectedError: stackMetadataUnavailableError, - expectedDiagnostic: 'malformed stack', - expectedOptions: { cwd: '/repo-root', host: 'github.com' } - }, - { - failure: 'non-positive stack number', - repoPath: '/repo-root', - connectionId: undefined, - probeResponse: { - stdout: JSON.stringify({ - number: 202, - head: { sha: validStackHeadSha }, - stack: { - number: 0, - position: 1, - size: 2, - base: { ref: 'main', sha: validStackBaseSha } - } - }) - }, - expectedError: stackMetadataUnavailableError, - expectedDiagnostic: 'malformed stack', - expectedOptions: { cwd: '/repo-root', host: 'github.com' } - }, - { - failure: 'fractional stack size', - repoPath: '/repo-root', - connectionId: undefined, - probeResponse: { - stdout: JSON.stringify({ - number: 202, - head: { sha: validStackHeadSha }, - stack: { - number: 51, - position: 1, - size: 1.5, - base: { ref: 'main', sha: validStackBaseSha } - } - }) - }, - expectedError: stackMetadataUnavailableError, - expectedDiagnostic: 'malformed stack', - expectedOptions: { cwd: '/repo-root', host: 'github.com' } - }, - { - failure: 'unsafe stack number', - repoPath: '/repo-root', - connectionId: undefined, - probeResponse: { - stdout: JSON.stringify({ - number: 202, - head: { sha: validStackHeadSha }, - stack: { - number: Number.MAX_SAFE_INTEGER + 1, - position: 1, - size: 2, - base: { ref: 'main', sha: validStackBaseSha } - } - }) - }, - expectedError: stackMetadataUnavailableError, - expectedDiagnostic: 'malformed stack', - expectedOptions: { cwd: '/repo-root', host: 'github.com' } - }, - { - failure: 'blank stack base ref', - repoPath: '/repo-root', - connectionId: undefined, - probeResponse: { - stdout: JSON.stringify({ - number: 202, - head: { sha: validStackHeadSha }, - stack: { - number: 51, - position: 2, - size: 2, - base: { ref: ' ', sha: validStackBaseSha } - } - }) - }, - expectedError: stackMetadataUnavailableError, - expectedDiagnostic: 'malformed stack', - expectedOptions: { cwd: '/repo-root', host: 'github.com' } - }, - { - failure: 'invalid stack base SHA', - repoPath: '/repo-root', - connectionId: undefined, - probeResponse: { - stdout: JSON.stringify({ - number: 202, - head: { sha: validStackHeadSha }, - stack: { - number: 51, - position: 2, - size: 2, - base: { ref: 'main', sha: 123 } - } - }) - }, - expectedError: stackMetadataUnavailableError, - expectedDiagnostic: 'malformed stack', - expectedOptions: { cwd: '/repo-root', host: 'github.com' } - }, - { - failure: 'invalid string stack base SHA', - repoPath: '/repo-root', - connectionId: undefined, - probeResponse: { - stdout: JSON.stringify({ - number: 202, - head: { sha: validStackHeadSha }, - stack: { - number: 51, - position: 2, - size: 2, - base: { ref: 'main', sha: 'not-a-git-object-id' } - } - }) - }, - expectedError: stackMetadataUnavailableError, - expectedDiagnostic: 'malformed stack', - expectedOptions: { cwd: '/repo-root', host: 'github.com' } - }, - { - failure: 'registered stack response without a head SHA', - repoPath: '/repo-root', - connectionId: undefined, - probeResponse: { - stdout: JSON.stringify({ - number: 202, - head: { ref: 'stack/api' }, - stack: { - number: 51, - position: 2, - size: 2, - base: { ref: 'main', sha: validStackBaseSha } - } - }) - }, - expectedError: stackMetadataUnavailableError, - expectedDiagnostic: 'missing head SHA', - expectedOptions: { cwd: '/repo-root', host: 'github.com' } - }, - { - failure: 'registered stack response with an invalid head SHA', - repoPath: '/repo-root', - connectionId: undefined, - probeResponse: { - stdout: JSON.stringify({ - number: 202, - head: { ref: 'stack/api', sha: {} }, - stack: { - number: 51, - position: 2, - size: 2, - base: { ref: 'main', sha: validStackBaseSha } - } - }) - }, - expectedError: stackMetadataUnavailableError, - expectedDiagnostic: 'missing head SHA', - expectedOptions: { cwd: '/repo-root', host: 'github.com' } - }, - { - failure: 'registered stack response with an invalid string head SHA', - repoPath: '/repo-root', - connectionId: undefined, - probeResponse: { - stdout: JSON.stringify({ - number: 202, - head: { ref: 'stack/api', sha: 'not-a-git-object-id' }, - stack: { - number: 51, - position: 2, - size: 2, - base: { ref: 'main', sha: validStackBaseSha } - } - }) - }, - expectedError: stackMetadataUnavailableError, - expectedDiagnostic: 'missing head SHA', - expectedOptions: { cwd: '/repo-root', host: 'github.com' } - } - ])('fails closed on $failure', async (scenario) => { - const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - if (scenario.probeResponse instanceof Error) { - metadataRequests.mockRejectedValueOnce(scenario.probeResponse) - } else { - metadataRequests.mockResolvedValueOnce(scenario.probeResponse) - } - // Stub legacy merge fallthrough so disabling the guard cannot fail on an unrelated missing fixture. - metadataRequests - .mockResolvedValueOnce({ - stdout: JSON.stringify({ - number: 202, - title: 'Stack API', - state: 'OPEN', - url: 'https://github.com/stablyai/orca/pull/202', - statusCheckRollup: [], - updatedAt: '2026-08-10T00:00:00Z', - isDraft: false, - mergeable: 'MERGEABLE', - baseRefName: 'stack/models', - headRefName: 'stack/api', - headRefOid: 'api-sha' - }) - }) - .mockResolvedValueOnce({ stdout: '', stderr: '' }) - - const result = await mergePR(scenario.repoPath, 202, 'squash', scenario.connectionId, { - owner: 'stablyai', - repo: 'orca', - host: scenario.expectedOptions.host - }) - - expect.soft(result).toEqual({ ok: false, error: scenario.expectedError }) - expect - .soft(metadataRequests.mock.calls.map(([args]) => args)) - .toEqual([['api', 'repos/stablyai/orca/pulls/202', '--include']]) - expect.soft(metadataRequests.mock.calls[0]?.[1]).toEqual(scenario.expectedOptions) - expect - .soft( - metadataRequests.mock.calls.some(([args]) => - args.includes('repos/stablyai/orca/pulls/202/merge-async') - ) - ) - .toBe(false) - expect - .soft(metadataRequests.mock.calls.some(([args]) => args[0] === 'pr' && args[1] === 'merge')) - .toBe(false) - expect.soft(acquireMock).toHaveBeenCalledTimes(1) - expect.soft(releaseMock).toHaveBeenCalledTimes(1) - expect - .soft(consoleWarnSpy) - .toHaveBeenCalledWith( - 'mergePR stack metadata probe failed for stablyai/orca#202:', - scenario.expectedDiagnostic - ) - expect.soft(consoleWarnSpy).toHaveBeenCalledTimes(1) - }) }) diff --git a/src/main/github/client-starred.test.ts b/src/main/github/client-starred.test.ts deleted file mode 100644 index 93988c7c369..00000000000 --- a/src/main/github/client-starred.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -import type * as GitExecFileModule from '../git/command-runner/git-exec-file' -import type * as GhExecFileModule from '../git/command-runner/gh-exec-file' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as GithubApiRepositoryModule from './github-api-repository' -import type * as GitHubEnterpriseRepositoryModule from './github-enterprise-repository' - -const { clientMocks, moduleMocks } = await vi.hoisted(async () => { - const moduleMocks = await import('./client-test-mocks') - return { clientMocks: moduleMocks.createGitHubClientMocks(), moduleMocks } -}) - -vi.mock('./gh-utils', () => moduleMocks.ghUtilsModuleMock(clientMocks)) -vi.mock('../git/runner', () => moduleMocks.gitRunnerModuleMock(clientMocks)) - -vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ - ...(await importOriginal()), - gitExecFileAsync: clientMocks.gitExecFileAsyncMock -})) - -vi.mock('../git/command-runner/gh-exec-file', async (importOriginal) => ({ - ...(await importOriginal()), - ghExecFileAsync: clientMocks.ghExecFileAsyncMock -})) -vi.mock('./local-git-config-signature', () => - moduleMocks.localGitConfigSignatureModuleMock(clientMocks) -) -vi.mock('./github-enterprise-repository', async (importOriginal) => - moduleMocks.githubEnterpriseRepositoryModuleMock( - await importOriginal() - ) -) -vi.mock('./rate-limit', () => moduleMocks.rateLimitModuleMock(clientMocks)) -vi.mock('./github-api-repository', async (importOriginal) => - moduleMocks.githubApiRepositoryModuleMock( - clientMocks, - await importOriginal() - ) -) - -import { __resetOrcaStarCheckForTests, checkOrcaStarred } from './client/fetch/orca-star' - -import { resetOriginRepositoryCache } from './client-test-harness' - -const { execFileAsyncMock, ghExecFileAsyncMock, acquireMock, releaseMock } = clientMocks - -async function flushMicrotasks(): Promise { - for (let i = 0; i < 5; i += 1) { - await Promise.resolve() - } -} - -describe('checkOrcaStarred', () => { - beforeEach(async () => { - resetOriginRepositoryCache() - execFileAsyncMock.mockReset() - ghExecFileAsyncMock.mockReset() - acquireMock.mockReset() - releaseMock.mockReset() - acquireMock.mockResolvedValue(undefined) - __resetOrcaStarCheckForTests() - }) - - it('coalesces concurrent checks onto one gh child', async () => { - let resolveGh: (value: { stdout: string; stderr: string }) => void = () => {} - ghExecFileAsyncMock.mockReturnValueOnce( - new Promise((resolve) => { - resolveGh = resolve - }) - ) - - const first = checkOrcaStarred() - const second = checkOrcaStarred() - const third = checkOrcaStarred() - await flushMicrotasks() - - expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(1) - expect(acquireMock).toHaveBeenCalledTimes(1) - - resolveGh({ stdout: 'HTTP/2.0 204 No Content\r\n', stderr: '' }) - await expect(Promise.all([first, second, third])).resolves.toEqual([true, true, true]) - }) - - it('starts a fresh check once the previous one has settled', async () => { - ghExecFileAsyncMock - .mockResolvedValueOnce({ stdout: 'HTTP/2.0 404 Not Found\r\n', stderr: '' }) - .mockResolvedValueOnce({ stdout: 'HTTP/2.0 204 No Content\r\n', stderr: '' }) - - await checkOrcaStarred() - await expect(checkOrcaStarred()).resolves.toBe(true) - expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(2) - }) -}) diff --git a/src/main/github/client-tracked-upstream-default-branch.test.ts b/src/main/github/client-tracked-upstream-default-branch.test.ts index ec2c206f327..01fd5e81a9f 100644 --- a/src/main/github/client-tracked-upstream-default-branch.test.ts +++ b/src/main/github/client-tracked-upstream-default-branch.test.ts @@ -1,5 +1,5 @@ import type * as GitExecFileModule from '../git/command-runner/git-exec-file' -import type * as GhExecFileModule from '../git/command-runner/gh-exec-file' +import type * as GhExecFileModule from '../git/command-runner/hosted-cli/gh-exec-file' import { beforeEach, describe, expect, it, vi } from 'vitest' import type * as GithubApiRepositoryModule from './github-api-repository' import type * as GitHubEnterpriseRepositoryModule from './github-enterprise-repository' @@ -10,14 +10,13 @@ const { clientMocks, moduleMocks } = await vi.hoisted(async () => { }) vi.mock('./gh-utils', () => moduleMocks.ghUtilsModuleMock(clientMocks)) -vi.mock('../git/runner', () => moduleMocks.gitRunnerModuleMock(clientMocks)) vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ ...(await importOriginal()), gitExecFileAsync: clientMocks.gitExecFileAsyncMock })) -vi.mock('../git/command-runner/gh-exec-file', async (importOriginal) => ({ +vi.mock('../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ ...(await importOriginal()), ghExecFileAsync: clientMocks.ghExecFileAsyncMock })) diff --git a/src/main/github/client-tracked-upstream-fork-owner.test.ts b/src/main/github/client-tracked-upstream-fork-owner.test.ts index f61b785ef22..ab6bf241224 100644 --- a/src/main/github/client-tracked-upstream-fork-owner.test.ts +++ b/src/main/github/client-tracked-upstream-fork-owner.test.ts @@ -1,5 +1,5 @@ import type * as GitExecFileModule from '../git/command-runner/git-exec-file' -import type * as GhExecFileModule from '../git/command-runner/gh-exec-file' +import type * as GhExecFileModule from '../git/command-runner/hosted-cli/gh-exec-file' import { beforeEach, describe, expect, it, vi } from 'vitest' import type * as GithubApiRepositoryModule from './github-api-repository' import type * as GitHubEnterpriseRepositoryModule from './github-enterprise-repository' @@ -10,14 +10,13 @@ const { clientMocks, moduleMocks } = await vi.hoisted(async () => { }) vi.mock('./gh-utils', () => moduleMocks.ghUtilsModuleMock(clientMocks)) -vi.mock('../git/runner', () => moduleMocks.gitRunnerModuleMock(clientMocks)) vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ ...(await importOriginal()), gitExecFileAsync: clientMocks.gitExecFileAsyncMock })) -vi.mock('../git/command-runner/gh-exec-file', async (importOriginal) => ({ +vi.mock('../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ ...(await importOriginal()), ghExecFileAsync: clientMocks.ghExecFileAsyncMock })) diff --git a/src/main/github/client-tracked-upstream-snapshot.test.ts b/src/main/github/client-tracked-upstream-snapshot.test.ts deleted file mode 100644 index 7b9474a76ab..00000000000 --- a/src/main/github/client-tracked-upstream-snapshot.test.ts +++ /dev/null @@ -1,159 +0,0 @@ -import type * as GitExecFileModule from '../git/command-runner/git-exec-file' -import type * as GhExecFileModule from '../git/command-runner/gh-exec-file' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as GithubApiRepositoryModule from './github-api-repository' -import type * as GitHubEnterpriseRepositoryModule from './github-enterprise-repository' - -const { clientMocks, moduleMocks } = await vi.hoisted(async () => { - const moduleMocks = await import('./client-test-mocks') - return { clientMocks: moduleMocks.createGitHubClientMocks(), moduleMocks } -}) - -vi.mock('./gh-utils', () => moduleMocks.ghUtilsModuleMock(clientMocks)) -vi.mock('../git/runner', () => moduleMocks.gitRunnerModuleMock(clientMocks)) - -vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ - ...(await importOriginal()), - gitExecFileAsync: clientMocks.gitExecFileAsyncMock -})) - -vi.mock('../git/command-runner/gh-exec-file', async (importOriginal) => ({ - ...(await importOriginal()), - ghExecFileAsync: clientMocks.ghExecFileAsyncMock -})) -vi.mock('./local-git-config-signature', () => - moduleMocks.localGitConfigSignatureModuleMock(clientMocks) -) -vi.mock('./github-enterprise-repository', async (importOriginal) => - moduleMocks.githubEnterpriseRepositoryModuleMock( - await importOriginal() - ) -) -vi.mock('./rate-limit', () => moduleMocks.rateLimitModuleMock(clientMocks)) -vi.mock('./github-api-repository', async (importOriginal) => - moduleMocks.githubApiRepositoryModuleMock( - clientMocks, - await importOriginal() - ) -) - -import { getPRForBranch } from './client/lookup/get-pr-for-branch' -import { - _getTrackedUpstreamBranchCacheSizesForTests, - __resetTrackedUpstreamBranchCacheForTests -} from './client/lookup/tracked-upstream-cache' -import { resetPRForBranchMocks } from './client-test-harness' - -const { - ghExecFileAsyncMock, - getOwnerRepoForRemoteMock, - resolvePRRepositoryCandidatesMock, - gitExecFileAsyncMock, - readLocalGitConfigSignatureMock -} = clientMocks - -describe('getPRForBranch', () => { - beforeEach(() => { - resetPRForBranchMocks(clientMocks) - }) - - it('does not cache positive tracked-upstream entries when config changes during the snapshot', async () => { - resolvePRRepositoryCandidatesMock.mockResolvedValue({ - candidates: [{ owner: 'acme', repo: 'widgets' }], - headRepo: { owner: 'acme', repo: 'widgets' } - }) - getOwnerRepoForRemoteMock.mockResolvedValue({ owner: 'acme', repo: 'widgets' }) - readLocalGitConfigSignatureMock - .mockResolvedValueOnce('/repo-root/.git/config\u0000mtime-a\u0000100') - .mockResolvedValueOnce('/repo-root/.git/config\u0000mtime-b\u0000120') - .mockResolvedValueOnce('/repo-root/.git/config\u0000mtime-b\u0000120') - .mockResolvedValueOnce('/repo-root/.git/config\u0000mtime-b\u0000120') - gitExecFileAsyncMock - .mockResolvedValueOnce({ stdout: 'feature\0origin/old-upstream\n', stderr: '' }) - .mockResolvedValueOnce({ stdout: 'feature\0origin/contributor/original\n', stderr: '' }) - ghExecFileAsyncMock - .mockResolvedValueOnce({ stdout: JSON.stringify([]) }) - .mockResolvedValueOnce({ stdout: JSON.stringify([]) }) - .mockResolvedValueOnce({ stdout: JSON.stringify([]) }) - .mockResolvedValueOnce({ - stdout: JSON.stringify([ - { - number: 82, - title: 'Stable config upstream PR', - state: 'open', - html_url: 'https://github.com/acme/widgets/pull/82', - updated_at: '2026-03-28T00:00:00Z', - draft: false, - mergeable: true, - base: { ref: 'main', sha: 'base-oid' }, - head: { ref: 'contributor/original', sha: 'upstream-head-oid' } - } - ]) - }) - - await getPRForBranch('/repo-root', 'feature') - const pr = await getPRForBranch('/repo-root', 'feature') - - const trackedUpstreamCalls = gitExecFileAsyncMock.mock.calls.filter(([args]) => - (args as string[]).includes('refs/heads') - ) - expect(trackedUpstreamCalls).toHaveLength(2) - expect(pr).toMatchObject({ - number: 82, - title: 'Stable config upstream PR' - }) - }) - - it('does not cache synthetic nulls from concurrent tracked-upstream waiters', async () => { - let resolveSnapshot: (value: { stdout: string; stderr: string }) => void - resolvePRRepositoryCandidatesMock.mockResolvedValue({ - candidates: [{ owner: 'acme', repo: 'widgets' }], - headRepo: { owner: 'acme', repo: 'widgets' } - }) - getOwnerRepoForRemoteMock.mockResolvedValue({ owner: 'acme', repo: 'widgets' }) - readLocalGitConfigSignatureMock.mockResolvedValue( - '/repo-root/.git/config\u0000mtime-a\u0000100' - ) - gitExecFileAsyncMock - .mockImplementationOnce( - () => - new Promise((resolve) => { - resolveSnapshot = resolve - }) - ) - .mockResolvedValueOnce({ stdout: 'new-feature\0origin/contributor/original\n', stderr: '' }) - ghExecFileAsyncMock - .mockResolvedValueOnce({ stdout: JSON.stringify([]) }) - .mockResolvedValueOnce({ stdout: JSON.stringify([]) }) - .mockResolvedValueOnce({ - stdout: JSON.stringify([ - { - number: 84, - title: 'Concurrent waiter upstream PR', - state: 'open', - html_url: 'https://github.com/acme/widgets/pull/84', - updated_at: '2026-03-28T00:00:00Z', - draft: false, - mergeable: true, - base: { ref: 'main', sha: 'base-oid' }, - head: { ref: 'contributor/original', sha: 'upstream-head-oid' } - } - ]) - }) - - const existingLookup = getPRForBranch('/repo-root', 'existing') - const waiterLookup = getPRForBranch('/repo-root', 'new-feature') - await vi.waitFor(() => expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(1)) - resolveSnapshot!({ stdout: 'existing\0\n', stderr: '' }) - const [, waiterPr] = await Promise.all([existingLookup, waiterLookup]) - - const trackedUpstreamCalls = gitExecFileAsyncMock.mock.calls.filter(([args]) => - (args as string[]).includes('refs/heads') - ) - expect(trackedUpstreamCalls).toHaveLength(2) - expect(waiterPr).toMatchObject({ - number: 84, - title: 'Concurrent waiter upstream PR' - }) - }) -}) diff --git a/src/main/github/client/check/check-details-admission-lifetime.test.ts b/src/main/github/client/check/check-details-admission-lifetime.test.ts index fa0d6db1ed3..dd648e7e407 100644 --- a/src/main/github/client/check/check-details-admission-lifetime.test.ts +++ b/src/main/github/client/check/check-details-admission-lifetime.test.ts @@ -4,7 +4,7 @@ import { completeFakeSpawn, createFakeSpawnedChild } from '../../../../shared/__fixtures__/fake-spawned-child' -import type { GhExecOptions } from '../../../git/command-runner/gh-exec-file' +import type { GhExecOptions } from '../../../git/command-runner/hosted-cli/gh-exec-file' const { spawnMock, resolverMock, signalMock, forceMock } = vi.hoisted(() => ({ spawnMock: vi.fn(), diff --git a/src/main/github/client/check/check-details-admission-lifetime.ts b/src/main/github/client/check/check-details-admission-lifetime.ts index e7d38a3f39a..7cd83d35a28 100644 --- a/src/main/github/client/check/check-details-admission-lifetime.ts +++ b/src/main/github/client/check/check-details-admission-lifetime.ts @@ -1,4 +1,4 @@ -import { createGhLogicalLifetime } from '../../../git/command-runner/gh-capture-lifetime' +import { createGhLogicalLifetime } from '../../../git/command-runner/hosted-cli/gh-capture-lifetime' import { createCheckDetailsAbortError, waitForCheckDetailsResolution } from './check-details-abort' export function createCheckDetailsAdmissionLifetime(release: () => void): { diff --git a/src/main/github/client/check/check-details-admission-snapshot.test.ts b/src/main/github/client/check/check-details-admission-snapshot.test.ts index 35a65391c15..b1975096fba 100644 --- a/src/main/github/client/check/check-details-admission-snapshot.test.ts +++ b/src/main/github/client/check/check-details-admission-snapshot.test.ts @@ -5,7 +5,7 @@ import { completeFakeSpawn, createFakeSpawnedChild } from '../../../../shared/__fixtures__/fake-spawned-child' -import type { GhExecOptions } from '../../../git/command-runner/gh-exec-file' +import type { GhExecOptions } from '../../../git/command-runner/hosted-cli/gh-exec-file' import { clearGhAccountTokenCacheForTests } from '../../gh-account-token' import { clearGhCapabilityStateForTests } from '../../gh-capability-state' import { getPRCheckDetails } from './get-pr-check-details' diff --git a/src/main/github/client/check/check-details-capture-diagnostics.test.ts b/src/main/github/client/check/check-details-capture-diagnostics.test.ts index 06938c409e8..b794dd37fce 100644 --- a/src/main/github/client/check/check-details-capture-diagnostics.test.ts +++ b/src/main/github/client/check/check-details-capture-diagnostics.test.ts @@ -6,7 +6,7 @@ import { completeFakeSpawn, createFakeSpawnedChild } from '../../../../shared/__fixtures__/fake-spawned-child' -import * as capture from '../../../git/command-runner/exec-file-capture' +import * as capture from '../../../git/command-runner/process-capture/exec-file-capture' import { RpcDispatcher } from '../../../runtime/rpc/dispatcher' import { GITHUB_PULL_REQUEST_METHODS } from '../../../runtime/rpc/methods/source-control/github/github-pull-request-methods' import type { OrcaRuntimeService } from '../../../runtime/orca-runtime' diff --git a/src/main/github/client/check/check-job-log-download.test.ts b/src/main/github/client/check/check-job-log-download.test.ts index 3b0a718286e..8edbe29128f 100644 --- a/src/main/github/client/check/check-job-log-download.test.ts +++ b/src/main/github/client/check/check-job-log-download.test.ts @@ -1,7 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import fixture from './__fixtures__/gh-api-unknown-escape-flag.json' import { startCheckJobLogDownload } from './check-job-log-download' -import type { GhCaptureLifetimeHooks } from '../../../git/command-runner/gh-capture-lifetime' +import type { GhCaptureLifetimeHooks } from '../../../git/command-runner/hosted-cli/gh-capture-lifetime' const { ghMock } = vi.hoisted(() => ({ ghMock: vi.fn() })) vi.mock('../../gh-utils', () => ({ ghExecFileAsync: ghMock })) const diagnostic = 'unknown flag: --allow-escape-sequences' diff --git a/src/main/github/client/check/check-job-log-download.ts b/src/main/github/client/check/check-job-log-download.ts index 46b7ade7bd0..b8d3e662b82 100644 --- a/src/main/github/client/check/check-job-log-download.ts +++ b/src/main/github/client/check/check-job-log-download.ts @@ -1,8 +1,8 @@ import { ghExecFileAsync } from '../../gh-utils' import type { GitHubApiRepository } from '../../github-api-repository' import type { GhExecOptions } from '../github-exec-scope' -import { createGhLogicalLifetime } from '../../../git/command-runner/gh-capture-lifetime' -import type { GhCaptureLifetimeHooks } from '../../../git/command-runner/gh-capture-lifetime' +import { createGhLogicalLifetime } from '../../../git/command-runner/hosted-cli/gh-capture-lifetime' +import type { GhCaptureLifetimeHooks } from '../../../git/command-runner/hosted-cli/gh-capture-lifetime' import { runCheckDetailsCall } from './check-details-admission-lifetime' import { createCheckDetailsAbortError, waitForCheckDetailsResolution } from './check-details-abort' diff --git a/src/main/github/client/check/check-job-log-execution.test.ts b/src/main/github/client/check/check-job-log-execution.test.ts index 4c6acf6eaf2..0f153f39aa1 100644 --- a/src/main/github/client/check/check-job-log-execution.test.ts +++ b/src/main/github/client/check/check-job-log-execution.test.ts @@ -7,8 +7,8 @@ import { const { spawnMock } = vi.hoisted(() => ({ spawnMock: vi.fn() })) vi.mock('node:child_process', async (original) => ({ ...(await original()), spawn: spawnMock })) import { snapshotCheckJobLogExecution } from './check-job-log-execution' -import { ghExecFileAsync } from '../../../git/command-runner/gh-exec-file' -import { createGhLogicalLifetime } from '../../../git/command-runner/gh-capture-lifetime' +import { ghExecFileAsync } from '../../../git/command-runner/hosted-cli/gh-exec-file' +import { createGhLogicalLifetime } from '../../../git/command-runner/hosted-cli/gh-capture-lifetime' const repo = { owner: 'acme', repo: 'widgets' } const platform = process.platform diff --git a/src/main/github/client/fetch/orca-star.ts b/src/main/github/client/fetch/orca-star.ts index 168058f9edf..aa29d0007f1 100644 --- a/src/main/github/client/fetch/orca-star.ts +++ b/src/main/github/client/fetch/orca-star.ts @@ -1,5 +1,5 @@ import { ghExecFileAsync, acquire, release } from '../../gh-utils' -import { runAsDefaultWslCliUserAct } from '../../../git/command-runner/default-wsl-cli-fallback' +import { runAsDefaultWslCliUserAct } from '../../../git/command-runner/hosted-cli/default-wsl-cli-fallback' export const ORCA_REPO = 'stablyai/orca' // Bound optional star prompts more tightly than user work; failures can fall back to the browser. diff --git a/src/main/github/client/lookup/pull-request-lookup-data.ts b/src/main/github/client/lookup/pull-request-lookup-data.ts index 0c39f4c22a7..4442f4965fc 100644 --- a/src/main/github/client/lookup/pull-request-lookup-data.ts +++ b/src/main/github/client/lookup/pull-request-lookup-data.ts @@ -8,7 +8,7 @@ import type { PRReviewDecision } from '../../../../shared/github/pull-request-types' import { gitExecFileAsync, type OwnerRepo } from '../../gh-utils' -import type { GitAdmissionTier } from '../../../git/command-runner/git-exec-options' +import type { GitAdmissionTier } from '../../../../shared/rpc-contract/git-admission-tier-params' import type { HostedReviewExecutionOptions } from '../../../source-control/hosted-review-git-options' import { mapPRState } from '../../mappers' import type { MergedPRCommitMembership } from '../../merged-pr-commit-membership' diff --git a/src/main/github/client/lookup/tracked-upstream-branch.ts b/src/main/github/client/lookup/tracked-upstream-branch.ts index 82eaaeee235..9fd4a838e34 100644 --- a/src/main/github/client/lookup/tracked-upstream-branch.ts +++ b/src/main/github/client/lookup/tracked-upstream-branch.ts @@ -4,7 +4,7 @@ import { } from '../../../../shared/git/remotes/git-review-branch-source' import { gitExecFileAsync } from '../../gh-utils' import { readLocalGitConfigSignature } from '../../local-git-config-signature' -import type { GitAdmissionTier } from '../../../git/command-runner/git-exec-options' +import type { GitAdmissionTier } from '../../../../shared/rpc-contract/git-admission-tier-params' import { TRACKED_UPSTREAM_SNAPSHOT_CACHE_TTL_MS, trackedUpstreamSnapshotCache, diff --git a/src/main/github/complete-pr-check-observation.test.ts b/src/main/github/complete-pr-check-observation.test.ts index fd60a304f27..a0d7c16bc5b 100644 --- a/src/main/github/complete-pr-check-observation.test.ts +++ b/src/main/github/complete-pr-check-observation.test.ts @@ -1,7 +1,7 @@ import { beforeEach, expect, it, vi } from 'vitest' const { exec } = vi.hoisted(() => ({ exec: vi.fn() })) -vi.mock('../git/command-runner/gh-exec-file', async (original) => ({ +vi.mock('../git/command-runner/hosted-cli/gh-exec-file', async (original) => ({ ...(await original>()), ghExecFileAsync: exec })) diff --git a/src/main/github/conflict-summary.ts b/src/main/github/conflict-summary.ts index 0eb6c10703e..37362de88d4 100644 --- a/src/main/github/conflict-summary.ts +++ b/src/main/github/conflict-summary.ts @@ -3,7 +3,7 @@ import { isUnsupportedMergeTreeMergeBaseError, isUnsupportedMergeTreeWriteTreeError } from '../../shared/git/branches/git-merge-tree-capability' -import { gitExecFileAsync } from '../git/runner' +import { gitExecFileAsync } from '../git/command-runner/git-exec-file' import { gitOptionsForWorktree, type GitRuntimeOptions } from '../git/git-runtime-options' import { createLocalGitObjectQuarantine } from '../git/local-git-object-quarantine' import { _resetCanonicalRepoKeyCacheForTests } from '../git/canonical-repo-key' @@ -11,7 +11,7 @@ import { RuntimeRemoteFetchController } from '../runtime/repositories/runtime-re import { clearGitCapabilityStateForTests, withLocalGitCapabilityCacheForExecution -} from '../git/command-runner/git-capability-state' +} from '../git/command-runner/host-routing/git-capability-state' import { __resetPRConflictSummaryDerivationCachesForTests, buildConflictSummaryCacheKey, diff --git a/src/main/github/gh-account-token.ts b/src/main/github/gh-account-token.ts index 965653cdaaf..fbcfdb5d84a 100644 --- a/src/main/github/gh-account-token.ts +++ b/src/main/github/gh-account-token.ts @@ -1,6 +1,6 @@ // Resolve bound credentials into child environments only; never mutate process-wide auth or log tokens. -import { ghExecFileAsync } from '../git/runner' -import type { GhCaptureLifetimeHooks } from '../git/command-runner/gh-capture-lifetime' +import { ghExecFileAsync } from '../git/command-runner/hosted-cli/gh-exec-file' +import type { GhCaptureLifetimeHooks } from '../git/command-runner/hosted-cli/gh-capture-lifetime' import { addWslEnvKeys } from '../../shared/wsl-env' import { ghTokenEnvVarForHost, diff --git a/src/main/github/gh-capability-state.test.ts b/src/main/github/gh-capability-state.test.ts index 7d2ab3905d6..a3cd51ec396 100644 --- a/src/main/github/gh-capability-state.test.ts +++ b/src/main/github/gh-capability-state.test.ts @@ -4,7 +4,7 @@ const { ghExecFileAsyncMock } = vi.hoisted(() => ({ ghExecFileAsyncMock: vi.fn() })) -vi.mock('../git/command-runner/gh-exec-file', async (importOriginal) => ({ +vi.mock('../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ ...(await importOriginal>()), ghExecFileAsync: ghExecFileAsyncMock })) diff --git a/src/main/github/gh-capability-state.ts b/src/main/github/gh-capability-state.ts index af62d831ebc..83889216ef1 100644 --- a/src/main/github/gh-capability-state.ts +++ b/src/main/github/gh-capability-state.ts @@ -1,11 +1,11 @@ // Require gh >=2.40 multi-account support per execution runtime before offering bindings. -import { ghExecFileAsync } from '../git/runner' +import { ghExecFileAsync } from '../git/command-runner/hosted-cli/gh-exec-file' import { parseWslUncPath } from '../../shared/wsl-paths' import type { GhMultiAccountCapability } from '../../shared/github/auth-types' import { createGhLogicalLifetime, type GhCaptureLifetimeHooks -} from '../git/command-runner/gh-capture-lifetime' +} from '../git/command-runner/hosted-cli/gh-capture-lifetime' export type GhCapabilityTarget = { cwd?: string diff --git a/src/main/github/gh-utils.test.ts b/src/main/github/gh-utils.test.ts index e8502f0c600..032c9411a5e 100644 --- a/src/main/github/gh-utils.test.ts +++ b/src/main/github/gh-utils.test.ts @@ -12,7 +12,7 @@ vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ gitExecFileAsync: gitExecFileAsyncMock })) -vi.mock('../git/command-runner/gh-exec-file', async (importOriginal) => ({ +vi.mock('../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ ...(await importOriginal>()), ghExecFileAsync: vi.fn() })) diff --git a/src/main/github/gh-utils.ts b/src/main/github/gh-utils.ts index 883ddc0b80b..e132997cf3a 100644 --- a/src/main/github/gh-utils.ts +++ b/src/main/github/gh-utils.ts @@ -1,6 +1,7 @@ import { execFile } from 'node:child_process' import { promisify } from 'node:util' -import { gitExecFileAsync, ghExecFileAsync } from '../git/runner' +import { gitExecFileAsync } from '../git/command-runner/git-exec-file' +import { ghExecFileAsync } from '../git/command-runner/hosted-cli/gh-exec-file' // Import pure parsing outside runner so runner-mocked tests retain the real implementation. import { extractExecError, parseRetryAfterMs } from '../git/exec-error' diff --git a/src/main/github/github-enterprise-repository.test.ts b/src/main/github/github-enterprise-repository.test.ts index 6a97404c2b7..eefbb09e56b 100644 --- a/src/main/github/github-enterprise-repository.test.ts +++ b/src/main/github/github-enterprise-repository.test.ts @@ -9,12 +9,12 @@ const { commandExecFileAsyncMock, ghExecFileAsyncMock, gitExecFileAsyncMock, res })) // Mock only execution so identity, runtime and auth-status parsing remain real. -vi.mock('../git/command-runner/command-exec-file', async (importOriginal) => ({ +vi.mock('../git/command-runner/process-capture/command-exec-file', async (importOriginal) => ({ ...(await importOriginal>()), commandExecFileAsync: commandExecFileAsyncMock })) -vi.mock('../git/command-runner/gh-exec-file', async (importOriginal) => ({ +vi.mock('../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ ...(await importOriginal>()), ghExecFileAsync: ghExecFileAsyncMock })) diff --git a/src/main/github/github-enterprise-repository.ts b/src/main/github/github-enterprise-repository.ts index 89a50c28ef2..d17ca6bb6c3 100644 --- a/src/main/github/github-enterprise-repository.ts +++ b/src/main/github/github-enterprise-repository.ts @@ -1,5 +1,5 @@ import { githubReadExecutionScope } from './github-read-execution-scope' -import { ghExecFileAsync } from '../git/runner' +import { ghExecFileAsync } from '../git/command-runner/hosted-cli/gh-exec-file' import type { GitHubOwnerRepo } from '../../shared/github/pull-request-types' import { getHostedReviewLocalGitOptions, diff --git a/src/main/github/github-pr-stack-async-merge.ts b/src/main/github/github-pr-stack-async-merge.ts index 299c5e7d6c9..9f999484e5f 100644 --- a/src/main/github/github-pr-stack-async-merge.ts +++ b/src/main/github/github-pr-stack-async-merge.ts @@ -1,5 +1,5 @@ import type { GitHubPRMergeMethod } from '../../shared/github/pull-request-types' -import { ghExecFileAsync } from '../git/runner' +import { ghExecFileAsync } from '../git/command-runner/hosted-cli/gh-exec-file' import { acquire, release } from './gh-utils' import { githubHostExecOptions, diff --git a/src/main/github/github-pr-stack.test.ts b/src/main/github/github-pr-stack.test.ts index e352ce9493a..0447ca3b7df 100644 --- a/src/main/github/github-pr-stack.test.ts +++ b/src/main/github/github-pr-stack.test.ts @@ -6,7 +6,7 @@ const { ghExecFileAsyncMock, rateLimitGuardMock, noteRateLimitSpendMock } = vi.h noteRateLimitSpendMock: vi.fn() })) -vi.mock('../git/command-runner/gh-exec-file', async (importOriginal) => ({ +vi.mock('../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ ...(await importOriginal>()), ghExecFileAsync: ghExecFileAsyncMock })) diff --git a/src/main/github/github-pr-stack.ts b/src/main/github/github-pr-stack.ts index 5b8114dfe99..fac1742b00f 100644 --- a/src/main/github/github-pr-stack.ts +++ b/src/main/github/github-pr-stack.ts @@ -7,7 +7,7 @@ import type { PRState } from '../../shared/github/pull-request-types' import { githubRepoIdentityKey } from '../../shared/github/repository-identity-key' -import { ghExecFileAsync } from '../git/runner' +import { ghExecFileAsync } from '../git/command-runner/hosted-cli/gh-exec-file' import { githubReadExecutionScope } from './github-read-execution-scope' import { githubHostExecOptions, diff --git a/src/main/github/github-repository-identity.fork-owner-repo.test.ts b/src/main/github/github-repository-identity.fork-owner-repo.test.ts index 5e194798172..058a43b9bc8 100644 --- a/src/main/github/github-repository-identity.fork-owner-repo.test.ts +++ b/src/main/github/github-repository-identity.fork-owner-repo.test.ts @@ -1,5 +1,5 @@ import type * as GitExecFileModule from '../git/command-runner/git-exec-file' -import type * as GhExecFileModule from '../git/command-runner/gh-exec-file' +import type * as GhExecFileModule from '../git/command-runner/hosted-cli/gh-exec-file' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' // Fork PR reads prefer upstream while origin-only probes retain the checkout identity. @@ -17,7 +17,7 @@ vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ gitExecFileAsync: gitExecFileAsyncMock })) -vi.mock('../git/command-runner/gh-exec-file', async (importOriginal) => ({ +vi.mock('../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ ...(await importOriginal()), ghExecFileAsync: ghExecFileAsyncMock })) diff --git a/src/main/github/github-repository-identity.ssh-host-alias.test.ts b/src/main/github/github-repository-identity.ssh-host-alias.test.ts index e92a9ea3e3f..5ebf41be4b7 100644 --- a/src/main/github/github-repository-identity.ssh-host-alias.test.ts +++ b/src/main/github/github-repository-identity.ssh-host-alias.test.ts @@ -1,4 +1,4 @@ -import type * as CommandExecFileModule from '../git/command-runner/command-exec-file' +import type * as CommandExecFileModule from '../git/command-runner/process-capture/command-exec-file' import type * as GitExecFileModule from '../git/command-runner/git-exec-file' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -14,7 +14,7 @@ const { readLocalGitConfigSignatureMock: vi.fn(async () => 'sig-10284') })) -vi.mock('../git/command-runner/command-exec-file', async (importOriginal) => ({ +vi.mock('../git/command-runner/process-capture/command-exec-file', async (importOriginal) => ({ ...(await importOriginal()), commandExecFileAsync: commandExecFileAsyncMock })) diff --git a/src/main/github/github-repository-identity.ts b/src/main/github/github-repository-identity.ts index c5d731bb03e..03a5ae8d5b4 100644 --- a/src/main/github/github-repository-identity.ts +++ b/src/main/github/github-repository-identity.ts @@ -15,7 +15,7 @@ import { } from './github-remote-identity-parsing' import { classifyGitHubOwnerRepoFromRemoteUrl } from './github-ssh-host-alias-resolution' import { isStableMissingGitRemoteError } from '../git/remotes/stable-missing-git-remote-error' -import type { GitAdmissionTier } from '../git/command-runner/git-exec-options' +import type { GitAdmissionTier } from '../../shared/rpc-contract/git-admission-tier-params' import { requireReachableGitRoute } from '../providers/execution-host-provider-dispatch' import { getConnectionExecutionHostId } from '../../shared/execution-host' import { resolveGitHubProjectAccount } from './github-project-account' diff --git a/src/main/github/github-ssh-host-alias-resolution.ts b/src/main/github/github-ssh-host-alias-resolution.ts index fcf59465688..5432a6f8c90 100644 --- a/src/main/github/github-ssh-host-alias-resolution.ts +++ b/src/main/github/github-ssh-host-alias-resolution.ts @@ -1,5 +1,5 @@ import type { GitHubOwnerRepo } from '../../shared/github/pull-request-types' -import { commandExecFileAsync } from '../git/runner' +import { commandExecFileAsync } from '../git/command-runner/process-capture/command-exec-file' import { parseWslPath } from '../wsl/filesystem/unc-path-access' import { resolveWithSshG } from '../ssh/config/ssh-g-config-resolution' import { diff --git a/src/main/github/pr-head-tracking-ref.ts b/src/main/github/pr-head-tracking-ref.ts index f50b094c1eb..b3301a3b144 100644 --- a/src/main/github/pr-head-tracking-ref.ts +++ b/src/main/github/pr-head-tracking-ref.ts @@ -1,4 +1,4 @@ -import { gitExecFileAsync } from '../git/runner' +import { gitExecFileAsync } from '../git/command-runner/git-exec-file' import { githubPullRequestHeadLocalRef, isSafeReviewHeadFetchRemote, diff --git a/src/main/github/project-view-host-auth.test.ts b/src/main/github/project-view-host-auth.test.ts index 579f5893d55..e122e453ae2 100644 --- a/src/main/github/project-view-host-auth.test.ts +++ b/src/main/github/project-view-host-auth.test.ts @@ -24,7 +24,7 @@ vi.mock('../git/exec-error', async (importOriginal) => ({ extractExecError: vi.fn(() => ({ stdout: '', stderr: '' })) })) -vi.mock('../git/command-runner/gh-exec-file', async (importOriginal) => ({ +vi.mock('../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ ...(await importOriginal>()), ghExecFileAsync: ghExecFileAsyncMock })) diff --git a/src/main/github/project-view/internals.ts b/src/main/github/project-view/internals.ts index 7f6b506822f..72efb3e2a7a 100644 --- a/src/main/github/project-view/internals.ts +++ b/src/main/github/project-view/internals.ts @@ -1,6 +1,7 @@ import { acquire, release } from '../gh-utils' import { isGitHubOwnerSlug } from '../../../shared/github/owner-slug' -import { extractExecError, ghExecFileAsync } from '../../git/runner' +import { extractExecError } from '../../git/exec-error' +import { ghExecFileAsync } from '../../git/command-runner/hosted-cli/gh-exec-file' import { repositoryRateLimitGuard, noteRepositoryRateLimitSpend, diff --git a/src/main/github/pull-request-sidebar-query.test.ts b/src/main/github/pull-request-sidebar-query.test.ts index 84b7b72533d..68a1d887b27 100644 --- a/src/main/github/pull-request-sidebar-query.test.ts +++ b/src/main/github/pull-request-sidebar-query.test.ts @@ -1,7 +1,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' const { exec, spend } = vi.hoisted(() => ({ exec: vi.fn(), spend: vi.fn() })) -vi.mock('../git/command-runner/gh-exec-file', async (importOriginal) => ({ +vi.mock('../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ ...(await importOriginal>()), ghExecFileAsync: exec })) diff --git a/src/main/github/rate-limit.test.ts b/src/main/github/rate-limit.test.ts index 97905ad09bf..22aa27a7af5 100644 --- a/src/main/github/rate-limit.test.ts +++ b/src/main/github/rate-limit.test.ts @@ -4,7 +4,7 @@ const { ghExecFileAsyncMock } = vi.hoisted(() => ({ ghExecFileAsyncMock: vi.fn() })) -vi.mock('../git/command-runner/gh-exec-file', async (importOriginal) => ({ +vi.mock('../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ ...(await importOriginal>()), ghExecFileAsync: ghExecFileAsyncMock })) diff --git a/src/main/github/rate-limit.ts b/src/main/github/rate-limit.ts index b1e70cc5265..39a90677a81 100644 --- a/src/main/github/rate-limit.ts +++ b/src/main/github/rate-limit.ts @@ -7,7 +7,7 @@ import type { import { isDefaultGitHubHost } from '../../shared/github/repository-identity-key' import { PrioritySemaphore } from '../../shared/priority-semaphore' import { isWslUncPath } from '../../shared/wsl-paths' -import { ghExecFileAsync } from '../git/runner' +import { ghExecFileAsync } from '../git/command-runner/hosted-cli/gh-exec-file' import { clearGhRateLimitBlock, getGhRateLimitBlockedUntilMs, diff --git a/src/main/github/work-item-search-test-harness.ts b/src/main/github/work-item-search-test-harness.ts index b328f5bf53d..ccdca328fdf 100644 --- a/src/main/github/work-item-search-test-harness.ts +++ b/src/main/github/work-item-search-test-harness.ts @@ -17,10 +17,10 @@ const { sourceContext: { host: 'github.com', available: true } })) const gitExecFileAsync = vi.hoisted(() => vi.fn()) -vi.mock('../git/command-runner/exec-file-capture', () => ({ +vi.mock('../git/command-runner/process-capture/exec-file-capture', () => ({ execFileCaptureToTermination: capture })) -vi.mock('../git/command-runner/wsl-command-resolution', () => ({ +vi.mock('../git/command-runner/host-routing/wsl-command-resolution', () => ({ resolveCommand: (binary: string, args: string[], cwd?: string, distro?: string) => ({ binary, args, @@ -30,10 +30,7 @@ vi.mock('../git/command-runner/wsl-command-resolution', () => ({ }), resolveDefaultWslCli: () => null })) -vi.mock('../git/runner', async () => ({ - ghExecFileAsync: (await import('../git/command-runner/gh-exec-file')).ghExecFileAsync, - gitExecFileAsync -})) + vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ ...(await importOriginal()), gitExecFileAsync diff --git a/src/main/gitlab/issues/gitlab-issue-queries.ts b/src/main/gitlab/issues/gitlab-issue-queries.ts index 195cd0b4efb..072135eee72 100644 --- a/src/main/gitlab/issues/gitlab-issue-queries.ts +++ b/src/main/gitlab/issues/gitlab-issue-queries.ts @@ -4,7 +4,7 @@ import type { IssueSourcePreference } from '../../../shared/repo-types' import { mapGitLabIssueInfo } from '../requests/gitlab-response-mapping' // prettier-ignore import { glabApiWithHeaders, acquire, release } from '../requests/glab-request-admission' -import { glabExecFileAsync } from '../../git/command-runner/glab-exec-file' +import { glabExecFileAsync } from '../../git/command-runner/hosted-cli/glab-exec-file' import { getIssueProjectRef, resolveIssueSource } from './gitlab-issue-source-resolution' import { classifyGlabError, classifyListFetchError } from '../requests/glab-error-classification' import { getGlabKnownHosts, type LocalGitExecOptions } from '../projects/gitlab-known-host-probe' diff --git a/src/main/gitlab/issues/issue-update.ts b/src/main/gitlab/issues/issue-update.ts index 197c59816a7..0ab00d70dda 100644 --- a/src/main/gitlab/issues/issue-update.ts +++ b/src/main/gitlab/issues/issue-update.ts @@ -3,7 +3,7 @@ import type { IssueSourcePreference } from '../../../shared/repo-types' import { acquire, release } from '../requests/glab-request-admission' import { classifyGlabError } from '../requests/glab-error-classification' import { getGlabKnownHosts, type LocalGitExecOptions } from '../projects/gitlab-known-host-probe' -import { glabExecFileAsync } from '../../git/command-runner/glab-exec-file' +import { glabExecFileAsync } from '../../git/command-runner/hosted-cli/glab-exec-file' import { glabHostEnvOptions, glabHostnameArgs, diff --git a/src/main/gitlab/merge-requests/branch-review-discovery.test.ts b/src/main/gitlab/merge-requests/branch-review-discovery.test.ts index b42ad10bdb7..ee722c95487 100644 --- a/src/main/gitlab/merge-requests/branch-review-discovery.test.ts +++ b/src/main/gitlab/merge-requests/branch-review-discovery.test.ts @@ -1,7 +1,7 @@ import { beforeEach, expect, it, vi } from 'vitest' const { read, pages } = vi.hoisted(() => ({ read: vi.fn(), pages: vi.fn() })) -vi.mock('../../git/command-runner/glab-exec-file', () => ({ +vi.mock('../../git/command-runner/hosted-cli/glab-exec-file', () => ({ glabExecFileAsync: read })) diff --git a/src/main/gitlab/merge-requests/branch-review-discovery.ts b/src/main/gitlab/merge-requests/branch-review-discovery.ts index a52c391cedf..351bf035166 100644 --- a/src/main/gitlab/merge-requests/branch-review-discovery.ts +++ b/src/main/gitlab/merge-requests/branch-review-discovery.ts @@ -2,7 +2,7 @@ import { selectBranchReview } from '../../source-control/branch-review-selection import { extractExecError } from '../../git/exec-error' import { fetchAllGitLabPages } from '../requests/gitlab-paginated-list' import { isUnsupportedReviewListFilter } from '../requests/glab-error-classification' -import { glabExecFileAsync } from '../../git/command-runner/glab-exec-file' +import { glabExecFileAsync } from '../../git/command-runner/hosted-cli/glab-exec-file' import { glabHostnameArgs, glabRepoExecOptions } from '../projects/gitlab-project-ref-resolution' import { parseGlabJsonList } from '../requests/glab-api-response' import type { LocalGitExecOptions } from '../projects/gitlab-known-host-probe' diff --git a/src/main/gitlab/merge-requests/merge-request-creation-lookup.ts b/src/main/gitlab/merge-requests/merge-request-creation-lookup.ts index cd41674af10..afb7b2a38e9 100644 --- a/src/main/gitlab/merge-requests/merge-request-creation-lookup.ts +++ b/src/main/gitlab/merge-requests/merge-request-creation-lookup.ts @@ -2,7 +2,7 @@ import { getHostedReviewLocalGitOptions, type HostedReviewExecutionOptions } from '../../source-control/hosted-review-git-options' -import { glabExecFileAsync } from '../../git/command-runner/glab-exec-file' +import { glabExecFileAsync } from '../../git/command-runner/hosted-cli/glab-exec-file' import { glabHostEnvOptions, glabRepoExecOptions } from '../projects/gitlab-project-ref-resolution' import type { ProjectRef } from '../projects/project-ref-parser' diff --git a/src/main/gitlab/merge-requests/merge-request-creation.ts b/src/main/gitlab/merge-requests/merge-request-creation.ts index 91cd1ca3c75..d07ea43e9a7 100644 --- a/src/main/gitlab/merge-requests/merge-request-creation.ts +++ b/src/main/gitlab/merge-requests/merge-request-creation.ts @@ -17,7 +17,7 @@ import { } from '../../source-control/hosted-review-git-options' import { getProjectSlug } from './merge-request-lookup' import { acquire, release } from '../requests/glab-request-admission' -import { glabExecFileAsync } from '../../git/command-runner/glab-exec-file' +import { glabExecFileAsync } from '../../git/command-runner/hosted-cli/glab-exec-file' import { glabHostEnvOptions, glabRepoExecOptions } from '../projects/gitlab-project-ref-resolution' import { findOpenMRByHeadBase, parseMergeRequestPayload } from './merge-request-creation-lookup' diff --git a/src/main/gitlab/merge-requests/merge-request-list.ts b/src/main/gitlab/merge-requests/merge-request-list.ts index c15af1061d4..1b4810e8f07 100644 --- a/src/main/gitlab/merge-requests/merge-request-list.ts +++ b/src/main/gitlab/merge-requests/merge-request-list.ts @@ -9,7 +9,7 @@ import { acquire, glabApiWithHeaders, release } from '../requests/glab-request-a import { classifyListFetchError } from '../requests/glab-error-classification' import { getGlabKnownHosts, type LocalGitExecOptions } from '../projects/gitlab-known-host-probe' import { glabHostnameArgs, glabRepoExecOptions } from '../projects/gitlab-project-ref-resolution' -import { glabExecFileAsync } from '../../git/command-runner/glab-exec-file' +import { glabExecFileAsync } from '../../git/command-runner/hosted-cli/glab-exec-file' import { parseGlabJsonList, parseGlabPaginationHeader } from '../requests/glab-api-response' import { resolveIssueSource } from '../issues/gitlab-issue-source-resolution' import { encodedProject } from '../projects/project-path-encoding' diff --git a/src/main/gitlab/merge-requests/merge-request-lookup.ts b/src/main/gitlab/merge-requests/merge-request-lookup.ts index b732021b15b..01eb81159dc 100644 --- a/src/main/gitlab/merge-requests/merge-request-lookup.ts +++ b/src/main/gitlab/merge-requests/merge-request-lookup.ts @@ -21,7 +21,7 @@ import { glabHostnameArgs, glabRepoExecOptions } from '../projects/gitlab-project-ref-resolution' -import { glabExecFileAsync } from '../../git/command-runner/glab-exec-file' +import { glabExecFileAsync } from '../../git/command-runner/hosted-cli/glab-exec-file' import type { ProjectRef } from '../projects/project-ref-parser' import { encodedProject } from '../projects/project-path-encoding' import { diff --git a/src/main/gitlab/merge-requests/merge-request-ready.ts b/src/main/gitlab/merge-requests/merge-request-ready.ts index 181e3fe57ce..736db394767 100644 --- a/src/main/gitlab/merge-requests/merge-request-ready.ts +++ b/src/main/gitlab/merge-requests/merge-request-ready.ts @@ -1,6 +1,6 @@ import { extractExecError } from '../../git/exec-error' import { parseGlabApiResponse } from '../requests/glab-api-response' -import { glabExecFileAsync } from '../../git/command-runner/glab-exec-file' +import { glabExecFileAsync } from '../../git/command-runner/hosted-cli/glab-exec-file' function isResponseObject(value: unknown): value is Record { return typeof value === 'object' && value !== null diff --git a/src/main/gitlab/merge-requests/merge-request-review-mutations.ts b/src/main/gitlab/merge-requests/merge-request-review-mutations.ts index 3bc86bd6bab..2388e38df09 100644 --- a/src/main/gitlab/merge-requests/merge-request-review-mutations.ts +++ b/src/main/gitlab/merge-requests/merge-request-review-mutations.ts @@ -9,7 +9,7 @@ import type { IssueSourcePreference } from '../../../shared/repo-types' import { acquire, release } from '../requests/glab-request-admission' import { classifyGlabError } from '../requests/glab-error-classification' import { glabHostnameArgs, glabRepoExecOptions } from '../projects/gitlab-project-ref-resolution' -import { glabExecFileAsync } from '../../git/command-runner/glab-exec-file' +import { glabExecFileAsync } from '../../git/command-runner/hosted-cli/glab-exec-file' import type { LocalGitExecOptions } from '../projects/gitlab-known-host-probe' import type { ProjectRef } from '../projects/project-ref-parser' import { encodedProject } from '../projects/project-path-encoding' diff --git a/src/main/gitlab/merge-requests/merge-request-state-mutations.ts b/src/main/gitlab/merge-requests/merge-request-state-mutations.ts index fc547ed4098..f573bd83486 100644 --- a/src/main/gitlab/merge-requests/merge-request-state-mutations.ts +++ b/src/main/gitlab/merge-requests/merge-request-state-mutations.ts @@ -1,7 +1,7 @@ import type { IssueSourcePreference } from '../../../shared/repo-types' import { acquire, release } from '../requests/glab-request-admission' import { glabHostEnvOptions, glabRepoExecOptions } from '../projects/gitlab-project-ref-resolution' -import { glabExecFileAsync } from '../../git/command-runner/glab-exec-file' +import { glabExecFileAsync } from '../../git/command-runner/hosted-cli/glab-exec-file' import type { LocalGitExecOptions } from '../projects/gitlab-known-host-probe' import type { ProjectRef } from '../projects/project-ref-parser' import { withProjectRef } from './merge-request-project-resolution' diff --git a/src/main/gitlab/merge-requests/merge-request-update.ts b/src/main/gitlab/merge-requests/merge-request-update.ts index c4f33411dfc..0b6862004ba 100644 --- a/src/main/gitlab/merge-requests/merge-request-update.ts +++ b/src/main/gitlab/merge-requests/merge-request-update.ts @@ -3,7 +3,7 @@ import type { GitLabMRUpdate } from '../../../shared/gitlab-types' import { acquire, release } from '../requests/glab-request-admission' import { classifyGlabError } from '../requests/glab-error-classification' import { glabHostnameArgs, glabRepoExecOptions } from '../projects/gitlab-project-ref-resolution' -import { glabExecFileAsync } from '../../git/command-runner/glab-exec-file' +import { glabExecFileAsync } from '../../git/command-runner/hosted-cli/glab-exec-file' import type { LocalGitExecOptions } from '../projects/gitlab-known-host-probe' import type { ProjectRef } from '../projects/project-ref-parser' import { encodedProject } from '../projects/project-path-encoding' diff --git a/src/main/gitlab/merge-requests/mr-file-diffs.ts b/src/main/gitlab/merge-requests/mr-file-diffs.ts index 32ce6de783b..56525f3f2e6 100644 --- a/src/main/gitlab/merge-requests/mr-file-diffs.ts +++ b/src/main/gitlab/merge-requests/mr-file-diffs.ts @@ -1,7 +1,7 @@ import type { GitLabMRFile } from '../../../shared/gitlab-types' import { encodedProject } from '../projects/project-path-encoding' import { glabHostnameArgs, glabRepoExecOptions } from '../projects/gitlab-project-ref-resolution' -import { glabExecFileAsync } from '../../git/command-runner/glab-exec-file' +import { glabExecFileAsync } from '../../git/command-runner/hosted-cli/glab-exec-file' import type { LocalGitExecOptions } from '../projects/gitlab-known-host-probe' import type { ProjectRef } from '../projects/project-ref-parser' diff --git a/src/main/gitlab/merge-requests/mr-reviewers-and-approvals.ts b/src/main/gitlab/merge-requests/mr-reviewers-and-approvals.ts index 0b938570dfa..92790a7cdff 100644 --- a/src/main/gitlab/merge-requests/mr-reviewers-and-approvals.ts +++ b/src/main/gitlab/merge-requests/mr-reviewers-and-approvals.ts @@ -2,7 +2,7 @@ import type { GitLabAssignableUser, GitLabMRApprovalState } from '../../../share import { mapGitLabUser, type GitLabRawUser } from '../projects/gitlab-assignable-user-mapping' import { encodedProject } from '../projects/project-path-encoding' import { glabHostnameArgs, glabRepoExecOptions } from '../projects/gitlab-project-ref-resolution' -import { glabExecFileAsync } from '../../git/command-runner/glab-exec-file' +import { glabExecFileAsync } from '../../git/command-runner/hosted-cli/glab-exec-file' import type { LocalGitExecOptions } from '../projects/gitlab-known-host-probe' import type { ProjectRef } from '../projects/project-ref-parser' diff --git a/src/main/gitlab/merge-requests/review-project-identity.ts b/src/main/gitlab/merge-requests/review-project-identity.ts index fd6279c7787..babb85d7926 100644 --- a/src/main/gitlab/merge-requests/review-project-identity.ts +++ b/src/main/gitlab/merge-requests/review-project-identity.ts @@ -1,7 +1,7 @@ import { runCoalescedProbe, type CoalescedProbes } from '../../git/remotes/coalesced-probe' import { codeHostReadExecutionScope } from '../../source-control/code-host-read-execution-scope' import { readLocalGitConfigSignature } from '../../github/local-git-config-signature' -import { glabExecFileAsync } from '../../git/command-runner/glab-exec-file' +import { glabExecFileAsync } from '../../git/command-runner/hosted-cli/glab-exec-file' import { glabHostnameArgs, glabRepoExecOptions } from '../projects/gitlab-project-ref-resolution' import type { LocalGitExecOptions } from '../projects/gitlab-known-host-probe' import type { ProjectRef } from '../projects/project-ref-parser' diff --git a/src/main/gitlab/pipelines/pipeline-job-graph.test.ts b/src/main/gitlab/pipelines/pipeline-job-graph.test.ts index abec7aa38a5..02f03118858 100644 --- a/src/main/gitlab/pipelines/pipeline-job-graph.test.ts +++ b/src/main/gitlab/pipelines/pipeline-job-graph.test.ts @@ -8,7 +8,7 @@ vi.mock('../requests/glab-request-admission', () => ({ release: vi.fn() })) -vi.mock('../../git/command-runner/glab-exec-file', () => ({ +vi.mock('../../git/command-runner/hosted-cli/glab-exec-file', () => ({ glabExecFileAsync: async (args: string[]) => ({ stdout: (await glabApiWithHeadersMock(args.slice(1))).body }) diff --git a/src/main/gitlab/pipelines/pipeline-job-mutations.ts b/src/main/gitlab/pipelines/pipeline-job-mutations.ts index ff343a4d336..162d60a2fdc 100644 --- a/src/main/gitlab/pipelines/pipeline-job-mutations.ts +++ b/src/main/gitlab/pipelines/pipeline-job-mutations.ts @@ -11,7 +11,7 @@ import { isMissingJobLogError } from '../requests/glab-error-classification' import { glabHostnameArgs, glabRepoExecOptions } from '../projects/gitlab-project-ref-resolution' -import { glabExecFileAsync } from '../../git/command-runner/glab-exec-file' +import { glabExecFileAsync } from '../../git/command-runner/hosted-cli/glab-exec-file' import type { LocalGitExecOptions } from '../projects/gitlab-known-host-probe' import type { ProjectRef } from '../projects/project-ref-parser' import { encodedProject } from '../projects/project-path-encoding' diff --git a/src/main/gitlab/projects/gitlab-known-host-probe.test.ts b/src/main/gitlab/projects/gitlab-known-host-probe.test.ts index e6603e7792d..e5fcfa29c8f 100644 --- a/src/main/gitlab/projects/gitlab-known-host-probe.test.ts +++ b/src/main/gitlab/projects/gitlab-known-host-probe.test.ts @@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const { glabExecFileAsyncMock } = vi.hoisted(() => ({ glabExecFileAsyncMock: vi.fn() })) -vi.mock('../../git/command-runner/glab-exec-file', async (importOriginal) => ({ +vi.mock('../../git/command-runner/hosted-cli/glab-exec-file', async (importOriginal) => ({ ...(await importOriginal>()), glabExecFileAsync: glabExecFileAsyncMock })) diff --git a/src/main/gitlab/projects/gitlab-known-host-probe.ts b/src/main/gitlab/projects/gitlab-known-host-probe.ts index 7ec52c11c18..dc54223944f 100644 --- a/src/main/gitlab/projects/gitlab-known-host-probe.ts +++ b/src/main/gitlab/projects/gitlab-known-host-probe.ts @@ -2,7 +2,7 @@ import { stripAnsiEscapeSequences } from '../../../shared/ansi-escape-sequences' import { runCoalescedProbe, type CoalescedProbes } from '../../git/remotes/coalesced-probe' import { extractExecError } from '../../git/exec-error' import { NEGATIVE_ENTRY_TTL_MS } from '../../git/remotes/remote-ref-probe-cache' -import { glabExecFileAsync } from '../../git/command-runner/glab-exec-file' +import { glabExecFileAsync } from '../../git/command-runner/hosted-cli/glab-exec-file' import { DEFAULT_GITLAB_HOSTS, normalizeGitLabHost } from './project-ref-parser' import type { GitAdmissionTier } from '../../../shared/rpc-contract/git-admission-tier-params' diff --git a/src/main/gitlab/projects/gitlab-project-ref-resolution.ts b/src/main/gitlab/projects/gitlab-project-ref-resolution.ts index 3c3230a2c86..26f419c84a6 100644 --- a/src/main/gitlab/projects/gitlab-project-ref-resolution.ts +++ b/src/main/gitlab/projects/gitlab-project-ref-resolution.ts @@ -1,4 +1,4 @@ -import { glabExecFileAsync } from '../../git/command-runner/glab-exec-file' +import { glabExecFileAsync } from '../../git/command-runner/hosted-cli/glab-exec-file' import type { GitAdmissionTier } from '../../../shared/rpc-contract/git-admission-tier-params' import { addWslEnvKeys } from '../../../shared/wsl-env' import { isTransientGitProbeError, readRemoteUrl } from '../../git/remotes/remote-url-probe' diff --git a/src/main/gitlab/projects/task-project-eligibility.test.ts b/src/main/gitlab/projects/task-project-eligibility.test.ts index 19ea11c4406..c0848c5acbf 100644 --- a/src/main/gitlab/projects/task-project-eligibility.test.ts +++ b/src/main/gitlab/projects/task-project-eligibility.test.ts @@ -14,12 +14,12 @@ vi.mock('../../git/command-runner/git-exec-file', async (importOriginal) => ({ gitExecFileAsync: git })) -vi.mock('../../git/command-runner/glab-exec-file', async (importOriginal) => ({ +vi.mock('../../git/command-runner/hosted-cli/glab-exec-file', async (importOriginal) => ({ ...(await importOriginal>()), glabExecFileAsync: glab })) -vi.mock('../../git/command-runner/gh-exec-file', async (importOriginal) => ({ +vi.mock('../../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ ...(await importOriginal>()), ghExecFileAsync: gh })) diff --git a/src/main/gitlab/requests/gitlab-auth-and-rate-limit.ts b/src/main/gitlab/requests/gitlab-auth-and-rate-limit.ts index b8a16a1191f..7d99f333642 100644 --- a/src/main/gitlab/requests/gitlab-auth-and-rate-limit.ts +++ b/src/main/gitlab/requests/gitlab-auth-and-rate-limit.ts @@ -5,7 +5,7 @@ import type { GitLabViewer } from '../../../shared/gitlab-types' import { acquire, glabApiWithHeaders, release } from './glab-request-admission' -import { glabExecFileAsync } from '../../git/command-runner/glab-exec-file' +import { glabExecFileAsync } from '../../git/command-runner/hosted-cli/glab-exec-file' import { parseGlabAuthStatusHosts, rememberGlabKnownHosts diff --git a/src/main/gitlab/requests/glab-request-admission.test.ts b/src/main/gitlab/requests/glab-request-admission.test.ts index d84763b58e1..6846251a84a 100644 --- a/src/main/gitlab/requests/glab-request-admission.test.ts +++ b/src/main/gitlab/requests/glab-request-admission.test.ts @@ -13,7 +13,7 @@ vi.mock('../../git/command-runner/git-exec-file', async (importOriginal) => ({ gitExecFileAsync: gitExecFileAsyncMock })) -vi.mock('../../git/command-runner/glab-exec-file', async (importOriginal) => ({ +vi.mock('../../git/command-runner/hosted-cli/glab-exec-file', async (importOriginal) => ({ ...(await importOriginal>()), glabExecFileAsync: glabExecFileAsyncMock })) diff --git a/src/main/gitlab/requests/glab-request-admission.ts b/src/main/gitlab/requests/glab-request-admission.ts index e4cd89331a7..35e4b03fc8b 100644 --- a/src/main/gitlab/requests/glab-request-admission.ts +++ b/src/main/gitlab/requests/glab-request-admission.ts @@ -1,4 +1,4 @@ -import { glabExecFileAsync } from '../../git/command-runner/glab-exec-file' +import { glabExecFileAsync } from '../../git/command-runner/hosted-cli/glab-exec-file' import { parseGlabApiResponse, type GlabApiResponse } from './glab-api-response' const MAX_CONCURRENT = 4 diff --git a/src/main/gitlab/work-items/work-item-details.test.ts b/src/main/gitlab/work-items/work-item-details.test.ts index 9cb7f790ac3..522d4600958 100644 --- a/src/main/gitlab/work-items/work-item-details.test.ts +++ b/src/main/gitlab/work-items/work-item-details.test.ts @@ -39,7 +39,7 @@ vi.mock('../issues/gitlab-issue-source-resolution', () => ({ resolveIssueSource: resolveIssueSourceMock })) -vi.mock('../../git/command-runner/glab-exec-file', () => ({ +vi.mock('../../git/command-runner/hosted-cli/glab-exec-file', () => ({ glabExecFileAsync: glabExecFileAsyncMock })) diff --git a/src/main/gitlab/work-items/work-item-details.ts b/src/main/gitlab/work-items/work-item-details.ts index e31cede9d2e..4e73fb778cd 100644 --- a/src/main/gitlab/work-items/work-item-details.ts +++ b/src/main/gitlab/work-items/work-item-details.ts @@ -24,7 +24,7 @@ import { gitLabRunTimes } from '../pipelines/gitlab-run-times' import { acquire, release } from '../requests/glab-request-admission' import { getGlabKnownHosts, type LocalGitExecOptions } from '../projects/gitlab-known-host-probe' import { glabHostnameArgs, glabRepoExecOptions } from '../projects/gitlab-project-ref-resolution' -import { glabExecFileAsync } from '../../git/command-runner/glab-exec-file' +import { glabExecFileAsync } from '../../git/command-runner/hosted-cli/glab-exec-file' import { resolveIssueSource } from '../issues/gitlab-issue-source-resolution' import type { ProjectRef } from '../projects/project-ref-parser' diff --git a/src/main/gitlab/work-items/work-item-queries.ts b/src/main/gitlab/work-items/work-item-queries.ts index c334abca664..ccc7863fa87 100644 --- a/src/main/gitlab/work-items/work-item-queries.ts +++ b/src/main/gitlab/work-items/work-item-queries.ts @@ -15,7 +15,7 @@ import { glabHostnameArgs, glabRepoExecOptions } from '../projects/gitlab-project-ref-resolution' -import { glabExecFileAsync } from '../../git/command-runner/glab-exec-file' +import { glabExecFileAsync } from '../../git/command-runner/hosted-cli/glab-exec-file' import { parseGlabJsonList } from '../requests/glab-api-response' import { resolveIssueSource } from '../issues/gitlab-issue-source-resolution' import type { ProjectRef } from '../projects/project-ref-parser' diff --git a/src/main/ipc/filesystem/filesystem-content-search-cancellation.test.ts b/src/main/ipc/filesystem/filesystem-content-search-cancellation.test.ts index 83c388f603a..28995d08650 100644 --- a/src/main/ipc/filesystem/filesystem-content-search-cancellation.test.ts +++ b/src/main/ipc/filesystem/filesystem-content-search-cancellation.test.ts @@ -39,7 +39,7 @@ vi.mock('../../git/command-runner/git-exec-file', async (importOriginal) => ({ gitExecFileAsync: vi.fn() })) -vi.mock('../../git/command-runner/wsl-aware-spawn', async (importOriginal) => ({ +vi.mock('../../git/command-runner/host-routing/wsl-aware-spawn', async (importOriginal) => ({ ...(await importOriginal>()), wslAwareSpawn: wslAwareSpawnMock })) diff --git a/src/main/ipc/filesystem/filesystem-git-pull-request-generation-handlers.ts b/src/main/ipc/filesystem/filesystem-git-pull-request-generation-handlers.ts index 977bd39724a..1b0f45c9732 100644 --- a/src/main/ipc/filesystem/filesystem-git-pull-request-generation-handlers.ts +++ b/src/main/ipc/filesystem/filesystem-git-pull-request-generation-handlers.ts @@ -18,7 +18,7 @@ import { prepareLocalCommitMessageAgentEnv } from '../../text-generation/commit- import { SSH_HOST_NOT_SERVED_MESSAGE } from '../../providers/ssh-host-not-served-error' import { resolveRegisteredWorktreePath } from '../worktrees/removal/registered-worktree-roots-cache' import { getLocalGitOptionsForRegisteredWorktree } from '../local-worktree-runtime-options' -import { gitExecFileAsync } from '../../git/runner' +import { gitExecFileAsync } from '../../git/command-runner/git-exec-file' import { withLinkedIssueDraftContext } from '../../../shared/source-control/ai/recipes/source-control-ai-action-variables' import { resolveSourceControlAiLinkedIssueMeta } from '../source-control/source-control-ai-linked-issue' import { resolveHostedReviewBodyForGeneration } from '../../source-control/pull-request-template' diff --git a/src/main/ipc/filesystem/filesystem-git-status-handlers.ts b/src/main/ipc/filesystem/filesystem-git-status-handlers.ts index e28b3bb6d8a..e6bf373f44c 100644 --- a/src/main/ipc/filesystem/filesystem-git-status-handlers.ts +++ b/src/main/ipc/filesystem/filesystem-git-status-handlers.ts @@ -6,7 +6,7 @@ import type { } from '../../../shared/git/status/git-status-types' import type { GitDiffResult } from '../../../shared/git/diff/git-diff-compare-types' import type { GitStatusRefBindingRequest as GitStatusUpstreamRefWatchRequest } from '../worktrees/git/worktree-git-status-ref-watch' -import type { GitAdmissionTier } from '../../git/command-runner/git-exec-options' +import type { GitAdmissionTier } from '../../../shared/rpc-contract/git-admission-tier-params' import { getStatus } from '../../git/source-control/status-read' import { getSubmoduleStatus } from '../../git/source-control/submodule-status' import { diff --git a/src/main/ipc/filesystem/filesystem-git-url-handlers.ts b/src/main/ipc/filesystem/filesystem-git-url-handlers.ts index bd17b4cecb5..5731087b44e 100644 --- a/src/main/ipc/filesystem/filesystem-git-url-handlers.ts +++ b/src/main/ipc/filesystem/filesystem-git-url-handlers.ts @@ -1,5 +1,5 @@ import { ipcMain } from 'electron' -import { awaitWindowsHostGitEnvironmentReady } from '../../git/runner' +import { awaitWindowsHostGitEnvironmentReady } from '../../git/command-runner/host-routing/windows-host-git-environment' import { getRemoteCommitUrl, getRemoteFileUrl } from '../../git/repo' import { resolveRegisteredWorktreePath } from '../worktrees/removal/registered-worktree-roots-cache' import { getLocalGitOptionsForRegisteredWorktree } from '../local-worktree-runtime-options' diff --git a/src/main/ipc/filesystem/filesystem-list-files-name-filter.test.ts b/src/main/ipc/filesystem/filesystem-list-files-name-filter.test.ts index d4a46b12f95..d4a54690723 100644 --- a/src/main/ipc/filesystem/filesystem-list-files-name-filter.test.ts +++ b/src/main/ipc/filesystem/filesystem-list-files-name-filter.test.ts @@ -1,7 +1,7 @@ import { EventEmitter } from 'node:events' import { afterEach, describe, expect, it, vi } from 'vitest' import type { Store } from '../../persistence/loading-store/store' -import type * as GitRunner from '../../git/command-runner/wsl-aware-spawn' +import type * as GitRunner from '../../git/command-runner/host-routing/wsl-aware-spawn' import { pathMatchesFileNameFilterTokens, splitFileNameFilterTokens @@ -11,7 +11,7 @@ const { wslAwareSpawnMock } = vi.hoisted(() => ({ wslAwareSpawnMock: vi.fn() })) -vi.mock('../../git/command-runner/wsl-aware-spawn', async (importOriginal) => ({ +vi.mock('../../git/command-runner/host-routing/wsl-aware-spawn', async (importOriginal) => ({ ...(await importOriginal()), wslAwareSpawn: wslAwareSpawnMock })) diff --git a/src/main/ipc/filesystem/filesystem-search-file-paths.test.ts b/src/main/ipc/filesystem/filesystem-search-file-paths.test.ts index bc79450ef13..d323518409c 100644 --- a/src/main/ipc/filesystem/filesystem-search-file-paths.test.ts +++ b/src/main/ipc/filesystem/filesystem-search-file-paths.test.ts @@ -2,7 +2,7 @@ import { EventEmitter } from 'node:events' import type { ChildProcess } from 'node:child_process' import { beforeEach, describe, expect, it, vi } from 'vitest' import type { Store } from '../../persistence/loading-store/store' -import type * as GitRunner from '../../git/command-runner/wsl-aware-spawn' +import type * as GitRunner from '../../git/command-runner/host-routing/wsl-aware-spawn' import type * as BundledRipgrepPath from '../../ripgrep/bundled-ripgrep-path' const { @@ -17,7 +17,7 @@ const { wslAwareSpawnMock: vi.fn() })) -vi.mock('../../git/command-runner/wsl-aware-spawn', async (importOriginal) => ({ +vi.mock('../../git/command-runner/host-routing/wsl-aware-spawn', async (importOriginal) => ({ ...(await importOriginal()), wslAwareSpawn: wslAwareSpawnMock })) diff --git a/src/main/ipc/filesystem/git-remote/compare-handlers.ts b/src/main/ipc/filesystem/git-remote/compare-handlers.ts index 47788dce98a..818c5970a99 100644 --- a/src/main/ipc/filesystem/git-remote/compare-handlers.ts +++ b/src/main/ipc/filesystem/git-remote/compare-handlers.ts @@ -9,7 +9,7 @@ import { resolveRegisteredWorktreePath } from '../../worktrees/removal/registere import { getLocalGitOptionsForRegisteredWorktree } from '../../local-worktree-runtime-options' import { validateFullGitObjectId } from '../access/filesystem-path-containment' import type { FilesystemHandlerContext } from '../filesystem-handler-context' -import type { GitAdmissionTier } from '../../../git/command-runner/git-exec-options' +import type { GitAdmissionTier } from '../../../../shared/rpc-contract/git-admission-tier-params' import { requireReachableGitRoute } from '../../../providers/execution-host-provider-dispatch' import { getConnectionExecutionHostId } from '../../../../shared/execution-host' import { assertWslUncPathRunning } from '../../../wsl/filesystem/wsl-unc-access-gate' diff --git a/src/main/ipc/preflight-provider-command-selection.test.ts b/src/main/ipc/preflight-provider-command-selection.test.ts index dc9b519bb93..101ff1e6865 100644 --- a/src/main/ipc/preflight-provider-command-selection.test.ts +++ b/src/main/ipc/preflight-provider-command-selection.test.ts @@ -3,9 +3,9 @@ import { tmpdir } from 'node:os' import path from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { removeTree } from '../../shared/windows-transient-lock-removal' -import { ghExecFileAsync } from '../git/command-runner/gh-exec-file' -import { glabExecFileAsync } from '../git/command-runner/glab-exec-file' -import { execFileCaptureToTermination } from '../git/command-runner/exec-file-capture' +import { ghExecFileAsync } from '../git/command-runner/hosted-cli/gh-exec-file' +import { glabExecFileAsync } from '../git/command-runner/hosted-cli/glab-exec-file' +import { execFileCaptureToTermination } from '../git/command-runner/process-capture/exec-file-capture' import { execLocalPreflightCommandOrThrow, findRunnableLocalCommand diff --git a/src/main/ipc/repos-execution-host-catalog.test.ts b/src/main/ipc/repos-execution-host-catalog.test.ts index 7d3312a4276..056d18212ae 100644 --- a/src/main/ipc/repos-execution-host-catalog.test.ts +++ b/src/main/ipc/repos-execution-host-catalog.test.ts @@ -1,7 +1,7 @@ import type * as RepoDetectionModule from '../git/repo-detection' import type * as GitExecFileModule from '../git/command-runner/git-exec-file' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as GitRunner from '../git/runner' +import type * as GitSpawnModule from '../git/command-runner/git-spawn' import type * as RepoModule from '../git/repo' const { reposMocks, moduleMocks, gitRepoProbeMocks } = await vi.hoisted(async () => { @@ -32,8 +32,8 @@ vi.mock('electron', () => moduleMocks.electronModuleMock(reposMocks)) vi.mock('../git/repo', async (importOriginal) => moduleMocks.gitRepoModuleMock(await importOriginal(), gitRepoProbeMocks) ) -vi.mock('../git/runner', async (importOriginal) => - moduleMocks.gitRunnerModuleMock(reposMocks, await importOriginal()) +vi.mock('../git/command-runner/git-spawn', async (importOriginal) => + moduleMocks.gitSpawnModuleMock(reposMocks, await importOriginal()) ) vi.mock('../git/worktrees/catalog/worktree-scan-cache', async (importOriginal) => ({ ...(await importOriginal>()), @@ -47,7 +47,7 @@ vi.mock('../workspaces/creation/worktree-root-preparation', () => ) import { registerRepoHandlers } from './repos' -import { clearGitCapabilityStateForTests } from '../git/command-runner/git-capability-state' +import { clearGitCapabilityStateForTests } from '../git/command-runner/host-routing/git-capability-state' import { resetSshProviderAuthorities } from '../ssh/connection/authority/ssh-provider-authority' import { getGitRepoRoot, isGitRepo } from '../git/repo' import { createRepoHandlerHarness, resetProjectGroupMocks } from './repos-remote-test-harness' diff --git a/src/main/ipc/repos-nested-import.test.ts b/src/main/ipc/repos-nested-import.test.ts index 155752334ef..be9a80cf2ac 100644 --- a/src/main/ipc/repos-nested-import.test.ts +++ b/src/main/ipc/repos-nested-import.test.ts @@ -4,7 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { mkdir, mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' -import type * as GitRunner from '../git/runner' +import type * as GitSpawnModule from '../git/command-runner/git-spawn' import type * as RepoModule from '../git/repo' const { reposMocks, moduleMocks, gitRepoProbeMocks } = await vi.hoisted(async () => { @@ -35,8 +35,8 @@ vi.mock('electron', () => moduleMocks.electronModuleMock(reposMocks)) vi.mock('../git/repo', async (importOriginal) => moduleMocks.gitRepoModuleMock(await importOriginal(), gitRepoProbeMocks) ) -vi.mock('../git/runner', async (importOriginal) => - moduleMocks.gitRunnerModuleMock(reposMocks, await importOriginal()) +vi.mock('../git/command-runner/git-spawn', async (importOriginal) => + moduleMocks.gitSpawnModuleMock(reposMocks, await importOriginal()) ) vi.mock('../git/worktrees/catalog/worktree-scan-cache', async (importOriginal) => ({ ...(await importOriginal>()), @@ -50,7 +50,7 @@ vi.mock('../workspaces/creation/worktree-root-preparation', () => ) import { registerRepoHandlers } from './repos' -import { clearGitCapabilityStateForTests } from '../git/command-runner/git-capability-state' +import { clearGitCapabilityStateForTests } from '../git/command-runner/host-routing/git-capability-state' import { resetSshProviderAuthorities } from '../ssh/connection/authority/ssh-provider-authority' import { getGitRepoRoot, isGitRepo } from '../git/repo' import { createRepoHandlerHarness, resetProjectGroupMocks } from './repos-remote-test-harness' diff --git a/src/main/ipc/repos-nested-scan.test.ts b/src/main/ipc/repos-nested-scan.test.ts index 119156cbb34..57db21514fa 100644 --- a/src/main/ipc/repos-nested-scan.test.ts +++ b/src/main/ipc/repos-nested-scan.test.ts @@ -4,7 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { mkdir, mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' -import type * as GitRunner from '../git/runner' +import type * as GitSpawnModule from '../git/command-runner/git-spawn' import type * as RepoModule from '../git/repo' const { reposMocks, moduleMocks, gitRepoProbeMocks } = await vi.hoisted(async () => { @@ -35,8 +35,8 @@ vi.mock('electron', () => moduleMocks.electronModuleMock(reposMocks)) vi.mock('../git/repo', async (importOriginal) => moduleMocks.gitRepoModuleMock(await importOriginal(), gitRepoProbeMocks) ) -vi.mock('../git/runner', async (importOriginal) => - moduleMocks.gitRunnerModuleMock(reposMocks, await importOriginal()) +vi.mock('../git/command-runner/git-spawn', async (importOriginal) => + moduleMocks.gitSpawnModuleMock(reposMocks, await importOriginal()) ) vi.mock('../git/worktrees/catalog/worktree-scan-cache', async (importOriginal) => ({ ...(await importOriginal>()), @@ -50,7 +50,7 @@ vi.mock('../workspaces/creation/worktree-root-preparation', () => ) import { registerRepoHandlers } from './repos' -import { clearGitCapabilityStateForTests } from '../git/command-runner/git-capability-state' +import { clearGitCapabilityStateForTests } from '../git/command-runner/host-routing/git-capability-state' import { resetSshProviderAuthorities } from '../ssh/connection/authority/ssh-provider-authority' import { getGitRepoRoot, isGitRepo } from '../git/repo' import { createRepoHandlerHarness, resetProjectGroupMocks } from './repos-remote-test-harness' @@ -118,12 +118,4 @@ describe('projectGroups IPC validation', () => { await rm(root, { recursive: true, force: true }) } }) - - it('rejects local nested scans with relative paths', async () => { - await expect( - handlers.get('projectGroups:scanNested')!(null, { - path: 'relative/project' - }) - ).rejects.toThrow('Repo path must be an absolute path') - }) }) diff --git a/src/main/ipc/repos-remote-test-harness.ts b/src/main/ipc/repos-remote-test-harness.ts index 0b3b3e4a978..a944087a006 100644 --- a/src/main/ipc/repos-remote-test-harness.ts +++ b/src/main/ipc/repos-remote-test-harness.ts @@ -1,7 +1,7 @@ import { EventEmitter } from 'node:events' import { vi } from 'vitest' import type { Mock } from 'vitest' -import type * as GitRunner from '../git/runner' +import type * as GitSpawnModule from '../git/command-runner/git-spawn' import type * as RepoModule from '../git/repo' /** Unconstrained spy; annotated explicitly so declaration emit never names @vitest/spy internals. */ @@ -116,15 +116,12 @@ export function gitRepoModuleMock( } // Keep real environment builders so clone tests verify actual credential-prompt guards. -export function gitRunnerModuleMock( +export function gitSpawnModuleMock( mocks: ReposIpcMocks, - actual: typeof GitRunner + actual: typeof GitSpawnModule ): Record { return { ...actual, - gitExecFileAsync: mocks.gitExecFileAsyncMock, - gitExecFileAsyncBuffer: vi.fn(), - gitStreamStdout: vi.fn(), gitSpawn: mocks.gitSpawnMock, gitSpawnAfterWindowsEnvironmentReady: mocks.gitSpawnAfterWindowsEnvironmentReadyMock } diff --git a/src/main/ipc/repos/local-repo-registration.ts b/src/main/ipc/repos/local-repo-registration.ts index 53f4c136704..1eaca481785 100644 --- a/src/main/ipc/repos/local-repo-registration.ts +++ b/src/main/ipc/repos/local-repo-registration.ts @@ -2,7 +2,7 @@ import type { Store } from '../../persistence/loading-store/store' import type { Repo } from '../../../shared/repo-types' import { isFolderRepo } from '../../../shared/repo-kind' import { normalizeRuntimePathForComparison } from '../../../shared/cross-platform-path' -import { awaitWindowsHostGitEnvironmentReady } from '../../git/runner' +import { awaitWindowsHostGitEnvironmentReady } from '../../git/command-runner/host-routing/windows-host-git-environment' import { inspectGitRepoForRegistrationAsync, getGitRepoRootAsync, diff --git a/src/main/ipc/repos/nested-repo-import-handler.ts b/src/main/ipc/repos/nested-repo-import-handler.ts index e2152f68d2e..d04eec2dc19 100644 --- a/src/main/ipc/repos/nested-repo-import-handler.ts +++ b/src/main/ipc/repos/nested-repo-import-handler.ts @@ -8,7 +8,7 @@ import type { RepositoryMetadataOwner } from '../../workspaces/catalog/imported- import type { ProjectGroupImportResult } from '../../../shared/project-group-types' import { DEFAULT_REPO_BADGE_COLOR } from '../../../shared/constants' import { normalizeRuntimePathForComparison } from '../../../shared/cross-platform-path' -import { awaitWindowsHostGitEnvironmentReady } from '../../git/runner' +import { awaitWindowsHostGitEnvironmentReady } from '../../git/command-runner/host-routing/windows-host-git-environment' import { isGitRepoAsync, getRepoName } from '../../git/repo' import { createNestedProjectGroupResolver, diff --git a/src/main/ipc/repos/nested-repo-scan-ipc.ts b/src/main/ipc/repos/nested-repo-scan-ipc.ts index bf13244ecda..04da3a0f343 100644 --- a/src/main/ipc/repos/nested-repo-scan-ipc.ts +++ b/src/main/ipc/repos/nested-repo-scan-ipc.ts @@ -3,7 +3,7 @@ import { isAbsolute } from 'node:path' import type { z } from 'zod' import type { NestedRepoScanResult } from '../../../shared/project-group-types' import { normalizeRuntimePathForComparison } from '../../../shared/cross-platform-path' -import { awaitWindowsHostGitEnvironmentReady } from '../../git/runner' +import { awaitWindowsHostGitEnvironmentReady } from '../../git/command-runner/host-routing/windows-host-git-environment' import { scanNestedRepos } from '../../project-groups/nested-repo-discovery' import type { ProjectGroupScanNestedArgs } from './repo-ipc-arg-schemas' diff --git a/src/main/ipc/repos/repo-clone-lifecycle.ts b/src/main/ipc/repos/repo-clone-lifecycle.ts index 422d3833f68..d80df2976ba 100644 --- a/src/main/ipc/repos/repo-clone-lifecycle.ts +++ b/src/main/ipc/repos/repo-clone-lifecycle.ts @@ -8,7 +8,8 @@ import type { Repo } from '../../../shared/repo-types' import { isFolderRepo } from '../../../shared/repo-kind' import { DEFAULT_REPO_BADGE_COLOR } from '../../../shared/constants' import { getGitCloneFailureMessage } from '../../../shared/git/remotes/git-clone-failure-message' -import { gitSpawnAfterWindowsEnvironmentReady, promptGuardGitEnv } from '../../git/runner' +import { gitSpawnAfterWindowsEnvironmentReady } from '../../git/command-runner/git-spawn' +import { promptGuardGitEnv } from '../../git/command-runner/git-environment/git-process-env' import { reuseSavedCloneTarget } from '../../git/saved-clone-target' import { checkCloneTarget } from '../../git/clone-target-check' import type { CloneTargetArgs } from '../../../shared/git/clone/clone-target-check' diff --git a/src/main/ipc/repos/repo-creation-handlers.ts b/src/main/ipc/repos/repo-creation-handlers.ts index d17a56ee3ba..195e71769c7 100644 --- a/src/main/ipc/repos/repo-creation-handlers.ts +++ b/src/main/ipc/repos/repo-creation-handlers.ts @@ -12,7 +12,7 @@ import { normalizeRuntimePathForComparison } from '../../../shared/cross-platfor import { getRepoExecutionHostId, LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host' import { getEffectiveHostSetting } from '../../../shared/host-setting-overrides' import { probeGitAvailability } from '../../git/git-availability' -import { gitExecFileAsync } from '../../git/runner' +import { gitExecFileAsync } from '../../git/command-runner/git-exec-file' import { inspectGitRepoForRegistrationAsync } from '../../git/repo' import { getClonePathComparisonKey, getSavedProjectPathKeys } from '../../git/repo-clone-path' import { detectRepoLocalMetadata } from '../../repository-icons/repo-icon-autodetect' diff --git a/src/main/ipc/source-control/github-project-view-handlers.ts b/src/main/ipc/source-control/github-project-view-handlers.ts index d7799eb7fdf..ac0247be431 100644 --- a/src/main/ipc/source-control/github-project-view-handlers.ts +++ b/src/main/ipc/source-control/github-project-view-handlers.ts @@ -1,5 +1,5 @@ import { ipcMain } from 'electron' -import { runAsDefaultWslCliUserAct } from '../../git/command-runner/default-wsl-cli-fallback' +import { runAsDefaultWslCliUserAct } from '../../git/command-runner/hosted-cli/default-wsl-cli-fallback' import type { AddIssueCommentBySlugArgs, ClearProjectItemFieldArgs, diff --git a/src/main/ipc/worktree-remote.ts b/src/main/ipc/worktree-remote.ts index ed33dd0cf6b..9c2587afeb8 100644 --- a/src/main/ipc/worktree-remote.ts +++ b/src/main/ipc/worktree-remote.ts @@ -51,7 +51,7 @@ import { resolveWorktreeCreateBase } from '../workspaces/creation/worktree-creat import { getHostedReviewForBranch } from '../source-control/hosted-review' import type { ForgeProviderId } from '../source-control/forge-provider' import { validateGitPushTarget } from '../git/push-target-validation' -import { gitExecFileAsync } from '../git/runner' +import { gitExecFileAsync } from '../git/command-runner/git-exec-file' import type { OrcaRuntimeService } from '../runtime/orca-runtime' import type { RemoteFetchResult, diff --git a/src/main/ipc/worktrees-removal-recovery.test.ts b/src/main/ipc/worktrees-removal-recovery.test.ts deleted file mode 100644 index a48e83a492a..00000000000 --- a/src/main/ipc/worktrees-removal-recovery.test.ts +++ /dev/null @@ -1,189 +0,0 @@ -import type * as WorktreeRemovalModule from '../git/worktrees/removal/worktree-removal' -import type * as WorktreeScanCacheModule from '../git/worktrees/catalog/worktree-scan-cache' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as gitRunner from '../git/runner' -await vi.importActual('../git/worktrees/removal/worktree-removal') -import * as scopedRootsInvalidation from './worktrees/removal/registered-worktree-roots-scoped-invalidation' -import * as authorizedRootsCache from './worktrees/removal/registered-worktree-roots-cache' -import { deleteWorktreeHistoryDirMock } from './worktrees-test-module-mocks' -import { handlers, setupWorktreeHandlers, store } from './worktrees-test-harness' - -vi.mock('../git/worktrees/catalog/worktree-scan-cache', async (importOriginal) => { - return { - ...(await importOriginal()), - listWorktrees: (await import('./worktrees-test-module-mocks')).listWorktreesMock, - listWorktreesSharedStrictAllowingTrueEmpty: (await import('./worktrees-test-module-mocks')) - .listWorktreesMock, - listWorktreesSharedStrict: (await import('./worktrees-test-module-mocks')).listWorktreesMock - } -}) - -vi.mock('electron', async () => - (await import('./worktrees-test-module-mocks')).electronModuleMock() -) -vi.mock('../../shared/git/worktrees/git-worktree-porcelain-parser', async (importOriginal) => ({ - ...(await importOriginal>()), - parseWorktreeList: (await import('./worktrees-test-module-mocks')).parseWorktreeListMock -})) - -vi.mock('../git/worktrees/removal/worktree-removal-preflight', async (importOriginal) => ({ - ...(await importOriginal>()), - assertWorktreeCleanForRemoval: (await import('./worktrees-test-module-mocks')) - .assertWorktreeCleanForRemovalMock -})) - -vi.mock('../git/worktrees/creation/worktree-add', async (importOriginal) => ({ - ...(await importOriginal>()), - addWorktree: (await import('./worktrees-test-module-mocks')).addWorktreeMock -})) - -vi.mock('../git/worktrees/creation/worktree-sparse-add', async (importOriginal) => ({ - ...(await importOriginal>()), - addSparseWorktree: (await import('./worktrees-test-module-mocks')).addSparseWorktreeMock -})) - -vi.mock('../git/worktrees/removal/worktree-removal', async (importOriginal) => ({ - ...(await importOriginal>()), - removeWorktree: (await import('./worktrees-test-module-mocks')).removeWorktreeMock -})) - -vi.mock('../git/worktrees/removal/worktree-branch-removal', async (importOriginal) => ({ - ...(await importOriginal>()), - forceDeleteLocalBranch: (await import('./worktrees-test-module-mocks')).forceDeleteLocalBranchMock -})) -vi.mock('../git/worktrees/catalog/worktree-listing', async (importOriginal) => ({ - ...(await importOriginal>()), - listWorktreesStrict: (await import('./worktrees-test-module-mocks')).listWorktreesMock, - describeCreatedWorktree: (await import('./worktrees-test-module-mocks')) - .describeCreatedWorktreeMock -})) -const { getWorktreeRunnerMocks } = vi.hoisted(() => { - function createWorktreeRunnerMocks() { - return (async () => (await import('./worktrees-test-module-mocks')).gitRunnerModuleMock())() - } - let runner: ReturnType | undefined - return { getWorktreeRunnerMocks: () => (runner ??= createWorktreeRunnerMocks()) } -}) - -vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ - ...(await importOriginal>()), - gitExecFileAsync: (await getWorktreeRunnerMocks()).gitExecFileAsync -})) - -vi.mock('../git/command-runner/git-exec-file-sync', async (importOriginal) => ({ - ...(await importOriginal>()), - gitExecFileSync: (await getWorktreeRunnerMocks()).gitExecFileSync -})) -vi.mock('../git/repo', async () => - (await import('./worktrees-test-module-mocks')).gitRepoModuleMock() -) - -vi.mock('../git/repo-default-base-ref', async (importOriginal) => ({ - ...(await importOriginal>()), - getBaseRefDefault: (await import('./worktrees-test-module-mocks')).getBaseRefDefaultMock -})) -vi.mock('../git/git-username', async (importOriginal) => ({ - ...(await importOriginal>()), - resolveLocalGitUsername: (await import('./worktrees-test-module-mocks')) - .resolveLocalGitUsernameMock -})) -vi.mock('../github/client', async () => - (await import('./worktrees-test-module-mocks')).githubClientModuleMock() -) -vi.mock('../github/client/lookup/get-pr-for-branch', async () => - (await import('./worktrees-test-module-mocks')).githubClientModuleMock() -) -vi.mock('../source-control/hosted-review', async () => - (await import('./worktrees-test-module-mocks')).hostedReviewModuleMock() -) -vi.mock('./worktree-symlinks', async () => - (await import('./worktrees-test-module-mocks')).worktreeSymlinksModuleMock() -) - -vi.mock('../git/worktrees/content-paths/worktree-symlink-detection', async (importOriginal) => ({ - ...(await importOriginal>()), - findExistingWorktreeSymlinkPaths: (await import('./worktrees-test-module-mocks')) - .findExistingWorktreeSymlinkPathsMock -})) -vi.mock('../workspace-hooks/hooks', async () => - (await import('./worktrees-test-module-mocks')).hooksModuleMock() -) -vi.mock('../workspace-hooks/setup-runner-script-text', async (importOriginal) => - (await import('./worktrees-test-module-mocks')).setupRunnerScriptTextModuleMock( - (await importOriginal()) as Record - ) -) -vi.mock('../workspace-hooks/worktree-runner-script', async (importOriginal) => - (await import('./worktrees-test-module-mocks')).worktreeRunnerScriptModuleMock( - (await importOriginal()) as Record - ) -) -vi.mock('../workspace-hooks/effective-hook-config', async (importOriginal) => - (await import('./worktrees-test-module-mocks')).effectiveHookConfigModuleMock( - (await importOriginal()) as Record - ) -) -vi.mock('../workspace-hooks/setup-hook-env-vars', async (importOriginal) => - (await import('./worktrees-test-module-mocks')).setupHookEnvVarsModuleMock( - (await importOriginal()) as Record - ) -) -vi.mock('./worktree-logic', async (importOriginal) => - (await import('./worktrees-test-module-mocks')).worktreeLogicModuleMock( - (await importOriginal()) as Record - ) -) -vi.mock('../pty/history/terminal-history-deletion', async () => - (await import('./worktrees-test-module-mocks')).terminalHistoryDeletionModuleMock() -) -vi.mock('../ports/advertised-url-watcher', async () => - (await import('./worktrees-test-module-mocks')).advertisedUrlWatcherModuleMock() -) -vi.mock('../workspaces/cleanup/workspace-cleanup-scan-snapshot', async () => - (await import('./worktrees-test-module-mocks')).workspaceCleanupScanSnapshotModuleMock() -) -vi.mock('../workspaces/space-analysis/workspace-space-analysis-snapshot', async () => - (await import('./worktrees-test-module-mocks')).workspaceSpaceAnalysisSnapshotModuleMock() -) -vi.mock('../workspaces/cleanup/workspace-cleanup-removal-snapshot-prune', async () => - (await import('./worktrees-test-module-mocks')).workspaceCleanupRemovalSnapshotPruneModuleMock() -) -vi.mock('../runtime/workspaces/removal/worktree-teardown', async () => - (await import('./worktrees-test-module-mocks')).worktreeTeardownModuleMock() -) -vi.mock('./pty/provider/registry', async () => - (await import('./worktrees-test-module-mocks')).ptyRegistryModuleMock() -) -vi.mock('./pty/provider/state-cleanup', async () => - (await import('./worktrees-test-module-mocks')).ptyStateCleanupModuleMock() -) -await vi.importActual('../git/command-runner/git-exec-file') - -describe('registerWorktreeHandlers', () => { - beforeEach(() => { - setupWorktreeHandlers() - vi.spyOn(scopedRootsInvalidation, 'invalidateAuthorizedRootsCacheForRepo').mockClear() - vi.spyOn(authorizedRootsCache, 'invalidateAuthorizedRootsCache').mockClear() - }) - - it('refuses to delete the root workspace for folder-mode repos', async () => { - store.getRepo.mockReturnValue({ - id: 'repo-folder', - path: '/workspace/folder', - displayName: 'folder', - badgeColor: '#000', - addedAt: 0, - kind: 'folder' - }) - - await expect( - handlers['worktrees:remove'](null, { - worktreeId: 'repo-folder::/workspace/folder' - }) - ).rejects.toThrow('Cannot delete the project root workspace') - - expect(store.removeWorktreeMeta).not.toHaveBeenCalled() - expect(deleteWorktreeHistoryDirMock).not.toHaveBeenCalled() - }) - // Authoritative off-host removal must retire status rows too; local GC cannot reach them. -}) diff --git a/src/main/ipc/worktrees/create/register-review-base-handlers.ts b/src/main/ipc/worktrees/create/register-review-base-handlers.ts index a00487d0642..7697581d73b 100644 --- a/src/main/ipc/worktrees/create/register-review-base-handlers.ts +++ b/src/main/ipc/worktrees/create/register-review-base-handlers.ts @@ -2,7 +2,7 @@ import { ipcMain } from 'electron' import type { GitHubPrStartPoint, GitPushTarget } from '../../../../shared/worktree/types' import { isFolderRepo } from '../../../../shared/repo-kind' import { getRepoRoutingConnectionId } from '../../../../shared/execution-host' -import { gitExecFileAsync } from '../../../git/runner' +import { gitExecFileAsync } from '../../../git/command-runner/git-exec-file' import { getLocalProjectGhExecOptions, getLocalProjectGitExecOptions, diff --git a/src/main/ipc/worktrees/removal/register-worktree-forget-handlers.ts b/src/main/ipc/worktrees/removal/register-worktree-forget-handlers.ts index 49cb9e3c145..966bab1c5b3 100644 --- a/src/main/ipc/worktrees/removal/register-worktree-forget-handlers.ts +++ b/src/main/ipc/worktrees/removal/register-worktree-forget-handlers.ts @@ -25,7 +25,7 @@ import { import { SshHostNotServedError } from '../../../providers/ssh-host-not-served-error' import { getLocalProjectWorktreeGitOptions } from '../../../workspaces/execution-host/project-runtime-git-options' import { forceDeleteLocalBranch } from '../../../git/worktrees/removal/worktree-branch-removal' -import { gitExecFileAsync } from '../../../git/runner' +import { gitExecFileAsync } from '../../../git/command-runner/git-exec-file' import type { RemoveWorktreeArgs } from '../ipc-context-schemas' import { getWorktreeRemovalInFlightKey } from './worktree-removal-coordinator' import { getFolderWorkspaceRootId } from '../folder-workspace-model' diff --git a/src/main/opencode/text-tasks/wsl/opencode-wsl-text-task.ts b/src/main/opencode/text-tasks/wsl/opencode-wsl-text-task.ts index 31544632b56..f04f11f207b 100644 --- a/src/main/opencode/text-tasks/wsl/opencode-wsl-text-task.ts +++ b/src/main/opencode/text-tasks/wsl/opencode-wsl-text-task.ts @@ -9,7 +9,7 @@ import { relayBundleCandidates } from '../../../wsl/execution/relay-bundle-paths import { ensureWslPinnedRuntime } from '../../../wsl/execution/wsl-pinned-runtime' import { runWslProcess, type WslSpec } from '../../../wsl/execution/wsl-runner' import { describeWslProcessFailure } from '../../../wsl/execution/wsl-process-failure' -import { translateArgsForWsl } from '../../../git/command-runner/wsl-path-translation' +import { translateArgsForWsl } from '../../../git/command-runner/host-routing/wsl-path-translation' import { spawnSourceControlAgent } from '../../../text-generation/source-control-agent-launch' import { killSourceControlAgentProcess } from '../../../text-generation/source-control-agent-termination' import { MAX_SOURCE_CONTROL_AGENT_OUTPUT_BYTES } from '../../../text-generation/source-control-generation-limits' diff --git a/src/main/plugins/catalog/plugin-marketplace-fetch.ts b/src/main/plugins/catalog/plugin-marketplace-fetch.ts index b8baa2cec1c..8a5c526f8bb 100644 --- a/src/main/plugins/catalog/plugin-marketplace-fetch.ts +++ b/src/main/plugins/catalog/plugin-marketplace-fetch.ts @@ -10,7 +10,7 @@ import { pluginCatalogVersionError } from '../../../shared/plugins/catalog/plugin-catalog' import { formatPluginSchemaIssues } from '../../../shared/plugins/manifest/plugin-schema-issues' -import { gitExecFileAsyncBuffer } from '../../git/runner' +import { gitExecFileAsyncBuffer } from '../../git/command-runner/git-exec-file' import { extractCatalogImages, type CatalogBlobReader } from './plugin-catalog-image-extraction' import { fillMonorepoReleaseImages } from './plugin-catalog-monorepo-images' import { readPluginGitCommit } from '../installation/plugin-git-repository' diff --git a/src/main/plugins/installation/plugin-git-repository.ts b/src/main/plugins/installation/plugin-git-repository.ts index bc77c56f441..404869aa914 100644 --- a/src/main/plugins/installation/plugin-git-repository.ts +++ b/src/main/plugins/installation/plugin-git-repository.ts @@ -10,7 +10,7 @@ import { pluginGitConfigArgs, pluginGitFetchCommitArgs } from '../../../shared/plugins/installation/plugin-git-arguments' -import { gitExecFileAsync, gitExecFileAsyncBuffer } from '../../git/runner' +import { gitExecFileAsync, gitExecFileAsyncBuffer } from '../../git/command-runner/git-exec-file' import { MAX_PLUGIN_TOTAL_BYTES } from '../plugin-content-hash' import { materializePluginGitTree, type PluginGitBytesRunner } from './plugin-git-tree' diff --git a/src/main/project-groups/nested-repo-discovery.ts b/src/main/project-groups/nested-repo-discovery.ts index 7183dd7c31b..9c71207ea18 100644 --- a/src/main/project-groups/nested-repo-discovery.ts +++ b/src/main/project-groups/nested-repo-discovery.ts @@ -2,7 +2,7 @@ import { lstat, readFile, readdir, realpath, stat } from 'node:fs/promises' import { basename, dirname, join, resolve } from 'node:path' import type { NestedRepoCandidate, NestedRepoScanResult } from '../../shared/project-group-types' import { isGitRepoAsync } from '../git/repo' -import { awaitWindowsHostGitEnvironmentReady } from '../git/runner' +import { awaitWindowsHostGitEnvironmentReady } from '../git/command-runner/host-routing/windows-host-git-environment' import { parseWslUncPath } from '../../shared/wsl-paths' import { isIgnoredNestedRepoDirectory, diff --git a/src/main/providers/git-provider-contract.ts b/src/main/providers/git-provider-contract.ts index 282992fb7de..c762253d1bb 100644 --- a/src/main/providers/git-provider-contract.ts +++ b/src/main/providers/git-provider-contract.ts @@ -30,7 +30,7 @@ import type { ConflictResolution } from '../../shared/source-control/listing/sou import type { GitProviderStatusOptions } from './git-provider-status-options' import type { BranchSwitchCreation } from '../../shared/git/branch-switch-target' import type { RuntimeGitLocalBranches } from '../../shared/runtime-worktree-contracts' -import type { GitAdmissionTier } from '../git/command-runner/git-exec-options' +import type { GitAdmissionTier } from '../../shared/rpc-contract/git-admission-tier-params' export type { GitProviderStatusOptions } from './git-provider-status-options' diff --git a/src/main/providers/local-git-provider.ts b/src/main/providers/local-git-provider.ts index 607fd585333..8b18b5a563d 100644 --- a/src/main/providers/local-git-provider.ts +++ b/src/main/providers/local-git-provider.ts @@ -7,7 +7,8 @@ import { checkoutBranch, listLocalBranches } from '../git/checkout' import { getHistory, getHistoryRefs } from '../git/history' import { gitFastForward, gitFetch, gitPull, gitPullRebaseFromBase, gitPush } from '../git/remote' import { getRemoteCommitUrl, getRemoteFileUrl, isGitRepo } from '../git/repo' -import { awaitWindowsHostGitEnvironmentReady, gitExecFileAsync } from '../git/runner' +import { awaitWindowsHostGitEnvironmentReady } from '../git/command-runner/host-routing/windows-host-git-environment' +import { gitExecFileAsync } from '../git/command-runner/git-exec-file' import { abortMerge, abortRebase, diff --git a/src/main/ripgrep/bundled-ripgrep-spawn.ts b/src/main/ripgrep/bundled-ripgrep-spawn.ts index a3e069dabeb..745a4271855 100644 --- a/src/main/ripgrep/bundled-ripgrep-spawn.ts +++ b/src/main/ripgrep/bundled-ripgrep-spawn.ts @@ -1,4 +1,4 @@ -import { wslAwareSpawn } from '../git/runner' +import { wslAwareSpawn } from '../git/command-runner/host-routing/wsl-aware-spawn' import { bundledRipgrepCommand, bundledRipgrepWslSpawnOptions } from './bundled-ripgrep-path' import { RIPGREP_MISSING_CWD_EXIT_CODE } from '../../shared/ripgrep/ripgrep-process-availability' diff --git a/src/main/runtime/files/orca-runtime-files-preview-budget.test.ts b/src/main/runtime/files/orca-runtime-files-preview-budget.test.ts index d32321234c0..aaae2faf6a0 100644 --- a/src/main/runtime/files/orca-runtime-files-preview-budget.test.ts +++ b/src/main/runtime/files/orca-runtime-files-preview-budget.test.ts @@ -8,7 +8,7 @@ import { createRuntimeFileHost, useRuntimeFileHostLifecycle } from './runtime-file-host.test-fixture' -import { RUNTIME_PREVIEWABLE_BINARY_MAX_BYTES } from './file-preview-budget' + import { REMOTE_RPC_MAX_CONTENT_BYTES } from '../../../shared/remote-rpc-content-budget' vi.mock('fs', async () => (await import('./runtime-file-command-mock-registry')).fsModuleMock()) @@ -22,7 +22,7 @@ vi.mock( vi.mock('../../ipc/filesystem/access/filesystem-auth', async () => (await import('./runtime-file-command-mock-registry')).filesystemAuthModuleMock() ) -vi.mock('../../git/runner', async () => +vi.mock('../../git/command-runner/host-routing/wsl-aware-spawn', async () => (await import('./runtime-file-command-mock-registry')).gitRunnerModuleMock() ) vi.mock( @@ -49,16 +49,6 @@ describe('RuntimeFileReads', () => { return dir } - it('rejects a previewable image one byte above the cap', async () => { - const dir = await previewFixture(RUNTIME_PREVIEWABLE_BINARY_MAX_BYTES + 1) - const { commands } = createFileReads({ path: dir }) - resolveAuthorizedPathMock.mockImplementation(async (p: string) => p) - - await expect( - commands.readFileExplorerPreview('id:wt-1', 'logo.png', REMOTE_RPC_MAX_CONTENT_BYTES) - ).rejects.toThrow('file_too_large') - }) - // Phones read images a chat names by host path; only image files on this machine qualify. it('reads a chat image outside every project root but never another file type', async () => { const dir = await previewFixture() diff --git a/src/main/runtime/files/runtime-file-command-mock-registry.ts b/src/main/runtime/files/runtime-file-command-mock-registry.ts index ae1a6e8a59e..5792fee107f 100644 --- a/src/main/runtime/files/runtime-file-command-mock-registry.ts +++ b/src/main/runtime/files/runtime-file-command-mock-registry.ts @@ -5,7 +5,7 @@ import { vi, type Mock } from 'vitest' import type * as Fs from 'node:fs' import type * as FsPromises from 'node:fs/promises' import type * as FilesystemAuth from '../../ipc/filesystem/access/filesystem-auth' -import type * as GitRunner from '../../git/runner' +import type * as wslAwareSpawnModule from '../../git/command-runner/host-routing/wsl-aware-spawn' import type * as BundledRipgrepPath from '../../ripgrep/bundled-ripgrep-path' // Loose mock payloads allow partial fixtures while suites assert the exact call arguments. @@ -86,7 +86,9 @@ export async function filesystemAuthModuleMock() { } export async function gitRunnerModuleMock() { - const actual = await vi.importActual('../../git/runner') + const actual = await vi.importActual( + '../../git/command-runner/host-routing/wsl-aware-spawn' + ) return { ...actual, wslAwareSpawn: wslAwareSpawnMock diff --git a/src/main/runtime/files/search/runtime-search-line-fragments.test.ts b/src/main/runtime/files/search/runtime-search-line-fragments.test.ts deleted file mode 100644 index e5fa765c487..00000000000 --- a/src/main/runtime/files/search/runtime-search-line-fragments.test.ts +++ /dev/null @@ -1,112 +0,0 @@ -import { RuntimeFileSearch } from './file-search' -import { describe, expect, it, vi } from 'vitest' -import { EventEmitter } from 'node:events' -import { resolveAuthorizedPathMock, wslAwareSpawnMock } from '../runtime-file-command-mock-registry' -import { - createRuntimeFileHost, - useRuntimeFileHostLifecycle -} from '../runtime-file-host.test-fixture' - -vi.mock('fs', async () => (await import('../runtime-file-command-mock-registry')).fsModuleMock()) -vi.mock('fs/promises', async () => - (await import('../runtime-file-command-mock-registry')).fsPromisesModuleMock() -) -vi.mock( - '../watch/file-watcher-host', - async () => (await import('../runtime-file-command-mock-registry')).fileWatcherHostMock -) -vi.mock('../../../ipc/filesystem/access/filesystem-auth', async () => - (await import('../runtime-file-command-mock-registry')).filesystemAuthModuleMock() -) -vi.mock('../../../git/runner', async () => - (await import('../runtime-file-command-mock-registry')).gitRunnerModuleMock() -) -vi.mock( - '../../../ipc/local-worktree-runtime-options', - async () => - (await import('../runtime-file-command-mock-registry')).localWorktreeRuntimeOptionsMock -) - -type MockRuntimeSearchChild = EventEmitter & { - stdout: EventEmitter & { setEncoding: ReturnType } - stderr: EventEmitter - kill: ReturnType -} - -function createRuntimeSearchChild(): MockRuntimeSearchChild { - const child = new EventEmitter() as MockRuntimeSearchChild - child.stdout = new EventEmitter() as MockRuntimeSearchChild['stdout'] - child.stdout.setEncoding = vi.fn() - child.stderr = new EventEmitter() - child.kill = vi.fn() - return child -} - -async function flushRuntimeSearchMicrotasks(): Promise { - for (let index = 0; index < 8; index++) { - await Promise.resolve() - } -} - -describe('RuntimeFileSearch', () => { - useRuntimeFileHostLifecycle() - - it('assembles a fragmented runtime search record without rescanning the carry', async () => { - const { commands } = createFileSearch({ - resolveRuntimeFileTarget: vi.fn(async () => ({ - worktree: { id: 'wt-1', repoId: 'repo-1', path: '/repo' }, - executionHostId: 'local' - })) - }) - const child = createRuntimeSearchChild() - resolveAuthorizedPathMock.mockResolvedValue('/repo') - wslAwareSpawnMock.mockReturnValue(child) - const resultPromise = commands.searchRuntimeFiles('id:wt-1', { - query: 'needle', - maxResults: 10 - }) - await flushRuntimeSearchMicrotasks() - const line = JSON.stringify({ - type: 'match', - data: { - path: { text: '/repo/file.ts' }, - line_number: 1, - lines: { text: `needle🐋${'x'.repeat(128 * 1024)}` }, - submatches: [{ start: 0, end: 6 }] - } - }) - // Method-shaped type: a call-signature capture would reject `split`'s splitter-object overload. - const originalSplit: { split(separator: unknown, limit?: number): string[] }['split'] = - String.prototype.split - let scanned = 0 - const spy = vi.spyOn(String.prototype, 'split').mockImplementation(function ( - this: string, - separator: unknown, - limit?: number - ) { - if (separator === '\n') { - scanned += this.length - } - return originalSplit.call(this, separator, limit) - }) - try { - for (let offset = 0; offset < line.length; offset += 1024) { - child.stdout.emit('data', line.slice(offset, offset + 1024)) - } - child.emit('close', 0, null) - } finally { - spy.mockRestore() - } - const result = await resultPromise - expect(result.totalMatches).toBe(1) - expect(result.files[0].filePath).toBe('/repo/file.ts') - expect(result.files[0].matches[0].lineContent).toContain('needle🐋') - expect(scanned).toBeLessThanOrEqual(line.length * 2) - expect(child.stdout.listenerCount('data')).toBe(0) - }) -}) - -function createFileSearch(options?: Parameters[0]) { - const { host, store } = createRuntimeFileHost(options) - return { commands: new RuntimeFileSearch(host), store } -} diff --git a/src/main/runtime/integrations/github/runtime-github-issue-comment-commands.ts b/src/main/runtime/integrations/github/runtime-github-issue-comment-commands.ts index 3735a5c2c6e..75fd1e209a5 100644 --- a/src/main/runtime/integrations/github/runtime-github-issue-comment-commands.ts +++ b/src/main/runtime/integrations/github/runtime-github-issue-comment-commands.ts @@ -22,7 +22,7 @@ import { resolveIssueGitHubApiRepositorySource } from '../../../github/github-api-repository' import { projectGhExecOptions } from '../../../github/project-view/internals' -import { runAsDefaultWslCliUserAct } from '../../../git/command-runner/default-wsl-cli-fallback' +import { runAsDefaultWslCliUserAct } from '../../../git/command-runner/hosted-cli/default-wsl-cli-fallback' type LocalGitArgs = [] | [LocalProjectGhExecOptions] diff --git a/src/main/runtime/repositories/runtime-nested-repo-import.ts b/src/main/runtime/repositories/runtime-nested-repo-import.ts index 9a4a796bf55..7cfb86e7c36 100644 --- a/src/main/runtime/repositories/runtime-nested-repo-import.ts +++ b/src/main/runtime/repositories/runtime-nested-repo-import.ts @@ -14,7 +14,7 @@ import { getRepoExecutionHostId, getRepoRoutingConnectionId } from '../../../shared/execution-host' -import { awaitWindowsHostGitEnvironmentReady } from '../../git/command-runner/windows-host-git-environment' +import { awaitWindowsHostGitEnvironmentReady } from '../../git/command-runner/host-routing/windows-host-git-environment' import { getRepoName } from '../../git/repo' import { isGitRepoAsync } from '../../git/repo-detection' import { scanNestedRepos } from '../../project-groups/nested-repo-discovery' diff --git a/src/main/runtime/repositories/runtime-repository-clone-controller.ts b/src/main/runtime/repositories/runtime-repository-clone-controller.ts index 92fc7def209..3b3f5df0f83 100644 --- a/src/main/runtime/repositories/runtime-repository-clone-controller.ts +++ b/src/main/runtime/repositories/runtime-repository-clone-controller.ts @@ -14,7 +14,7 @@ import { getSavedProjectPathKeys } from '../../git/repo-clone-path' import { gitSpawnAfterWindowsEnvironmentReady } from '../../git/command-runner/git-spawn' -import { promptGuardGitEnv } from '../../git/command-runner/git-process-env' +import { promptGuardGitEnv } from '../../git/command-runner/git-environment/git-process-env' import { reuseSavedCloneTarget } from '../../git/saved-clone-target' import { checkCloneTarget } from '../../git/clone-target-check' import type { diff --git a/src/main/runtime/repositories/runtime-repository-fork-backfill.ts b/src/main/runtime/repositories/runtime-repository-fork-backfill.ts index ed74f846c04..c4499d0f772 100644 --- a/src/main/runtime/repositories/runtime-repository-fork-backfill.ts +++ b/src/main/runtime/repositories/runtime-repository-fork-backfill.ts @@ -2,7 +2,7 @@ import { getRepoExecutionHostId, getRepoSshConnectionId } from '../../../shared/ import type { Repo } from '../../../shared/repo-types' import { githubAvatarIcon, githubAvatarSlug } from '../../../shared/repo-icon' import { probeRepoUpstream } from '../../github/client/fetch/repo-slug-upstream' -import { GhExecutableAbsenceBatch } from '../../git/command-runner/gh-executable-absence-batch' +import { GhExecutableAbsenceBatch } from '../../git/command-runner/hosted-cli/gh-executable-absence-batch' import type { RuntimeStore } from '../construction/runtime-store-contract' import { isWslMoveRepoBlocked } from '../../persistence/moving-wsl-projects/orchestration/wsl-move-background-backoff' import { blockedWslDistroForPath, wslDistroForPath } from '../../wsl/filesystem/wsl-unc-access-gate' diff --git a/src/main/runtime/repositories/runtime-repository-registration-controller.ts b/src/main/runtime/repositories/runtime-repository-registration-controller.ts index 61d975024ee..a2ba0c08d28 100644 --- a/src/main/runtime/repositories/runtime-repository-registration-controller.ts +++ b/src/main/runtime/repositories/runtime-repository-registration-controller.ts @@ -9,7 +9,7 @@ import { } from '../../../shared/execution-host' import type { Repo } from '../../../shared/repo-types' import { gitExecFileAsync } from '../../git/command-runner/git-exec-file' -import { awaitWindowsHostGitEnvironmentReady } from '../../git/command-runner/windows-host-git-environment' +import { awaitWindowsHostGitEnvironmentReady } from '../../git/command-runner/host-routing/windows-host-git-environment' import { getRepoName } from '../../git/repo' import { inspectGitRepoForRegistrationAsync } from '../../git/repo-detection' import { getClonePathComparisonKey, getSavedProjectPathKeys } from '../../git/repo-clone-path' diff --git a/src/main/runtime/rpc/repo-add-cli.integration.test.ts b/src/main/runtime/rpc/repo-add-cli.integration.test.ts index 4e0332a61df..7df22e21d50 100644 --- a/src/main/runtime/rpc/repo-add-cli.integration.test.ts +++ b/src/main/runtime/rpc/repo-add-cli.integration.test.ts @@ -20,7 +20,7 @@ vi.mock('../../workspaces/creation/worktree-root-preparation', () => ({ prepareLocalWorktreeRootForRepo: vi.fn().mockResolvedValue(undefined) })) -vi.mock('../../git/command-runner/gh-exec-file', () => ({ +vi.mock('../../git/command-runner/hosted-cli/gh-exec-file', () => ({ ghExecFileAsync: vi.fn(async () => ({ stdout: '{"isFork":false}' })) })) diff --git a/src/main/runtime/terminal/artifacts/orca-runtime-files-terminal-artifact-grants.test.ts b/src/main/runtime/terminal/artifacts/orca-runtime-files-terminal-artifact-grants.test.ts index e2d888a7c9a..df795e843f5 100644 --- a/src/main/runtime/terminal/artifacts/orca-runtime-files-terminal-artifact-grants.test.ts +++ b/src/main/runtime/terminal/artifacts/orca-runtime-files-terminal-artifact-grants.test.ts @@ -21,7 +21,7 @@ vi.mock( vi.mock('../../../ipc/filesystem/access/filesystem-auth', async () => (await import('../../files/runtime-file-command-mock-registry')).filesystemAuthModuleMock() ) -vi.mock('../../../git/runner', async () => +vi.mock('../../../git/command-runner/host-routing/wsl-aware-spawn', async () => (await import('../../files/runtime-file-command-mock-registry')).gitRunnerModuleMock() ) vi.mock( diff --git a/src/main/runtime/terminal/artifacts/orca-runtime-files-terminal-artifact-io.test.ts b/src/main/runtime/terminal/artifacts/orca-runtime-files-terminal-artifact-io.test.ts index 7e21117b30b..c87e9b5e8e7 100644 --- a/src/main/runtime/terminal/artifacts/orca-runtime-files-terminal-artifact-io.test.ts +++ b/src/main/runtime/terminal/artifacts/orca-runtime-files-terminal-artifact-io.test.ts @@ -5,7 +5,7 @@ import { useTerminalArtifactTempFiles } from './orca-runtime-files-terminal-artifact-fixtures' import { describe, expect, it, vi } from 'vitest' -import { open, readFile, rm, symlink, utimes, writeFile } from 'node:fs/promises' +import { readFile, rm, symlink, writeFile } from 'node:fs/promises' import { join } from 'node:path' import { renameMock, @@ -13,10 +13,6 @@ import { statMock } from '../../files/runtime-file-command-mock-registry' import { useRuntimeFileHostLifecycle } from '../../files/runtime-file-host.test-fixture' -import { - LOCAL_PREVIEWABLE_BINARY_MAX_BYTES, - RUNTIME_PREVIEWABLE_BINARY_MAX_BYTES -} from '../../files/file-preview-budget' vi.mock('fs', async () => (await import('../../files/runtime-file-command-mock-registry')).fsModuleMock() @@ -31,7 +27,7 @@ vi.mock( vi.mock('../../../ipc/filesystem/access/filesystem-auth', async () => (await import('../../files/runtime-file-command-mock-registry')).filesystemAuthModuleMock() ) -vi.mock('../../../git/runner', async () => +vi.mock('../../../git/command-runner/host-routing/wsl-aware-spawn', async () => (await import('../../files/runtime-file-command-mock-registry')).gitRunnerModuleMock() ) vi.mock( @@ -159,67 +155,7 @@ describe('RuntimeTerminalArtifacts', () => { await expect(readFile(artifactPath, 'utf8')).resolves.toBe('{"ok":true}') }) - it('pages a granted binary file whole, beyond the text read cap, for its client only', async () => { - const bytes = Buffer.alloc(3 * 1024 * 1024 + 7, 0xab) - bytes[0] = 0 - const artifactPath = await tempFile('teste.mp4', '') - await writeFile(artifactPath, bytes) - const { paths, commands } = createTerminalArtifactSubjects({ path: '/repo' }) - resolveAuthorizedPathMock.mockImplementation(async (p: string) => p) - const target = absoluteFileTarget(await resolveTerminalArtifactPath(paths, artifactPath)) - const readPage = (offset: number, clientId = 'client-a') => - commands.readTerminalArtifactChunk( - 'id:wt-1', - target.grantId, - target.absolutePath, - offset, - 512 * 1024, - clientId - ) - - const pages: Buffer[] = [] - for (let offset = 0, eof = false; !eof;) { - const page = await readPage(offset) - pages.push(Buffer.from(page.contentBase64, 'base64')) - offset += page.bytesRead - eof = page.eof - } - - expect(Buffer.concat(pages).equals(bytes)).toBe(true) - await expect(readPage(0, 'client-b')).rejects.toThrow() - }) - // Why: files above the digest cap are pinned by stat alone; utimes can restore mtime but never ctime. - it('rejects a page of a large granted file rewritten in place with its mtime restored', async () => { - const artifactPath = await tempFile('render.mp4', '') - await writeFile(artifactPath, Buffer.alloc(LOCAL_PREVIEWABLE_BINARY_MAX_BYTES + 1, 0xab)) - // Whole seconds, so restoring them reproduces the granted mtime exactly. - const pinnedSeconds = 1_700_000_000 - await utimes(artifactPath, pinnedSeconds, pinnedSeconds) - const { paths, commands } = createTerminalArtifactSubjects({ path: '/repo' }) - resolveAuthorizedPathMock.mockImplementation(async (p: string) => p) - const target = absoluteFileTarget(await resolveTerminalArtifactPath(paths, artifactPath)) - - const handle = await open(artifactPath, 'r+') - const grantedCtimeMs = (await handle.stat()).ctimeMs - // Why: coarse-tick filesystems can stamp a quick rewrite with the granted ctime; rewrite until it moves. - do { - await handle.write(Buffer.alloc(16, 0xcd), 0, 16, 0) - await handle.utimes(pinnedSeconds, pinnedSeconds) - } while ((await handle.stat()).ctimeMs === grantedCtimeMs) - await handle.close() - - await expect( - commands.readTerminalArtifactChunk( - 'id:wt-1', - target.grantId, - target.absolutePath, - 0, - 512 * 1024, - 'client-a' - ) - ).rejects.toThrow('terminal_file_grant_stale') - }) it('rejects retargeted symlink terminal artifact reads before returning outside content', async () => { const artifactPath = await tempFile('result.json', '{"ok":true}') @@ -267,30 +203,6 @@ describe('RuntimeTerminalArtifacts', () => { await expect(readFile(outsidePath, 'utf8')).resolves.toBe('{"secret":true}') }) - it('keeps local terminal artifact previews above the remote cap available', async () => { - const size = RUNTIME_PREVIEWABLE_BINARY_MAX_BYTES + 1 - const artifactPath = await tempFile('result.png', 'a'.repeat(size)) - const { paths, commands } = createTerminalArtifactSubjects({ path: '/repo' }) - resolveAuthorizedPathMock.mockImplementation(async (p: string) => p) - - const result = await resolveTerminalArtifactPath(paths, artifactPath) - const target = absoluteFileTarget(result) - - await expect( - commands.readTerminalArtifactPreview( - 'id:wt-1', - target.grantId, - target.absolutePath, - 'client-a' - ) - ).resolves.toMatchObject({ - content: Buffer.alloc(size, 0x61).toString('base64'), - isBinary: true, - isImage: true, - mimeType: 'image/png' - }) - }) - it('rejects binary-extension terminal artifacts from the editable text path', async () => { const artifactPath = await tempFile('report.pdf', '%PDF text-looking bytes') const { paths, commands } = createTerminalArtifactSubjects({ path: '/repo' }) diff --git a/src/main/runtime/terminal/artifacts/orca-runtime-files-terminal-artifact-swap-detection.test.ts b/src/main/runtime/terminal/artifacts/orca-runtime-files-terminal-artifact-swap-detection.test.ts index 82a6c73c872..2bbc237e458 100644 --- a/src/main/runtime/terminal/artifacts/orca-runtime-files-terminal-artifact-swap-detection.test.ts +++ b/src/main/runtime/terminal/artifacts/orca-runtime-files-terminal-artifact-swap-detection.test.ts @@ -23,7 +23,7 @@ vi.mock( vi.mock('../../../ipc/filesystem/access/filesystem-auth', async () => (await import('../../files/runtime-file-command-mock-registry')).filesystemAuthModuleMock() ) -vi.mock('../../../git/runner', async () => +vi.mock('../../../git/command-runner/host-routing/wsl-aware-spawn', async () => (await import('../../files/runtime-file-command-mock-registry')).gitRunnerModuleMock() ) vi.mock( diff --git a/src/main/runtime/terminal/artifacts/orca-runtime-files-terminal-link-host-translation.test.ts b/src/main/runtime/terminal/artifacts/orca-runtime-files-terminal-link-host-translation.test.ts index a5edae419b4..d1fc8d8251d 100644 --- a/src/main/runtime/terminal/artifacts/orca-runtime-files-terminal-link-host-translation.test.ts +++ b/src/main/runtime/terminal/artifacts/orca-runtime-files-terminal-link-host-translation.test.ts @@ -25,7 +25,7 @@ vi.mock( vi.mock('../../../ipc/filesystem/access/filesystem-auth', async () => (await import('../../files/runtime-file-command-mock-registry')).filesystemAuthModuleMock() ) -vi.mock('../../../git/runner', async () => +vi.mock('../../../git/command-runner/host-routing/wsl-aware-spawn', async () => (await import('../../files/runtime-file-command-mock-registry')).gitRunnerModuleMock() ) vi.mock( diff --git a/src/main/runtime/workspaces/creation/runtime-local-worktree-create-test-harness.ts b/src/main/runtime/workspaces/creation/runtime-local-worktree-create-test-harness.ts index 127b87626bd..586f45801ba 100644 --- a/src/main/runtime/workspaces/creation/runtime-local-worktree-create-test-harness.ts +++ b/src/main/runtime/workspaces/creation/runtime-local-worktree-create-test-harness.ts @@ -5,7 +5,7 @@ import type { WorktreeMeta } from '../../../../shared/worktree/meta-types' import type { HostWorktreeTarget } from '../../../../shared/worktree/host-qualified-identity' import type { Repo } from '../../../../shared/repo-types' import type { RuntimeManagedWorktreeCreateArgs } from './runtime-managed-worktree-create-types' -import { resolveGitAdmissionTier } from '../../../git/command-runner/git-operation-executor' +import { resolveGitAdmissionTier } from '../../../git/command-runner/admission/git-operation-executor' import type { PreparationRearmHolder } from '../../../workspaces/creation/preparation/worktree-create-preparation' import { createWorktreeCreateTimingRecorder, diff --git a/src/main/runtime/workspaces/creation/runtime-local-worktree-create.test.ts b/src/main/runtime/workspaces/creation/runtime-local-worktree-create.test.ts index 8c1e79180ad..5d7cec3f793 100644 --- a/src/main/runtime/workspaces/creation/runtime-local-worktree-create.test.ts +++ b/src/main/runtime/workspaces/creation/runtime-local-worktree-create.test.ts @@ -7,7 +7,7 @@ import type { AddWorktreeOptions } from '../../../git/worktrees/worktree-operati import { acquireGitAdmission, _resetGitAdmissionForTests -} from '../../../git/command-runner/git-subprocess-admission' +} from '../../../git/command-runner/admission/git-subprocess-admission' import { GitAdmissionScheduler } from '../../../../shared/git/admission/git-admission-scheduler' const { diff --git a/src/main/source-control/hosted-review-creation-eligibility.test.ts b/src/main/source-control/hosted-review-creation-eligibility.test.ts index 260b6a82405..95a3b600a83 100644 --- a/src/main/source-control/hosted-review-creation-eligibility.test.ts +++ b/src/main/source-control/hosted-review-creation-eligibility.test.ts @@ -98,7 +98,7 @@ vi.mock('../gitlab/requests/glab-request-admission', () => ({ release: vi.fn() })) -vi.mock('../git/command-runner/glab-exec-file', () => ({ +vi.mock('../git/command-runner/hosted-cli/glab-exec-file', () => ({ glabExecFileAsync: glabExecFileAsyncMock })) diff --git a/src/main/source-control/hosted-review-creation-git-state.ts b/src/main/source-control/hosted-review-creation-git-state.ts index fd2a85d0493..53491b7adbf 100644 --- a/src/main/source-control/hosted-review-creation-git-state.ts +++ b/src/main/source-control/hosted-review-creation-git-state.ts @@ -8,7 +8,7 @@ import type { GitUpstreamStatus } from '../../shared/git/status/git-status-types import { gitExecFileAsync } from '../github/gh-utils' import { isShowRefNoMatchError } from '../../shared/git/refs/git-show-ref-no-match' import { probeExactRefsViaForEachRef } from '../git/exact-ref-probe' -import { gitOptionalLocksDisabledEnv } from '../git/runner' +import { gitOptionalLocksDisabledEnv } from '../git/command-runner/git-environment/git-process-env' import { parsePorcelainV1Records, type PorcelainV1Record diff --git a/src/main/source-control/hosted-review-creation-gitlab-self-hosted.test.ts b/src/main/source-control/hosted-review-creation-gitlab-self-hosted.test.ts index 7a3fbe7ed63..00ae0c91879 100644 --- a/src/main/source-control/hosted-review-creation-gitlab-self-hosted.test.ts +++ b/src/main/source-control/hosted-review-creation-gitlab-self-hosted.test.ts @@ -25,12 +25,12 @@ vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ gitExecFileAsync: gitExecFileAsyncMock })) -vi.mock('../git/command-runner/glab-exec-file', async (importOriginal) => ({ +vi.mock('../git/command-runner/hosted-cli/glab-exec-file', async (importOriginal) => ({ ...(await importOriginal>()), glabExecFileAsync: glabExecFileAsyncMock })) -vi.mock('../git/command-runner/gh-exec-file', async (importOriginal) => ({ +vi.mock('../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ ...(await importOriginal>()), ghExecFileAsync: ghExecFileAsyncMock })) diff --git a/src/main/source-control/hosted-review-creation-provider.ts b/src/main/source-control/hosted-review-creation-provider.ts index fd35cb89d84..f54d913b457 100644 --- a/src/main/source-control/hosted-review-creation-provider.ts +++ b/src/main/source-control/hosted-review-creation-provider.ts @@ -11,7 +11,7 @@ import { acquire as acquireGlab, release as releaseGlab } from '../gitlab/requests/glab-request-admission' -import { glabExecFileAsync } from '../git/command-runner/glab-exec-file' +import { glabExecFileAsync } from '../git/command-runner/hosted-cli/glab-exec-file' import { glabRepoExecOptions } from '../gitlab/projects/gitlab-project-ref-resolution' import { hostedReviewSshConnectionId } from './hosted-review-execution-host' import { diff --git a/src/main/source-control/hosted-review-creation.test.ts b/src/main/source-control/hosted-review-creation.test.ts index 28b03437718..ec8ca06b16e 100644 --- a/src/main/source-control/hosted-review-creation.test.ts +++ b/src/main/source-control/hosted-review-creation.test.ts @@ -98,7 +98,7 @@ vi.mock('../gitlab/requests/glab-request-admission', () => ({ release: vi.fn() })) -vi.mock('../git/command-runner/glab-exec-file', () => ({ +vi.mock('../git/command-runner/hosted-cli/glab-exec-file', () => ({ glabExecFileAsync: glabExecFileAsyncMock })) diff --git a/src/main/source-control/hosted-review-execution-host-routing.test.ts b/src/main/source-control/hosted-review-execution-host-routing.test.ts index 55a527eb520..40ed1a6211b 100644 --- a/src/main/source-control/hosted-review-execution-host-routing.test.ts +++ b/src/main/source-control/hosted-review-execution-host-routing.test.ts @@ -65,7 +65,7 @@ vi.mock('../gitlab/requests/glab-request-admission', () => ({ release: vi.fn() })) -vi.mock('../git/command-runner/glab-exec-file', () => ({ +vi.mock('../git/command-runner/hosted-cli/glab-exec-file', () => ({ glabExecFileAsync: glabExecFileAsyncMock })) @@ -73,7 +73,7 @@ vi.mock('../gitlab/projects/gitlab-project-ref-resolution', () => ({ glabRepoExecOptions: vi.fn(() => ({})) })) -vi.mock('../git/command-runner/git-process-env', async (importOriginal) => ({ +vi.mock('../git/command-runner/git-environment/git-process-env', async (importOriginal) => ({ ...(await importOriginal>()), gitOptionalLocksDisabledEnv: vi.fn(() => ({})) })) diff --git a/src/main/source-control/hosted-review-git-options.ts b/src/main/source-control/hosted-review-git-options.ts index d3db10278b0..289691c6f99 100644 --- a/src/main/source-control/hosted-review-git-options.ts +++ b/src/main/source-control/hosted-review-git-options.ts @@ -1,4 +1,4 @@ -import type { GitAdmissionTier } from '../git/command-runner/git-exec-options' +import type { GitAdmissionTier } from '../../shared/rpc-contract/git-admission-tier-params' import type { GhAccountBinding } from '../../shared/github/account-binding' export type HostedReviewLocalGitOptions = { diff --git a/src/main/source-control/repo-default-branch.ts b/src/main/source-control/repo-default-branch.ts index 7af70f71d64..0fc27c1e6f4 100644 --- a/src/main/source-control/repo-default-branch.ts +++ b/src/main/source-control/repo-default-branch.ts @@ -4,7 +4,7 @@ import { type GitExec } from '../../shared/git/refs/git-default-base-ref' -import { gitExecFileAsync } from '../git/runner' +import { gitExecFileAsync } from '../git/command-runner/git-exec-file' import { getRepoExecutionHostId } from '../../shared/execution-host' import { hostedReviewRepoScope, scopeGeneration } from './hosted-review-scope-generations' import type { HostedReviewLocalGitOptions } from './hosted-review-git-options' diff --git a/src/main/source-control/review-current-head.ts b/src/main/source-control/review-current-head.ts index a74e7b387ad..b805970b7de 100644 --- a/src/main/source-control/review-current-head.ts +++ b/src/main/source-control/review-current-head.ts @@ -1,4 +1,4 @@ -import { gitExecFileAsync } from '../git/runner' +import { gitExecFileAsync } from '../git/command-runner/git-exec-file' import { requireReachableGitRoute } from '../providers/execution-host-provider-dispatch' import { getConnectionExecutionHostId } from '../../shared/execution-host' import type { HostedReviewLocalGitOptions } from './hosted-review-git-options' diff --git a/src/main/startup/main-process-ready-foundation.ts b/src/main/startup/main-process-ready-foundation.ts index 12b535e211c..af0d0d23b60 100644 --- a/src/main/startup/main-process-ready-foundation.ts +++ b/src/main/startup/main-process-ready-foundation.ts @@ -28,10 +28,8 @@ import { initSshHostKeyStoreFile } from '../ssh/host-keys/ssh-host-key-store' import { initOrcadHeldFenceTokenFile } from '../managed-server/activation/orcad-held-fence-tokens' import { neutralizeLegacyTerminalShimDir } from '../pty/shell-startup/legacy-terminal-shim-dir' import { createWindowsShellPathHydration } from './windows-shell-path-hydration' -import { - configureWindowsHostGitEnvironmentReadiness, - setDefaultWslDistroOverride -} from '../git/runner' +import { configureWindowsHostGitEnvironmentReadiness } from '../git/command-runner/host-routing/windows-host-git-environment' +import { setDefaultWslDistroOverride } from '../git/command-runner/host-routing/wsl-command-resolution' import { wslHookRelayManager } from '../agent-hooks/wsl-relay/wsl-hook-relay-manager' import { applyAppIcon } from '../window/desktop-integration/app-icon' import { diff --git a/src/main/text-generation/source-control-agent-launch.ts b/src/main/text-generation/source-control-agent-launch.ts index 52c3aa07b0c..4f257cb93a2 100644 --- a/src/main/text-generation/source-control-agent-launch.ts +++ b/src/main/text-generation/source-control-agent-launch.ts @@ -4,7 +4,7 @@ import { withCliRuntimeOnPath } from '../../shared/node-cli-command-resolution' import { ORCA_AGENT_HOOKS_DISABLED_ENV } from '../../shared/agent-hook-listener/transport/agent-hook-suppression-env' import { quotePosixShell } from '../../shared/shell/launch/shell-argument-quoting' import { resolveCliCommand } from '../codex-cli/command' -import { wslAwareSpawn } from '../git/runner' +import { wslAwareSpawn } from '../git/command-runner/host-routing/wsl-aware-spawn' import { AGENT_PANE_HOOK_ENV_KEYS } from '../ipc/pty/host-env/spawn-env-keys' import { processEnvWithoutAgentSession } from '../../shared/agent-launch/startup/parent-agent-session-env' import { spawnSupervisedAgent } from './source-control-supervised-agent-spawn' diff --git a/src/main/text-generation/source-control-wsl-launch.test.ts b/src/main/text-generation/source-control-wsl-launch.test.ts index 434ec7df29e..ae17df2abcc 100644 --- a/src/main/text-generation/source-control-wsl-launch.test.ts +++ b/src/main/text-generation/source-control-wsl-launch.test.ts @@ -13,7 +13,7 @@ import { planCommitMessageGeneration } from '../../shared/source-control/ai/gene import { withPlatform } from './commit-message-text-generation-test-harness' import { spawnSourceControlAgent } from './source-control-agent-launch' import './source-control-local-generation' -import { resolveCommand } from '../git/command-runner/wsl-command-resolution' +import { resolveCommand } from '../git/command-runner/host-routing/wsl-command-resolution' const { spawnMock } = vi.hoisted(() => ({ spawnMock: vi.fn() })) vi.mock('node:child_process', async (original) => { diff --git a/src/main/updater/releases/updater-release-api-token.test.ts b/src/main/updater/releases/updater-release-api-token.test.ts index 6eb646798ca..6ea38a0bbf8 100644 --- a/src/main/updater/releases/updater-release-api-token.test.ts +++ b/src/main/updater/releases/updater-release-api-token.test.ts @@ -1,7 +1,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' const ghExecMock = vi.fn() -vi.mock('../../git/command-runner/gh-exec-file', () => ({ +vi.mock('../../git/command-runner/hosted-cli/gh-exec-file', () => ({ ghExecFileWithScopeAsync: async (...args: unknown[]) => ({ rateLimitScope: 'native:github.com', ...(await ghExecMock(...args)) diff --git a/src/main/updater/releases/updater-release-api-token.ts b/src/main/updater/releases/updater-release-api-token.ts index 9439c0c137e..7f3cac69b7b 100644 --- a/src/main/updater/releases/updater-release-api-token.ts +++ b/src/main/updater/releases/updater-release-api-token.ts @@ -1,4 +1,4 @@ -import { ghExecFileWithScopeAsync } from '../../git/command-runner/gh-exec-file' +import { ghExecFileWithScopeAsync } from '../../git/command-runner/hosted-cli/gh-exec-file' // Use ambient gh auth to avoid the shared per-IP quota; missing login falls back to unauthenticated. diff --git a/src/main/workspace-hooks/hooks.ts b/src/main/workspace-hooks/hooks.ts index 6194e841958..0b5c0177188 100644 --- a/src/main/workspace-hooks/hooks.ts +++ b/src/main/workspace-hooks/hooks.ts @@ -7,7 +7,7 @@ import { getHookRuntimeTarget, getHookWslContext } from './hook-runtime-target' import { getSetupEnvVars, type HookWorkspaceIdentity } from './setup-hook-env-vars' import { applyHostHookOrcaCliEnv, wslHookOrcaCliEnv } from './hook-orca-cli-env' import { iterateLfScriptLines } from './setup-runner-script-text' -import { promptGuardShellEnv } from '../git/command-runner/git-process-env' +import { promptGuardShellEnv } from '../git/command-runner/git-environment/git-process-env' import { dropIncoherentCondaActivationEnv } from '../pty/shell-startup/conda-activation-env' import { toLinuxPath } from '../../shared/wsl-paths' import { runWslProcess } from '../wsl/execution/wsl-runner' diff --git a/src/main/workspace-hooks/worktree-runner-script.ts b/src/main/workspace-hooks/worktree-runner-script.ts index e7dd4ef7288..14b1db3a075 100644 --- a/src/main/workspace-hooks/worktree-runner-script.ts +++ b/src/main/workspace-hooks/worktree-runner-script.ts @@ -9,7 +9,7 @@ import { scriptDeclaresPosixShell } from '../../shared/workspace-setup/setup-scr import { resolveWindowsShellStartupFamily } from '../../shared/windows-terminal-shell' import { resolveWindowsGitBashShellPath } from '../pty/shell-startup/git-bash' import { gitExecFileSync } from '../git/command-runner/git-exec-file-sync' -import { isLocalGitRuntimeRouterInstalled } from '../git/command-runner/local-git-runtime-route' +import { isLocalGitRuntimeRouterInstalled } from '../git/command-runner/host-routing/local-git-runtime-route' import { readWorktreeGitPath } from '../git/worktrees/catalog/worktree-git-path' import { resolveWslWorktreeGitPath } from '../git/worktrees/catalog/wsl-worktree-git-path' import { knownWslAutomountRoots } from '../wsl/filesystem/wsl-automount-root' diff --git a/src/main/workspaces/catalog/repo-git-remote-identity-enrichment.test.ts b/src/main/workspaces/catalog/repo-git-remote-identity-enrichment.test.ts index 8d81b17a632..8e874d465dc 100644 --- a/src/main/workspaces/catalog/repo-git-remote-identity-enrichment.test.ts +++ b/src/main/workspaces/catalog/repo-git-remote-identity-enrichment.test.ts @@ -8,7 +8,7 @@ import { type GitRemoteIdentityProbe, probeGitRemoteIdentity } from './repo-git- import { WSL_HOSTS_INTERNAL_GATE_ENV } from '../../../shared/wsl-host-internal-gate' import type * as DistroGate from '../../wsl/discovery/wsl-background-distro-gate' import type { WslDistroRunningState } from '../../wsl/discovery/wsl-background-distro-gate' -import '../../git/command-runner/local-git-runtime-route' +import '../../git/command-runner/host-routing/local-git-runtime-route' import { enrichMissingRepoGitRemoteIdentities, flushRepoGitRemoteIdentityEnrichmentForTests, diff --git a/src/main/workspaces/catalog/repo-git-remote-identity-enrichment.ts b/src/main/workspaces/catalog/repo-git-remote-identity-enrichment.ts index 093d4bcb11d..7395514a532 100644 --- a/src/main/workspaces/catalog/repo-git-remote-identity-enrichment.ts +++ b/src/main/workspaces/catalog/repo-git-remote-identity-enrichment.ts @@ -12,7 +12,7 @@ import { getProjectProviderIdentity } from '../../../shared/project-host-setup-p import { getStoredRepoExecutionHostId } from '../execution-host/repo-execution-host' import { probeGitRemoteIdentity } from './repo-git-remote-identity' import { getProjectRuntimeReadGitOptions } from '../execution-host/project-runtime-git-options' -import { isLocalGitRuntimeRouterInstalled } from '../../git/command-runner/local-git-runtime-route' +import { isLocalGitRuntimeRouterInstalled } from '../../git/command-runner/host-routing/local-git-runtime-route' import type { ProjectRuntimeResolutionStore } from '../execution-host/local-project-runtime-resolution' import { isWslMoveRepoBlocked } from '../../persistence/moving-wsl-projects/orchestration/wsl-move-background-backoff' import { blockedWslDistroForPath, wslDistroForPath } from '../../wsl/filesystem/wsl-unc-access-gate' diff --git a/src/main/workspaces/execution-host/project-runtime-git-router-store.test.ts b/src/main/workspaces/execution-host/project-runtime-git-router-store.test.ts index a32fef94cd0..f78667d8ee4 100644 --- a/src/main/workspaces/execution-host/project-runtime-git-router-store.test.ts +++ b/src/main/workspaces/execution-host/project-runtime-git-router-store.test.ts @@ -9,7 +9,7 @@ import { isLocalGitRuntimeRouterInstalled, routeLocalGitOptions, setLocalGitRuntimeRouter -} from '../../git/command-runner/local-git-runtime-route' +} from '../../git/command-runner/host-routing/local-git-runtime-route' import { noteWslHostsLivePolicyBlock, resetWslHostsGateForTests diff --git a/src/main/workspaces/execution-host/project-runtime-git-router.ts b/src/main/workspaces/execution-host/project-runtime-git-router.ts index 2bc0a37e0f0..0d46f674364 100644 --- a/src/main/workspaces/execution-host/project-runtime-git-router.ts +++ b/src/main/workspaces/execution-host/project-runtime-git-router.ts @@ -20,7 +20,7 @@ import { setBackgroundWslGitGate, setLocalGitRuntimeRouter, type LocalGitRuntimeRouter -} from '../../git/command-runner/local-git-runtime-route' +} from '../../git/command-runner/host-routing/local-git-runtime-route' import { isWslDistroRunningForBackgroundWork } from '../../wsl/discovery/wsl-background-distro-gate' import { onWslHostsNewWorkChanged, diff --git a/src/shared/remote-runtime/requests/remote-runtime-request-connection.test.ts b/src/shared/remote-runtime/requests/remote-runtime-request-connection.test.ts index 543062d4b35..ecafb26db71 100644 --- a/src/shared/remote-runtime/requests/remote-runtime-request-connection.test.ts +++ b/src/shared/remote-runtime/requests/remote-runtime-request-connection.test.ts @@ -20,13 +20,13 @@ import { import { RemoteRuntimeRequestConnection } from './remote-runtime-request-connection' import { remoteRuntimeClientCapabilities } from '../remote-runtime-client-capabilities' import { createFakeSpawnedChild } from '../../__fixtures__/fake-spawned-child' -import * as commandResolution from '../../../main/git/command-runner/git-command-resolution' +import * as commandResolution from '../../../main/git/command-runner/host-routing/git-command-resolution' import * as gitRunner from '../../../main/git/command-runner/git-exec-file' import { acquireGitAdmission, _gitAdmissionSnapshotForTests, _resetGitAdmissionForTests -} from '../../../main/git/command-runner/git-subprocess-admission' +} from '../../../main/git/command-runner/admission/git-subprocess-admission' import { GitAdmissionScheduler } from '../../git/admission/git-admission-scheduler' const { execFileMock } = vi.hoisted(() => ({ execFileMock: vi.fn() })) diff --git a/tests/e2e/paired-external-worktree-discovery.spec.ts b/tests/e2e/paired-external-worktree-discovery.spec.ts deleted file mode 100644 index 2242f03b713..00000000000 --- a/tests/e2e/paired-external-worktree-discovery.spec.ts +++ /dev/null @@ -1,170 +0,0 @@ -import { rmSync } from 'node:fs' -import path from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { gitExecFileAsync } from '../../src/main/git/runner' -import { listWorktreesStrict } from '../../src/main/git/worktrees/catalog/worktree-listing' -import { areWorktreePathsEqual } from '../../src/main/git/worktrees/catalog/worktree-path-comparison' -import { expect, test } from './helpers/orca-app' -import { - createRuntimeDesktopPairingOffer, - launchPairedElectronClient, - type PairedElectronClient -} from './helpers/paired-electron-client' -import { worktreeRow } from './worktree-row-locators' - -function equivalentTestPaths(value: string): string[] { - const normalized = path.normalize(value) - if (process.platform === 'win32') { - return [normalized.replaceAll('\\', '/').toLowerCase()] - } - if (process.platform !== 'darwin') { - return [normalized] - } - return normalized.startsWith('/private/var/') - ? [normalized, normalized.slice('/private'.length)] - : [normalized, `/private${normalized}`] -} - -function pathsMatch(left: string, right: string): boolean { - return equivalentTestPaths(left).some((candidate) => areWorktreePathsEqual(candidate, right)) -} - -function waitForCatalogWorktree(page: Page, repoId: string, worktreePath: string): Promise { - return page.evaluate( - ({ expectedPaths, expectedRepoId, windows }) => { - const comparablePath = (value: string): string => - windows ? value.replaceAll('\\', '/').toLowerCase() : value - const findId = (): string | undefined => - window.__store - ?.getState() - .allWorktrees() - .find( - (worktree) => - worktree.repoId === expectedRepoId && - expectedPaths.includes(comparablePath(worktree.path)) - )?.id - const existing = findId() - if (existing) { - return existing - } - return new Promise((resolve) => { - const unsubscribe = window.__store!.subscribe(() => { - const id = findId() - if (id) { - unsubscribe() - resolve(id) - } - }) - }) - }, - { - expectedPaths: equivalentTestPaths(worktreePath), - expectedRepoId: repoId, - windows: process.platform === 'win32' - } - ) -} - -async function readRuntimeTransportContinuity(page: Page, environmentId: string) { - const remoteControl = await page.evaluate(async (selector) => { - const response = await window.api.runtimeEnvironments.getStatus({ selector }) - if (!response.ok) { - throw new Error(response.error.message) - } - return response.result.remoteControl ?? null - }, environmentId) - if (!remoteControl || remoteControl.state !== 'ready' || remoteControl.lastConnectedAt === null) { - throw new Error('Paired client shared-control transport is not ready') - } - return { - state: remoteControl.state, - lastConnectedAt: remoteControl.lastConnectedAt, - lastClose: remoteControl.lastClose, - lastError: remoteControl.lastError, - reconnectAttempt: remoteControl.reconnectAttempt - } -} - -test('shows an externally created worktree on a paired client without reconnect', async ({ - registerPostElectronShutdownCleanup, - sharedPage, - testRepoPath -}, testInfo) => { - test.setTimeout(120_000) - const suffix = `${Date.now()}-${testInfo.workerIndex}` - const branch = `e2e-paired-external-${suffix}` - const externalPath = path.join(path.dirname(testRepoPath), branch) - let client: PairedElectronClient | undefined - let worktreeCreated = false - registerPostElectronShutdownCleanup(async () => { - if (worktreeCreated) { - await gitExecFileAsync(['worktree', 'remove', '--force', externalPath], { - cwd: testRepoPath - }).catch(() => undefined) - await gitExecFileAsync(['branch', '-D', branch], { cwd: testRepoPath }).catch(() => undefined) - } - rmSync(externalPath, { recursive: true, force: true }) - }) - - try { - const repos = await sharedPage.evaluate( - () => window.__store?.getState().repos.map((repo) => ({ id: repo.id, path: repo.path })) ?? [] - ) - const repoId = repos.find((repo) => pathsMatch(repo.path, testRepoPath))?.id - if (!repoId) { - throw new Error(`Headed host did not catalog ${testRepoPath}`) - } - client = await launchPairedElectronClient( - await createRuntimeDesktopPairingOffer(sharedPage), - testInfo, - 'External worktree discovery' - ) - await client.page.waitForFunction( - ({ expectedPaths, expectedRepoId, windows }) => - window.__store - ?.getState() - .allWorktrees() - .some( - (worktree) => - worktree.repoId === expectedRepoId && - expectedPaths.includes( - windows ? worktree.path.replaceAll('\\', '/').toLowerCase() : worktree.path - ) - ) ?? false, - { - expectedPaths: equivalentTestPaths(testRepoPath), - expectedRepoId: repoId, - windows: process.platform === 'win32' - } - ) - - const clientTransportBefore = await readRuntimeTransportContinuity( - client.page, - client.environmentId - ) - const hostCatalogUpdate = waitForCatalogWorktree(sharedPage, repoId, externalPath) - const clientCatalogUpdate = waitForCatalogWorktree(client.page, repoId, externalPath) - await gitExecFileAsync(['worktree', 'add', '--quiet', '-b', branch, externalPath], { - cwd: testRepoPath - }) - worktreeCreated = true - - expect( - (await listWorktreesStrict(testRepoPath)).some((worktree) => - pathsMatch(worktree.path, externalPath) - ) - ).toBe(true) - const [hostWorktreeId, clientWorktreeId] = await Promise.all([ - hostCatalogUpdate, - clientCatalogUpdate - ]) - expect(clientWorktreeId).toBe(hostWorktreeId) - await expect(worktreeRow(sharedPage, hostWorktreeId)).toBeVisible() - await expect(worktreeRow(client.page, clientWorktreeId)).toBeVisible() - expect(await readRuntimeTransportContinuity(client.page, client.environmentId)).toEqual( - clientTransportBefore - ) - } finally { - await client?.dispose() - } -})