Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
ed4da90
fix(worktree): retry local main refresh through git lock contention a…
brennanb2025 Sep 28, 2026
d9be8bb
fix(worktree): overlap the local main refresh with the checkout and r…
brennanb2025 Sep 28, 2026
cf87ce1
fix(worktree): skip the local base refresh when the create makes that…
brennanb2025 Sep 28, 2026
d0c5342
fix(worktree): say plainly what happens after the local base refresh …
brennanb2025 Sep 28, 2026
d3bc7d7
test(worktree): prove SSH local base refreshes of one repo run one at…
brennanb2025 Sep 28, 2026
a62ecbf
test(worktree): drop type assertions from the SSH refresh overlap tes…
brennanb2025 Sep 29, 2026
f00a5a7
fix(worktree): fast-forward local main with one host-owned merge --ff…
brennanb2025 Sep 29, 2026
e174d18
fix(worktree): fast-forward local main even when the repo requires si…
brennanb2025 Sep 29, 2026
cdd6f52
fix(worktree): clear git read caches when a shared local main update …
brennanb2025 Sep 29, 2026
9195e7e
fix(worktree): never overwrite an ignored file when fast-forwarding l…
brennanb2025 Sep 29, 2026
ab6b30d
fix(worktree): keep the local main update a plain fast-forward whatev…
brennanb2025 Sep 29, 2026
3613960
fix(worktree): make the Git 2.25 fast-forward contract pass in CI and…
brennanb2025 Sep 29, 2026
e5011cd
Merge remote-tracking branch 'origin/main' into brennanb2025/create-l…
brennanb2025 Sep 30, 2026
52e48a8
fix(worktree): answer every create from a local main update toward it…
brennanb2025 Sep 30, 2026
822bad1
test(worktree): record the third create's result in the mixed-remote …
brennanb2025 Sep 30, 2026
0e81766
chore(worktree): correct the toast id rationale
brennanb2025 Sep 30, 2026
9344565
Merge remote-tracking branch 'origin/main' into brennanb2025/create-l…
brennanb2025 Sep 30, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions config/scripts/pr-code-change-scope.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ const GIT_COMPAT_PREFIXES = [
'.github/actions/prepare-git-compatibility/',
'src/shared/git-',
'src/shared/review-head-tracking-ref',
'src/shared/worktree/local-base-branch-fast-forward',
'src/main/git/',
'src/relay/git-',
'config/scripts/git-binary-compatibility'
Expand Down
6 changes: 6 additions & 0 deletions config/scripts/pr-code-change-scope.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,12 @@ describe('per-job path classification', () => {
expectClassification(['.github/actions/prepare-git-compatibility/action.yml'], {
git_compatibility: true
})
// The contract pins the local-main fast-forward's exact arguments.
expectClassification(['src/shared/worktree/local-base-branch-fast-forward.ts'], {
git_compatibility: true,
package: true,
package_windows: true
})
})

it('runs the Codex index-heal contract only when the heal or its transport changes', () => {
Expand Down
20 changes: 3 additions & 17 deletions src/main/git/exact-ref-probe.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { isSafeGitRefName } from '../../shared/git-status-upstream-ref'
import { isShowRefNoMatchError } from '../../shared/git-show-ref-no-match'

export { isShowRefNoMatchError }

export type ExactRefProbeExecOptions = {
maxBuffer?: number
Expand All @@ -22,23 +25,6 @@ const EXACT_REF_PROBE_CONCURRENCY = 8
// SHA-1 and SHA-256 repositories both report a full object id here.
const OBJECT_ID_PATTERN = /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/

export function isShowRefNoMatchError(error: unknown): boolean {
const record = error && typeof error === 'object' ? (error as Record<string, unknown>) : undefined
// Git reports a missing ref as numeric exit status 1. Keep string-valued
// transport/error codes (including a relay that happens to use `"1"`) in
// the unknown bucket so SSH loss cannot look like an absent ref.
if (record?.code !== 1) {
return false
}
// `--quiet` makes Git print nothing for a missing ref, but a wrapper that
// also exits 1 always explains itself: `wsl.exe` on a dead distro, a relay
// transport error. Empty stderr is what separates proven absence from a
// probe that never ran. A runner that reports no stderr at all (the SSH
// provider) keeps its existing exit-code contract.
const stderr = record.stderr
return stderr === undefined || stderr === null || String(stderr).trim().length === 0
}

function commandOptions(options: ExactRefProbeExecOptions): ExactRefProbeExecOptions | undefined {
if (options.maxBuffer === undefined && options.timeoutMs === undefined) {
return undefined
Expand Down
626 changes: 276 additions & 350 deletions src/main/git/worktree-add-local-base-refresh.test.ts

Large diffs are not rendered by default.

33 changes: 19 additions & 14 deletions src/main/git/worktree-add-local-base-suggestion.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,9 @@ describe('addWorktree', () => {
const worktreeListOutput = 'worktree /repo\nHEAD abc123\nbranch refs/heads/main\n'
gitExecFileAsyncMock
.mockResolvedValueOnce({ stdout: 'abc123\n' }) // rev-parse refs/remotes/origin/main^{commit}
.mockResolvedValueOnce({ stdout: '0\t2\n' }) // rev-list --left-right --count
.mockResolvedValueOnce({ stdout: 'old-main\n' }) // rev-parse refs/heads/main^{commit}
.mockResolvedValueOnce({ stdout: 'remote-main\n' }) // rev-parse refs/remotes/origin/main^{commit}
.mockResolvedValueOnce({ stdout: '' }) // merge-base captured OIDs
.mockResolvedValueOnce({ stdout: '0\t2\n' }) // rev-list --left-right --count
.mockResolvedValueOnce({ stdout: worktreeListOutput }) // worktree list --porcelain
.mockResolvedValueOnce({ stdout: '' }) // status --porcelain
.mockResolvedValueOnce({ stdout: '' }) // worktree add
Expand All @@ -60,16 +59,23 @@ describe('addWorktree', () => {
localBranch: 'main',
behind: 2
})
expect(gitExecFileAsyncMock.mock.calls[1]).toEqual([
['rev-list', '--left-right', '--count', 'refs/heads/main...refs/remotes/origin/main'],
{ cwd: '/repo' }
expect(gitExecFileAsyncMock.mock.calls.slice(1, 6)).toEqual([
[['rev-parse', '--verify', 'refs/heads/main^{commit}'], { cwd: '/repo' }],
[['rev-parse', '--verify', 'refs/remotes/origin/main^{commit}'], { cwd: '/repo' }],
[['rev-list', '--left-right', '--count', 'old-main...remote-main'], { cwd: '/repo' }],
[['worktree', 'list', '--porcelain'], { cwd: '/repo' }],
[['--no-optional-locks', 'status', '--porcelain', '--untracked-files=no'], { cwd: '/repo' }]
])
// Advisory only: nothing moves the local branch.
const commands = gitExecFileAsyncMock.mock.calls.map(([args]) => args)
expect(commands.some((args) => args.includes('merge') || args[0] === 'update-ref')).toBe(false)
})

it('skips advisory owner probes when the local base is already current', async () => {
gitExecFileAsyncMock
.mockResolvedValueOnce({ stdout: 'abc123\n' }) // resolve creation base
.mockResolvedValueOnce({ stdout: '0\t0\n' }) // local base is current
.mockResolvedValueOnce({ stdout: 'same\n' }) // rev-parse refs/heads/main^{commit}
.mockResolvedValueOnce({ stdout: 'same\n' }) // rev-parse refs/remotes/origin/main^{commit}: current
.mockResolvedValueOnce({ stdout: '' }) // worktree add
.mockResolvedValueOnce({ stdout: '' }) // persist branch base
.mockResolvedValueOnce({ stdout: 'true\n' }) // push.autoSetupRemote already set
Expand All @@ -82,7 +88,8 @@ describe('addWorktree', () => {

expect(gitExecFileAsyncMock.mock.calls.map(([args]) => args)).toEqual([
['rev-parse', '--verify', '--quiet', 'refs/remotes/origin/main^{commit}'],
['rev-list', '--left-right', '--count', 'refs/heads/main...refs/remotes/origin/main'],
['rev-parse', '--verify', 'refs/heads/main^{commit}'],
['rev-parse', '--verify', 'refs/remotes/origin/main^{commit}'],
[
'worktree',
'add',
Expand All @@ -107,10 +114,9 @@ describe('addWorktree', () => {
const worktreeListOutput = 'worktree /repo\nHEAD abc123\nbranch refs/heads/main\n'
gitExecFileAsyncMock
.mockResolvedValueOnce({ stdout: 'abc123\n' }) // rev-parse refs/remotes/foo/bar/main^{commit}
.mockResolvedValueOnce({ stdout: '0\t2\n' }) // rev-list --left-right --count
.mockResolvedValueOnce({ stdout: 'old-main\n' }) // rev-parse refs/heads/main^{commit}
.mockResolvedValueOnce({ stdout: 'remote-main\n' }) // rev-parse refs/remotes/foo/bar/main^{commit}
.mockResolvedValueOnce({ stdout: '' }) // merge-base captured OIDs
.mockResolvedValueOnce({ stdout: '0\t2\n' }) // rev-list --left-right --count
.mockResolvedValueOnce({ stdout: worktreeListOutput }) // worktree list --porcelain
.mockResolvedValueOnce({ stdout: '' }) // status --porcelain
.mockResolvedValueOnce({ stdout: '' }) // worktree add
Expand Down Expand Up @@ -140,8 +146,8 @@ describe('addWorktree', () => {
localBranch: 'main',
behind: 2
})
expect(gitExecFileAsyncMock.mock.calls[1]).toEqual([
['rev-list', '--left-right', '--count', 'refs/heads/main...refs/remotes/foo/bar/main'],
expect(gitExecFileAsyncMock.mock.calls[2]).toEqual([
['rev-parse', '--verify', 'refs/remotes/foo/bar/main^{commit}'],
{ cwd: '/repo' }
])
})
Expand All @@ -150,10 +156,9 @@ describe('addWorktree', () => {
const worktreeListOutput = 'worktree /repo\nHEAD abc123\nbranch refs/heads/main\n'
gitExecFileAsyncMock
.mockResolvedValueOnce({ stdout: 'abc123\n' }) // rev-parse refs/remotes/origin/main^{commit}
.mockResolvedValueOnce({ stdout: '0\t2\n' }) // rev-list --left-right --count
.mockResolvedValueOnce({ stdout: 'old-main\n' }) // rev-parse refs/heads/main^{commit}
.mockResolvedValueOnce({ stdout: 'remote-upstream-main\n' }) // rev-parse refs/remotes/upstream/main^{commit}
.mockResolvedValueOnce({ stdout: '' }) // merge-base captured OIDs
.mockResolvedValueOnce({ stdout: 'remote-main\n' }) // rev-parse refs/remotes/origin/main^{commit}
.mockResolvedValueOnce({ stdout: '0\t2\n' }) // rev-list --left-right --count
.mockResolvedValueOnce({ stdout: worktreeListOutput }) // worktree list --porcelain
.mockResolvedValueOnce({ stdout: ' M package.json\n' }) // status --porcelain
.mockResolvedValueOnce({ stdout: '' }) // worktree add
Expand Down
51 changes: 35 additions & 16 deletions src/main/git/worktree-add.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { runWithGitReadCacheInvalidation } from './status'
import { invalidateWslLinkedWorktreeGitRouting } from './wsl-linked-worktree-git-routing'
import {
getLocalBaseRefUpdateSuggestionForWorktreeCreate,
parseRemoteTrackingLocalBaseRef,
refreshLocalBaseRefForWorktreeCreate
} from './worktree-base-refresh'
import { resolveWorktreeBaseCommitOid } from './worktree-base-ref-probe'
Expand All @@ -22,31 +23,43 @@ import { gitExecOptions, resolveWorktreeAddTimeoutMs } from './worktree-operatio
import { bumpWorktreeScanGeneration } from './worktree-scan-cache'
import { assertNoPendingWorktreeRemovalConflict } from '../worktree-background-removal'

export type WorktreeAddBaseContext = AddWorktreeResult & {
export type WorktreeAddBaseContext = Pick<AddWorktreeResult, 'localBaseRefUpdateSuggestion'> & {
effectiveBase: string
effectiveBaseOid?: string
/** Started, not awaited: the worktree is created from the remote-tracking commit, so the refresh can overlap the checkout. Never rejects. */
pendingLocalBaseRefRefresh?: Promise<LocalBaseRefRefreshResult | undefined>
}

export async function resolveWorktreeAddBaseContext(
repoPath: string,
baseBranch: string,
refreshLocalBaseRef: boolean,
options: AddWorktreeOptions
options: AddWorktreeOptions,
createdBranch: string
): Promise<WorktreeAddBaseContext> {
let effectiveBaseOid: string | null = null
const effectiveBase = await resolveWorktreeAddBaseRef(baseBranch, async (qualifiedRef) => {
effectiveBaseOid = await resolveWorktreeBaseCommitOid(repoPath, qualifiedRef, options)
return effectiveBaseOid !== null
})
const localBaseRefRefresh = refreshLocalBaseRef
? await refreshLocalBaseRefForWorktreeCreate(
repoPath,
baseBranch,
effectiveBase,
options.remoteTrackingBase,
options
)
: undefined
// Why: `-b` refuses an existing branch, so creating the base's own local branch leaves nothing to refresh; probing it would race the overlapped add's branch write into a false "not fast-forward" warning.
const createsLocalBaseBranch =
parseRemoteTrackingLocalBaseRef(baseBranch, effectiveBase, options.remoteTrackingBase)
?.localBranch === createdBranch
const pendingLocalBaseRefRefresh =
refreshLocalBaseRef && !createsLocalBaseBranch
? refreshLocalBaseRefForWorktreeCreate(
repoPath,
baseBranch,
effectiveBase,
options.remoteTrackingBase,
options
).catch((error: unknown) => {
// Why: the create may already have succeeded by the time this settles; a refresh bug must not fail it.
console.warn('addWorktree: local base ref refresh failed unexpectedly', error)
return undefined
})
: undefined
const localBaseRefUpdateSuggestion =
!refreshLocalBaseRef && options.suggestLocalBaseRefUpdate
? await getLocalBaseRefUpdateSuggestionForWorktreeCreate(
Expand All @@ -63,7 +76,7 @@ export async function resolveWorktreeAddBaseContext(
...(!refreshLocalBaseRef && !options.suggestLocalBaseRefUpdate && effectiveBaseOid
? { effectiveBaseOid }
: {}),
...(localBaseRefRefresh ? { localBaseRefRefresh } : {}),
...(pendingLocalBaseRefRefresh ? { pendingLocalBaseRefRefresh } : {}),
...(localBaseRefUpdateSuggestion ? { localBaseRefUpdateSuggestion } : {})
}
}
Expand Down Expand Up @@ -188,7 +201,7 @@ async function performAddWorktree(
// Why: Git still owns that path and branch until the background delete finishes; a create now
// would race it, and the branch cleanup that follows would find the branch checked out again.
assertNoPendingWorktreeRemovalConflict(repoPath, { worktreePath, branch })
let localBaseRefRefresh: LocalBaseRefRefreshResult | undefined
let pendingLocalBaseRefRefresh: Promise<LocalBaseRefRefreshResult | undefined> | undefined
let localBaseRefUpdateSuggestion: LocalBaseRefUpdateSuggestion | undefined
// Why: enable long paths for this Windows checkout without changing user Git config.
const args = [...windowsLongPathGitArgs(repoPath), 'worktree', 'add']
Expand All @@ -207,10 +220,11 @@ async function performAddWorktree(
repoPath,
baseBranch,
refreshLocalBaseRef,
options
options,
branch
)
effectiveBase = baseContext.effectiveBase
localBaseRefRefresh = baseContext.localBaseRefRefresh
pendingLocalBaseRefRefresh = baseContext.pendingLocalBaseRefRefresh
localBaseRefUpdateSuggestion = baseContext.localBaseRefUpdateSuggestion
args.push(effectiveBase)
}
Expand All @@ -221,14 +235,18 @@ async function performAddWorktree(
// Why: resolve per call — hoisting this to a module const would freeze the override at import.
timeout: resolveWorktreeAddTimeoutMs()
})
} catch (error) {
// Why: settle the overlapped refresh inside the caller's ref-maintenance pause before reporting the failure.
await pendingLocalBaseRefRefresh
throw error
} finally {
// Git may have written the target's `.git` marker even when it reports a late
// failure, so drop any pre-create route before the follow-up commands route.
invalidateWslLinkedWorktreeGitRouting(worktreePath)
}

if (options.checkoutExistingBranch) {
return localBaseRefRefresh ? { localBaseRefRefresh } : {}
return {}
}

if (effectiveBase) {
Expand All @@ -241,6 +259,7 @@ async function performAddWorktree(
// linked worktree writes the shared common-dir config (whole repo) — intentional and idempotent,
// so it's warn-only and not rolled back on failure.
await configurePushAutoSetupRemote(worktreePath, options)
const localBaseRefRefresh = await pendingLocalBaseRefRefresh
return {
...(localBaseRefRefresh ? { localBaseRefRefresh } : {}),
...(localBaseRefUpdateSuggestion ? { localBaseRefUpdateSuggestion } : {})
Expand Down
Loading
Loading