Files
orca/src/main/git/remove-worktree-branch-cleanup.test.ts
Neil 9367169888 refactor(tests): split every oversized test file off the max-lines suppression list (#14728)
* refactor(tests): split oversized test files off the max-lines suppression list

Every `*.test.ts`/`*.spec.ts` that carried an `eslint/oxlint-disable max-lines`
directive is now split into focused, behavior-scoped suites that fit the 800-line
test budget, with shared setup extracted into co-located `*-test-harness.ts` /
`*-test-fixtures.ts` modules (300-line budget). 83 files became ~930; the largest
output is 797 effective lines. `orca-runtime.test.ts` is intentionally untouched.

Test bodies were moved by scripted line-range slicing rather than retyped, so
assertions are byte-identical. The only permitted body edits were mechanical
rebinding where a shared value moved into a harness (e.g. `tmpHome` ->
`homes.tmpHome`).

Registries that enumerate test files were updated in lockstep:
- config/max-lines-baseline.txt: pruned 341 -> 258 entries (all 83 removed).
- config/reliability-gates.jsonc: 33 gates repointed at the split files, with
  assertionRefs split per file where a gate's coverage now spans several.
- .github/workflows/pr.yml: the real-zsh lane now lists the 4 split files that
  actually exercise zsh, so they keep running in the dedicated shell lane.

Also renamed agent-hooks `server-test-fixtures.ts` to `server.test-fixtures.ts`
so the global-fetch call-site audit keeps skipping it, and added `.js` extensions
to the CLI suites' dynamic harness imports (node16 resolution) to unbreak
`build:cli`.

Verification: full suite 52,449 passing vs 52,448 at baseline with zero
assertions lost; `pnpm lint`, `pnpm typecheck`, and `pnpm build:cli` all exit 0;
the terminal-pane e2e spec runs 31/31 headless.

* refactor(tests): split hook-idle arbitration suite that oxfmt pushed over budget

The pre-commit oxfmt pass reflowed pty-connection-hook-idle-arbitration.test.ts
to 811 effective lines, 11 over the test budget. Split the hook-completion side
effect and replacement-agent veto cases into their own suite; both files now sit
well under the cap and the 15 tests are unchanged.

* test: port upstream test changes into the split files after rebase

Rebasing onto main surfaced 27 tests that main had added to files this branch
deleted, plus edits to tests that had already moved. Taking the deletion side of
those modify/delete conflicts would have dropped that coverage silently, so each
upstream change is ported into the split file that now owns the behavior — for
example main's six orchestration mailbox tests land across orchestration-runs,
-send, and -check.

Also repoints `orchestration.notification-mailbox-consistency`, a gate main added
after this branch's gate remap, at those same three split files, and re-prunes
the max-lines baseline against main's (257 entries).

Verified: all 27 upstream test titles present; full suite 52,761 passing with the
only diff vs baseline being 12 tests main itself removed and 3 that moved from
skipped to passing; lint and typecheck exit 0.

* fix(test): flush pending continuations before tearing down terminal test globals

CI shard 5/16 failed on both Node 24 and 26 with `ReferenceError: window is not
defined` from pty-connection.ts, surfacing through
pty-connection-daemon-snapshot-replay.test.ts.

The reattach/settle chains `await` a real promise and then touch `window.api`.
Under fake timers those continuations cannot run, so they only become schedulable
once restoreTerminalTestGlobals() switches back to real timers — which previously
happened immediately before `delete globalThis.window`, so a late continuation
threw and failed the whole file. Flush async ticks in that window instead.

This is latent in the source rather than new: the pre-split 25k-line file kept
running other tests after these, which gave the chains time to settle before
teardown. Splitting the file moved teardown directly behind them.

* fix(test): keep an inert window after terminal test teardown instead of deleting it

The async-tick flush was not enough: the reattach/settle chain can resolve after
teardown regardless of how long we drain, so CI shard 5/16 still failed with
`ReferenceError: window is not defined` from pty-connection.ts.

A real renderer never loses `window`, so deleting it was the artificial part.
Swap in an inert proxy whose properties resolve to callables and whose calls
resolve to undefined, making a late `window.api.pty.*` call a harmless no-op.
The next test replaces it wholesale via installTerminalTestGlobals(), and no test
asserts that `window` is absent.
2026-08-15 00:54:20 -07:00

464 lines
14 KiB
TypeScript

import type * as FsPromises from 'node:fs/promises'
import { beforeEach, describe, expect, it, vi } from 'vitest'
const {
gitExecFileAsyncMock,
gitExecFileSyncMock,
translateWslOutputPathsMock,
statMock,
readFileMock,
resolveGitDirMock,
moveWorktreeDirectoryToTrashMock,
restoreWorktreeDirectoryFromTrashMock,
scheduleWorktreeTrashDeletionMock
} = vi.hoisted(() => ({
gitExecFileAsyncMock: vi.fn(),
gitExecFileSyncMock: vi.fn(),
translateWslOutputPathsMock: vi.fn((output: string) => output),
statMock: vi.fn(),
readFileMock: vi.fn(),
resolveGitDirMock: vi.fn(),
moveWorktreeDirectoryToTrashMock: vi.fn(),
restoreWorktreeDirectoryFromTrashMock: vi.fn(),
scheduleWorktreeTrashDeletionMock: vi.fn()
}))
vi.mock('../worktree-trash', () => ({
moveWorktreeDirectoryToTrash: moveWorktreeDirectoryToTrashMock,
restoreWorktreeDirectoryFromTrash: restoreWorktreeDirectoryFromTrashMock,
scheduleWorktreeTrashDeletion: scheduleWorktreeTrashDeletionMock
}))
vi.mock('./runner', () => ({
gitExecFileAsync: gitExecFileAsyncMock,
gitExecFileSync: gitExecFileSyncMock,
translateWslOutputPaths: translateWslOutputPathsMock
}))
vi.mock('./status', () => ({
resolveGitDir: resolveGitDirMock,
runWithGitReadCacheInvalidation: <T>(run: () => Promise<T>) => run()
}))
vi.mock('fs/promises', async () => {
const actual = await vi.importActual<typeof FsPromises>('fs/promises')
return { ...actual, stat: statMock, readFile: readFileMock }
})
import {
createGitCallReader,
createGitCommandMocker,
expectGitCallOrder,
resetWorktreeGitMocks,
resetWorktreeRemovalState
} from './remove-worktree-test-harness'
import { forceDeleteLocalBranch, removeWorktree } from './worktree'
const mockGitCommands = createGitCommandMocker(gitExecFileAsyncMock)
const getGitCalls = createGitCallReader(gitExecFileAsyncMock)
beforeEach(() => {
resetWorktreeRemovalState({
moveWorktreeDirectoryToTrashMock,
restoreWorktreeDirectoryFromTrashMock,
scheduleWorktreeTrashDeletionMock
})
})
describe('removeWorktree', () => {
beforeEach(() => {
resetWorktreeGitMocks({
gitExecFileAsyncMock,
gitExecFileSyncMock,
translateWslOutputPathsMock,
statMock,
readFileMock,
resolveGitDirMock
})
})
it('keeps removal successful when branch cleanup fails', async () => {
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
mockGitCommands({
'git worktree list --porcelain': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
worktree /repo-feature
HEAD def456
branch refs/heads/feature/test
`
},
'git worktree list --porcelain#2': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
`
},
'git branch -d -- feature/test': {
error: new Error('branch delete failed'),
stderr: 'branch delete failed'
}
})
await expect(removeWorktree('/repo', '/repo-feature')).resolves.toEqual({
preservedBranch: { branchName: 'feature/test', head: 'def456' }
})
expect(warnSpy).toHaveBeenCalledWith(
'[git] Preserved local branch "feature/test" after removing worktree (not fully merged)',
expect.any(Error)
)
warnSpy.mockRestore()
})
it('deletes a squash-merged branch when merging it into the base is a no-op', async () => {
mockGitCommands({
'git worktree list --porcelain -z': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
worktree /repo-feature
HEAD def456
branch refs/heads/feature/test
`
},
'git worktree list --porcelain -z#2': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
`
},
'git worktree list --porcelain': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
`
},
'git worktree list --porcelain#2': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
`
},
'git branch -d -- feature/test': {
error: new Error('branch delete failed'),
stderr: 'error: the branch feature/test is not fully merged'
},
'git config --get branch.feature/test.base': {
stdout: 'refs/remotes/origin/main\n'
},
'git rev-parse --verify --quiet refs/remotes/origin/main^{commit}': {
stdout: 'base123\n'
},
'git rev-parse --verify --quiet HEAD^{commit}': {
stdout: 'base123\n'
},
'git merge-tree --write-tree base123 refs/heads/feature/test': {
stdout: 'tree123\n'
},
'git rev-parse --verify --quiet base123^{tree}': {
stdout: 'tree123\n'
}
})
await expect(removeWorktree('/repo', '/repo-feature')).resolves.toEqual({})
const calls = getGitCalls()
expect(calls).toContain('git branch -d -- feature/test')
expect(calls).toContain('git merge-tree --write-tree base123 refs/heads/feature/test')
expect(calls).toContain('git update-ref -d refs/heads/feature/test def456')
expect(calls).toContain('git config --remove-section branch.feature/test')
expect(calls).not.toContain('git remote')
})
it('deletes a squash-merged branch with branch-only merge commits via expected head', async () => {
mockGitCommands({
'git worktree list --porcelain -z': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
worktree /repo-feature
HEAD def456
branch refs/heads/feature/test
`
},
'git worktree list --porcelain -z#2': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
`
},
'git worktree list --porcelain': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
`
},
'git branch -d -- feature/test': {
error: new Error('branch delete failed'),
stderr: 'error: the branch feature/test is not fully merged'
},
'git config --get branch.feature/test.base': {
stdout: 'refs/remotes/origin/main\n'
},
'git rev-parse --verify --quiet refs/remotes/origin/main^{commit}': {
stdout: 'target123\n'
},
'git merge-tree --write-tree target123 refs/heads/feature/test': {
stdout: 'merged-tree\n'
},
'git rev-parse --verify --quiet target123^{tree}': {
stdout: 'target-tree\n'
},
'git rev-list --right-only --merges --count target123...refs/heads/feature/test': {
stdout: '1\n'
},
'git merge-base target123 refs/heads/feature/test': {
stdout: 'base123\n'
},
'git diff base123 refs/heads/feature/test': {
stdout: 'branch net diff\n'
},
'git patch-id --stable#1': {
stdout: 'patch123 0000000000000000000000000000000000000000\n'
},
'git rev-list --ancestry-path --max-count=201 base123..target123': {
stdout: 'squash123\n'
},
'git show --format= squash123': {
stdout: 'squash diff\n'
},
'git patch-id --stable#2': {
stdout: 'patch123 squash123\n'
},
'git merge-tree --write-tree squash123 refs/heads/feature/test': {
stdout: 'squash-tree\n'
},
'git rev-parse --verify --quiet squash123^{tree}': {
stdout: 'squash-tree\n'
}
})
await expect(removeWorktree('/repo', '/repo-feature')).resolves.toEqual({})
const calls = getGitCalls()
expect(calls).toContain('git update-ref -d refs/heads/feature/test def456')
expect(calls).toContain('git config --remove-section branch.feature/test')
expect(gitExecFileAsyncMock.mock.calls).toContainEqual([
['patch-id', '--stable'],
{ cwd: '/repo', stdin: 'branch net diff\n' }
])
expect(gitExecFileAsyncMock.mock.calls).toContainEqual([
['patch-id', '--stable'],
{ cwd: '/repo', stdin: 'squash diff\n' }
])
})
it('refreshes the saved remote base before deleting a safe-delete-rejected branch', async () => {
mockGitCommands({
'git worktree list --porcelain -z': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
worktree /repo-feature
HEAD def456
branch refs/heads/feature/test
`
},
'git worktree list --porcelain -z#2': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
`
},
'git worktree list --porcelain': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
`
},
'git worktree list --porcelain#2': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
`
},
'git branch -d -- feature/test': {
error: new Error('branch delete failed'),
stderr: 'error: the branch feature/test is not fully merged'
},
'git config --get branch.feature/test.base': {
stdout: 'refs/remotes/origin/main\n'
},
'git remote': {
stdout: 'origin\n'
},
'git fetch --prune origin': {
stdout: ''
},
'git rev-parse --verify --quiet refs/remotes/origin/main^{commit}': {
stdout: 'base123\n'
},
'git merge-tree --write-tree base123 refs/heads/feature/test': {
stdout: 'tree123\n'
},
'git rev-parse --verify --quiet base123^{tree}': {
stdout: 'tree123\n'
}
})
await expect(removeWorktree('/repo', '/repo-feature')).resolves.toEqual({})
const calls = getGitCalls()
const mergeTreeCall = 'git merge-tree --write-tree base123 refs/heads/feature/test'
const mergeTreeIndexes = calls.flatMap((call, index) => (call === mergeTreeCall ? [index] : []))
const fetchIndex = calls.indexOf('git fetch --prune origin')
const updateRefIndex = calls.indexOf('git update-ref -d refs/heads/feature/test def456')
expect(calls).toContain('git fetch --prune origin')
expect(calls).toContain('git update-ref -d refs/heads/feature/test def456')
expect(mergeTreeIndexes).toHaveLength(1)
expect(fetchIndex).toBeLessThan(mergeTreeIndexes[0])
expect(mergeTreeIndexes[0]).toBeLessThan(updateRefIndex)
expectGitCallOrder(
calls,
'git fetch --prune origin',
'git update-ref -d refs/heads/feature/test def456'
)
})
it('preserves an already-merged branch when cleanup races after worktree removal', async () => {
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
mockGitCommands({
'git worktree list --porcelain -z': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
worktree /repo-feature
HEAD def456
branch refs/heads/feature/test
`
},
'git worktree list --porcelain -z#2': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
`
},
'git worktree list --porcelain': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
`
},
'git branch -d -- feature/test': {
error: new Error('branch delete failed'),
stderr: 'error: the branch feature/test is not fully merged'
},
'git config --get branch.feature/test.base': {
stdout: 'refs/remotes/origin/main\n'
},
'git rev-parse --verify --quiet refs/remotes/origin/main^{commit}': {
stdout: 'base123\n'
},
'git rev-list --right-only --merges --count base123...refs/heads/feature/test': {
stdout: '0\n'
},
'git cherry -v base123 refs/heads/feature/test': {
stdout: '- def456 fix: already squash-merged\n'
},
'git update-ref -d refs/heads/feature/test def456': {
error: new Error('cannot lock ref')
}
})
await expect(removeWorktree('/repo', '/repo-feature')).resolves.toEqual({
preservedBranch: { branchName: 'feature/test', head: 'def456' }
})
expect(warnSpy).toHaveBeenCalledWith(
'[git] Failed to delete already-merged local branch "feature/test" after removing worktree',
expect.any(Error)
)
expect(warnSpy).toHaveBeenCalledWith(
'[git] Preserved local branch "feature/test" after removing worktree (not fully merged)',
expect.any(Error)
)
warnSpy.mockRestore()
})
it('force-deletes a preserved branch only at its saved head', async () => {
mockGitCommands({})
await forceDeleteLocalBranch('/repo', 'feature/test', 'def456')
const calls = getGitCalls()
expect(calls).toContain('git worktree list --porcelain')
expect(calls).toContain('git update-ref -d refs/heads/feature/test def456')
expect(calls).toContain('git config --remove-section branch.feature/test')
})
it('refuses to force-delete a preserved branch that is checked out again', async () => {
mockGitCommands({
'git worktree list --porcelain': {
stdout: `worktree /repo-feature
HEAD def456
branch refs/heads/feature/test
`
}
})
await expect(forceDeleteLocalBranch('/repo', 'feature/test', 'def456')).rejects.toThrow(
'checked out in another worktree'
)
expect(getGitCalls()).not.toContain('git update-ref -d refs/heads/feature/test def456')
})
it('restores a preserved branch when a concurrent checkout wins after deletion', async () => {
mockGitCommands({
'git worktree list --porcelain': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
`
},
'git worktree list --porcelain#2': {
stdout: `worktree /repo-feature
HEAD 0000000000000000000000000000000000000000
branch refs/heads/feature/test
`
}
})
await expect(forceDeleteLocalBranch('/repo', 'feature/test', 'def456')).rejects.toThrow(
'checked out in another worktree'
)
expect(gitExecFileAsyncMock.mock.calls.map((call) => call[0])).toContainEqual([
'update-ref',
'refs/heads/feature/test',
'def456',
''
])
})
it('refuses to force-delete a preserved branch after its head changes', async () => {
mockGitCommands({
'git update-ref -d refs/heads/feature/test def456': {
error: new Error('cannot lock ref')
}
})
await expect(forceDeleteLocalBranch('/repo', 'feature/test', 'def456')).rejects.toThrow(
'changed after the workspace was deleted'
)
expect(getGitCalls()).not.toContain('git config --remove-section branch.feature/test')
})
})