Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: clear abandoned git locks in pull/fetch/rebase paths (#7513)

[._.]/ Adam Eivy7a63e2a71c2c
diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.js
index 01933874ab..864536e086 100644
--- a/server/lib/importScoping.test.js
+++ b/server/lib/importScoping.test.js
@@ -658,7 +658,15 @@ describe('deferred imports stay deferred (#6156)', () => {
// The remainder of the raise restores the ~1.5k of headroom this is meant to
// carry: the previous number had drifted to ONE above the measured total, the
// zero-headroom state #6305 raised it out of, where any addition at all fails.
-const MAX_STATIC_INSTANTIATIONS = 109200;
+//
+// Raised to 110700 for the stale git lock fix (#7513). Measured after the
+// change: 109,282, so its own cost is +82 — one new test file
+// (`services/git.staleLock.test.js`) reaching `services/git.js`'s existing
+// closure to cover `pull`/`syncBranch`/`ensureLatest`'s lock-clearing paths.
+// No new heavy edge: `git.js` was already reached by a dozen other server
+// test files. The remainder restores headroom the previous number had worn
+// down to zero.
+const MAX_STATIC_INSTANTIATIONS = 110700;
const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);
diff --git a/server/services/git.js b/server/services/git.js
index e047e3657b..726e797bfc 100644
--- a/server/services/git.js
+++ b/server/services/git.js
@@ -700,7 +700,20 @@ export async function getBranches(dir, { strict = false } = {}) {
* Pull changes from remote for current branch
*/
export async function pull(dir) {
- const result = await execGit(['pull', '--rebase', '--autostash'], dir);
+ const result = await execGit(['pull', '--rebase', '--autostash'], dir).catch((err) => {
+ // A rebase killed mid-flight can leave the repo in a rebase-in-progress
+ // state, so a lock found here is cleared but NOT retried — blindly
+ // re-running `pull --rebase` could stack onto that abandoned state instead
+ // of starting clean. Surface it so the next explicit pull starts fresh.
+ const clearedLock = clearStaleGitLock(err.message);
+ if (clearedLock) {
+ throw new Error(
+ `Cleared an abandoned git lock (${clearedLock}) left by a killed git process. `
+ + `The pull did not run — retry it now that the lock is clear.`
+ );
+ }
+ throw err;
+ });
return { success: true, output: result.stdout + result.stderr };
}
@@ -740,7 +753,14 @@ export async function updateDefaultBranch(dir) {
.filter(Boolean)
.join('\n') || fallback;
- await execGit(['fetch', 'origin'], dir);
+ // A killed `fetch` can leave a shared ref lock (`refs/remotes/origin/*.lock`,
+ // `packed-refs.lock`) that every worktree of this repo shares. `fetch` is
+ // idempotent, so this uses the same clear-and-retry-once shape as
+ // `updateSubmodule` rather than surfacing a permanent, confusing failure.
+ await execGit(['fetch', 'origin'], dir).catch(async (err) => {
+ if (!clearStaleGitLock(err.message)) throw err;
+ await execGit(['fetch', 'origin'], dir);
+ });
const runtimeBranch = await execGit(['config', '--get', 'portos.runtimeBranch'], dir, { ignoreExitCode: true });
const branch = runtimeBranch.stdout.trim() || await getDefaultBranch(dir, { strict: true });
if (!branch) throw new ServerError('could not determine origin default branch', { status: 400, code: 'NO_DEFAULT_BRANCH' });
@@ -754,12 +774,18 @@ export async function updateDefaultBranch(dir) {
const checkout = await execGit(['checkout', branch], dir, { ignoreExitCode: true });
output += checkout.stdout + checkout.stderr;
if (checkout.exitCode !== 0) {
+ // Checkout can leave a partially-written index, so a lock found here is
+ // cleared but NOT retried — the next explicit attempt starts from a
+ // lock-free repo instead of racing this one.
+ const clearedLock = clearStaleGitLock(checkout.stderr);
return {
success: false,
branch,
output,
conflict: true,
- error: bothStreams(checkout, `could not check out ${branch}`)
+ error: clearedLock
+ ? `Cleared an abandoned git lock (${clearedLock}) left by a killed git process. The checkout onto ${branch} did not run — retry the update now that the lock is clear.`
+ : bothStreams(checkout, `could not check out ${branch}`)
};
}
}
@@ -768,6 +794,17 @@ export async function updateDefaultBranch(dir) {
output += fastForward.stdout + fastForward.stderr;
if (fastForward.exitCode === 0) return { success: true, branch, output, conflict: false };
+ const fastForwardLock = clearStaleGitLock(fastForward.stderr);
+ if (fastForwardLock) {
+ return {
+ success: false,
+ branch,
+ output,
+ conflict: true,
+ error: `Cleared an abandoned git lock (${fastForwardLock}) left by a killed git process. The fast-forward pull did not run — retry the update now that the lock is clear.`
+ };
+ }
+
const rebase = await execGit(['pull', '--rebase', '--autostash', 'origin', branch], dir, { ignoreExitCode: true });
output += rebase.stdout + rebase.stderr;
if (rebase.exitCode === 0) {
@@ -783,7 +820,21 @@ export async function updateDefaultBranch(dir) {
};
}
+ const rebaseLock = clearStaleGitLock(rebase.stderr);
+ // A rebase killed mid-flight can leave `.git/rebase-merge`/`rebase-apply`
+ // behind alongside the lock, so abort it here too — otherwise the next
+ // attempt fails immediately on "rebase already in progress" instead of the
+ // clean retry this error promises.
await execGit(['rebase', '--abort'], dir, { ignoreExitCode: true });
+ if (rebaseLock) {
+ return {
+ success: false,
+ branch,
+ output,
+ conflict: true,
+ error: `Cleared an abandoned git lock (${rebaseLock}) left by a killed git process. The rebase onto origin/${branch} did not complete — retry the update now that the lock is clear.`
+ };
+ }
return {
success: false,
branch,
@@ -804,9 +855,15 @@ export async function syncBranch(dir, branch = null) {
const pullSuccess = !pullResult.stderr?.includes('fatal') && !pullResult.stderr?.includes('CONFLICT');
if (!pullSuccess) {
+ // A rebase killed mid-flight can leave the repo in a rebase-in-progress
+ // state, so a lock found here is cleared but NOT retried automatically —
+ // surface it so the next explicit sync starts from a lock-free repo.
+ const clearedLock = clearStaleGitLock(pullResult.stderr);
return {
success: false,
- error: pullResult.stderr || 'Pull failed',
+ error: clearedLock
+ ? `Cleared an abandoned git lock (${clearedLock}) left by a killed git process. The pull did not complete — retry the sync now that the lock is clear.`
+ : (pullResult.stderr || 'Pull failed'),
pulled: false,
pushed: false
};
@@ -853,8 +910,13 @@ export async function ensureLatest(dir) {
const remote = await getRemote(dir).catch(() => null);
if (!remote?.origin) return { success: true, branch: currentBranch, conflict: false, error: null, skipped: 'no-remote' };
- // Fetch latest refs from origin
- const fetchResult = await execGit(['fetch', 'origin'], dir, { ignoreExitCode: true });
+ // Fetch latest refs from origin. Idempotent, so an abandoned lock (left by a
+ // killed git process, shared by every worktree of this repo) is cleared and
+ // retried once rather than reported as a permanent failure.
+ let fetchResult = await execGit(['fetch', 'origin'], dir, { ignoreExitCode: true });
+ if (fetchResult.stderr?.includes('fatal') && clearStaleGitLock(fetchResult.stderr)) {
+ fetchResult = await execGit(['fetch', 'origin'], dir, { ignoreExitCode: true });
+ }
if (fetchResult.stderr?.includes('fatal')) {
return { success: false, branch: currentBranch, conflict: false, error: `fetch failed: ${fetchResult.stderr}` };
}
@@ -887,13 +949,42 @@ export async function ensureLatest(dir) {
return { success: true, branch: currentBranch, conflict: false, error: null };
}
+ // A lock found here is cleared but NOT retried — a blind retry could race a
+ // still-write-in-progress index. Surface it so the next explicit attempt
+ // starts from a lock-free repo.
+ const mergeLock = clearStaleGitLock(mergeResult.stderr);
+ if (mergeLock) {
+ return {
+ success: false,
+ branch: currentBranch,
+ conflict: true,
+ error: `Cleared an abandoned git lock (${mergeLock}) left by a killed git process. The fast-forward merge did not complete — retry now that the lock is clear.`
+ };
+ }
+
// Fast-forward failed — local branch has diverged. Try rebase.
const rebaseResult = await execGit(['rebase', `origin/${currentBranch}`], dir, { ignoreExitCode: true });
- const rebaseOk = !rebaseResult.stderr?.includes('CONFLICT') && !rebaseResult.stderr?.includes('error:');
+ // `fatal:` (git's prefix for an abandoned-lock failure, matching `mergeOk`
+ // above) alongside the existing conflict/error markers — without it a lock
+ // failure here read as a silent success.
+ const rebaseOk = !rebaseResult.stderr?.includes('fatal')
+ && !rebaseResult.stderr?.includes('CONFLICT')
+ && !rebaseResult.stderr?.includes('error:');
if (!rebaseOk) {
- // Rebase failed — abort and report conflict
+ // A rebase killed mid-flight can leave `.git/rebase-merge`/`rebase-apply`
+ // behind alongside a lock, so abort it regardless of the cause before
+ // deciding how to report the failure.
+ const rebaseLock = clearStaleGitLock(rebaseResult.stderr);
await execGit(['rebase', '--abort'], dir, { ignoreExitCode: true });
+ if (rebaseLock) {
+ return {
+ success: false,
+ branch: currentBranch,
+ conflict: true,
+ error: `Cleared an abandoned git lock (${rebaseLock}) left by a killed git process. The rebase onto origin/${currentBranch} did not complete — retry now that the lock is clear.`
+ };
+ }
return {
success: false,
branch: currentBranch,
diff --git a/server/services/git.staleLock.test.js b/server/services/git.staleLock.test.js
new file mode 100644
index 0000000000..7476e51f2f
--- /dev/null
+++ b/server/services/git.staleLock.test.js
@@ -0,0 +1,206 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const execGitMock = vi.hoisted(() => vi.fn());
+
+vi.mock('../lib/execGit.js', () => ({ execGit: execGitMock,
+ execGitSafe: (...args) => execGitMock(...args).catch(err => ({ exitCode: 1, stdout: '', stderr: err.message })) }));
+
+// Mocked so the retry/no-retry decision is driven by a stub, not real file
+// mtimes — `lib/gitStaleLock.test.js` owns proving WHICH locks it agrees to
+// remove.
+vi.mock('../lib/gitStaleLock.js', () => ({ clearStaleGitLock: vi.fn(() => null) }));
+
+import { ensureLatest, pull, syncBranch } from './git.js';
+import { clearStaleGitLock } from '../lib/gitStaleLock.js';
+
+const ok = (stdout = '') => ({ stdout, stderr: '', exitCode: 0 });
+const fail = (stderr = '', exitCode = 1) => ({ stdout: '', stderr, exitCode });
+const key = (args) => args.join(' ');
+const commands = () => execGitMock.mock.calls.map(([args]) => key(args));
+
+beforeEach(() => {
+ execGitMock.mockReset();
+ clearStaleGitLock.mockReset();
+ clearStaleGitLock.mockReturnValue(null);
+});
+
+// `pull`, `syncBranch`, and `ensureLatest` — the rest of the pull/fetch/rebase
+// family `updateSubmodule` already covers (git.submodules.test.js) and
+// `updateDefaultBranch` covers (git.updateDefaultBranch.test.js). A killed git
+// process leaves a shared ref/index lock that wedges every worktree of the
+// repo forever, so each of these clears an abandoned lock but never
+// auto-retries a non-idempotent command (#7513).
+
+describe('pull', () => {
+ it('pulls with rebase and autostash, returning the combined output', async () => {
+ execGitMock.mockResolvedValue(ok('Already up to date.\n'));
+
+ const result = await pull('/repo');
+
+ expect(result).toEqual({ success: true, output: 'Already up to date.\n' });
+ expect(execGitMock).toHaveBeenCalledWith(['pull', '--rebase', '--autostash'], '/repo');
+ });
+
+ it('clears an abandoned lock without retrying the pull', async () => {
+ const lockError = new Error("fatal: Unable to create '/repo/.git/index.lock': File exists");
+ execGitMock.mockRejectedValue(lockError);
+ clearStaleGitLock.mockReturnValue('/repo/.git/index.lock');
+
+ await expect(pull('/repo')).rejects.toThrow(/Cleared an abandoned git lock.*index\.lock/);
+ expect(clearStaleGitLock).toHaveBeenCalledWith(lockError.message);
+ expect(execGitMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('surfaces the original failure unchanged when the lock is too young to clear', async () => {
+ const lockError = new Error("fatal: Unable to create '/repo/.git/index.lock': File exists");
+ execGitMock.mockRejectedValue(lockError);
+
+ await expect(pull('/repo')).rejects.toThrow(/Unable to create/);
+ expect(execGitMock).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('syncBranch', () => {
+ it('pulls with rebase then pushes', async () => {
+ execGitMock.mockImplementation((args) => {
+ if (args[0] === 'pull') return Promise.resolve(ok('Already up to date.\n'));
+ if (args[0] === 'push') return Promise.resolve(ok('everything up-to-date\n'));
+ return Promise.resolve(ok());
+ });
+
+ const result = await syncBranch('/repo', 'feature/work');
+
+ expect(result).toMatchObject({ success: true, pulled: true, pushed: true });
+ expect(execGitMock).toHaveBeenCalledWith(
+ ['pull', '--rebase', '--autostash', 'origin', 'feature/work'], '/repo', { ignoreExitCode: true }
+ );
+ });
+
+ it('clears an abandoned pull lock without retrying, and does not push', async () => {
+ execGitMock.mockImplementation((args) => {
+ if (args[0] === 'pull') return Promise.resolve(fail("fatal: Unable to create '/repo/.git/index.lock': File exists"));
+ return Promise.resolve(ok());
+ });
+ clearStaleGitLock.mockReturnValue('/repo/.git/index.lock');
+
+ const result = await syncBranch('/repo', 'feature/work');
+
+ expect(result).toMatchObject({ success: false, pulled: false, pushed: false });
+ expect(result.error).toContain('/repo/.git/index.lock');
+ expect(commands()).not.toContain('push origin feature/work');
+ });
+
+ it('surfaces the raw pull failure unchanged when the lock is too young to clear', async () => {
+ execGitMock.mockImplementation((args) => {
+ if (args[0] === 'pull') return Promise.resolve(fail("fatal: Unable to create '/repo/.git/index.lock': File exists"));
+ return Promise.resolve(ok());
+ });
+
+ const result = await syncBranch('/repo', 'feature/work');
+
+ expect(result).toMatchObject({ success: false, pulled: false, pushed: false });
+ expect(result.error).toContain('Unable to create');
+ });
+});
+
+describe('ensureLatest', () => {
+ // A local branch already diverged from origin (different SHAs), a clean
+ // working tree, so the flow always reaches the fast-forward-or-rebase steps.
+ const base = {
+ 'rev-parse --is-inside-work-tree': ok('true\n'),
+ 'rev-parse --abbrev-ref HEAD': ok('main\n'),
+ 'remote -v': ok('origin [email protected]:example/example.git (fetch)\norigin [email protected]:example/example.git (push)\n'),
+ 'fetch origin': ok(),
+ 'rev-parse origin/main': ok('b'.repeat(40)),
+ 'rev-parse HEAD': ok('a'.repeat(40)),
+ 'status --porcelain': ok(),
+ 'merge --ff-only origin/main': ok('Fast-forward'),
+ 'rebase origin/main': ok('Successfully rebased'),
+ 'rebase --abort': ok()
+ };
+
+ const withGit = (overrides = {}) => {
+ const table = { ...base, ...overrides };
+ execGitMock.mockImplementation((args) => Promise.resolve(table[key(args)] ?? ok()));
+ };
+
+ beforeEach(() => withGit());
+
+ it('fast-forwards a diverged branch without rebasing', async () => {
+ const result = await ensureLatest('/repo');
+
+ expect(result).toMatchObject({ success: true, branch: 'main', conflict: false });
+ expect(commands()).toContain('merge --ff-only origin/main');
+ expect(commands()).not.toContain('rebase origin/main');
+ });
+
+ // `fetch` is idempotent, so a lock here is cleared and retried once rather
+ // than reported as a permanent failure.
+ it('clears an abandoned fetch lock and retries once', async () => {
+ withGit({ 'fetch origin': fail("fatal: Unable to create '/repo/.git/refs/remotes/origin/main.lock': File exists") });
+ let fetches = 0;
+ const scripted = execGitMock.getMockImplementation();
+ execGitMock.mockImplementation(async (args, cwd, options) => {
+ if (key(args) === 'fetch origin' && ++fetches === 1) return scripted(args, cwd, options);
+ if (key(args) === 'fetch origin') return ok();
+ return scripted(args, cwd, options);
+ });
+ clearStaleGitLock.mockReturnValue('/repo/.git/refs/remotes/origin/main.lock');
+
+ const result = await ensureLatest('/repo');
+
+ expect(result).toMatchObject({ success: true, branch: 'main' });
+ expect(clearStaleGitLock).toHaveBeenCalledWith(expect.stringContaining('main.lock'));
+ expect(commands().filter((c) => c === 'fetch origin')).toHaveLength(2);
+ });
+
+ it('surfaces the fetch lock failure without retrying when the lock is too young', async () => {
+ withGit({ 'fetch origin': fail("fatal: Unable to create '/repo/.git/refs/remotes/origin/main.lock': File exists") });
+
+ const result = await ensureLatest('/repo');
+
+ expect(result).toMatchObject({ success: false, branch: 'main' });
+ expect(result.error).toContain('Unable to create');
+ expect(commands().filter((c) => c === 'fetch origin')).toHaveLength(1);
+ });
+
+ it('clears an abandoned merge lock without falling through to rebase', async () => {
+ withGit({ 'merge --ff-only origin/main': fail("fatal: Unable to create '/repo/.git/index.lock': File exists") });
+ clearStaleGitLock.mockReturnValue('/repo/.git/index.lock');
+
+ const result = await ensureLatest('/repo');
+
+ expect(result).toMatchObject({ success: false, branch: 'main', conflict: true });
+ expect(result.error).toContain('/repo/.git/index.lock');
+ expect(commands()).not.toContain('rebase origin/main');
+ });
+
+ it('clears an abandoned rebase lock, aborts the rebase, and does not retry', async () => {
+ withGit({
+ 'merge --ff-only origin/main': fail('fatal: Not possible to fast-forward, aborting.'),
+ 'rebase origin/main': fail("fatal: Unable to create '/repo/.git/index.lock': File exists")
+ });
+ // The merge failure above names no lock — only the rebase failure should
+ // clear one, or this would (wrongly) short-circuit before the rebase runs.
+ clearStaleGitLock.mockImplementation((message) => (message.includes('.lock') ? '/repo/.git/index.lock' : null));
+
+ const result = await ensureLatest('/repo');
+
+ expect(result).toMatchObject({ success: false, branch: 'main', conflict: true });
+ expect(result.error).toContain('/repo/.git/index.lock');
+ expect(commands()).toContain('rebase --abort');
+ });
+
+ it('reports a genuine rebase conflict unchanged when there is no lock', async () => {
+ withGit({
+ 'merge --ff-only origin/main': fail('fatal: Not possible to fast-forward, aborting.'),
+ 'rebase origin/main': fail('CONFLICT (content): Merge conflict in server/index.js')
+ });
+
+ const result = await ensureLatest('/repo');
+
+ expect(result).toMatchObject({ success: false, branch: 'main', conflict: true });
+ expect(result.error).toContain('diverged from origin and rebase has conflicts');
+ expect(commands()).toContain('rebase --abort');
+ });
+});
diff --git a/server/services/git.updateDefaultBranch.test.js b/server/services/git.updateDefaultBranch.test.js
index 927c0649a8..354e5cc948 100644
--- a/server/services/git.updateDefaultBranch.test.js
+++ b/server/services/git.updateDefaultBranch.test.js
@@ -5,7 +5,13 @@ const execGitMock = vi.hoisted(() => vi.fn());
vi.mock('../lib/execGit.js', () => ({ execGit: execGitMock,
execGitSafe: (...args) => execGitMock(...args).catch(err => ({ exitCode: 1, stdout: '', stderr: err.message })) }));
+// Mocked so the retry/no-retry decision is driven by a stub, not real file
+// mtimes — `lib/gitStaleLock.test.js` owns proving WHICH locks it agrees to
+// remove.
+vi.mock('../lib/gitStaleLock.js', () => ({ clearStaleGitLock: vi.fn(() => null) }));
+
import { updateDefaultBranch } from './git.js';
+import { clearStaleGitLock } from '../lib/gitStaleLock.js';
const ok = (stdout = '') => ({ stdout, stderr: '', exitCode: 0 });
const fail = (stderr = '', exitCode = 1) => ({ stdout: '', stderr, exitCode });
@@ -29,6 +35,8 @@ const withGit = (overrides = {}) => {
beforeEach(() => {
execGitMock.mockReset();
+ clearStaleGitLock.mockReset();
+ clearStaleGitLock.mockReturnValue(null);
withGit();
});
@@ -118,4 +126,86 @@ describe('updateDefaultBranch', () => {
expect(commands()).not.toContain('pull --ff-only origin main');
expect(commands()).not.toContain('rebase --abort');
});
+
+ // A killed `fetch` leaves a lock every worktree of the repo shares — without
+ // this, every later "Update App" click fails forever, blaming a git process
+ // that exited long ago (#7513).
+ it('clears an abandoned fetch lock and retries once', async () => {
+ const lockError = new Error("fatal: Unable to create '/repo/.git/refs/remotes/origin/main.lock': File exists");
+ let fetches = 0;
+ execGitMock.mockImplementation((args) => {
+ if (key(args) === 'fetch origin' && ++fetches === 1) return Promise.reject(lockError);
+ return Promise.resolve(base[key(args)] ?? ok());
+ });
+ clearStaleGitLock.mockReturnValue('/repo/.git/refs/remotes/origin/main.lock');
+
+ const result = await updateDefaultBranch('/repo');
+
+ expect(result).toMatchObject({ success: true, branch: 'main' });
+ expect(clearStaleGitLock).toHaveBeenCalledWith(lockError.message);
+ expect(commands().filter((c) => c === 'fetch origin')).toHaveLength(2);
+ });
+
+ it('surfaces the fetch lock failure without retrying when the lock is too young', async () => {
+ const lockError = new Error("fatal: Unable to create '/repo/.git/refs/remotes/origin/main.lock': File exists");
+ execGitMock.mockImplementation((args) => {
+ if (key(args) === 'fetch origin') return Promise.reject(lockError);
+ return Promise.resolve(base[key(args)] ?? ok());
+ });
+ clearStaleGitLock.mockReturnValue(null);
+
+ await expect(updateDefaultBranch('/repo')).rejects.toThrow(/Unable to create/);
+ expect(commands().filter((c) => c === 'fetch origin')).toHaveLength(1);
+ });
+
+ it('clears an abandoned checkout lock without retrying the checkout', async () => {
+ withGit({ 'checkout main': fail("fatal: Unable to create '/repo/.git/index.lock': File exists") });
+ clearStaleGitLock.mockReturnValue('/repo/.git/index.lock');
+
+ const result = await updateDefaultBranch('/repo');
+
+ expect(result).toMatchObject({ success: false, branch: 'main', conflict: true });
+ expect(result.error).toContain('/repo/.git/index.lock');
+ expect(result.error).toMatch(/retry/i);
+ expect(commands().filter((c) => c === 'checkout main')).toHaveLength(1);
+ expect(commands()).not.toContain('pull --ff-only origin main');
+ });
+
+ it('reports checkout contention unchanged when the lock is too young to clear', async () => {
+ withGit({ 'checkout main': fail("fatal: Unable to create '/repo/.git/index.lock': File exists") });
+ clearStaleGitLock.mockReturnValue(null);
+
+ const result = await updateDefaultBranch('/repo');
+
+ expect(result).toMatchObject({ success: false, branch: 'main', conflict: true });
+ expect(result.error).toContain('Unable to create');
+ });
+
+ it('clears an abandoned fast-forward-pull lock without falling through to rebase', async () => {
+ withGit({ 'pull --ff-only origin main': fail("fatal: Unable to create '/repo/.git/refs/remotes/origin/main.lock': File exists") });
+ clearStaleGitLock.mockReturnValue('/repo/.git/refs/remotes/origin/main.lock');
+
+ const result = await updateDefaultBranch('/repo');
+
+ expect(result).toMatchObject({ success: false, branch: 'main', conflict: true });
+ expect(result.error).toContain('/repo/.git/refs/remotes/origin/main.lock');
+ expect(commands()).not.toContain('pull --rebase --autostash origin main');
+ });
+
+ it('clears an abandoned rebase lock, aborts the rebase, and does not retry', async () => {
+ withGit({
+ 'pull --ff-only origin main': fail('fatal: Not possible to fast-forward, aborting.'),
+ 'pull --rebase --autostash origin main': fail("fatal: Unable to create '/repo/.git/index.lock': File exists")
+ });
+ // The ff-only failure above names no lock — only the rebase failure should
+ // clear one, or this would (wrongly) short-circuit before the rebase runs.
+ clearStaleGitLock.mockImplementation((message) => (message.includes('.lock') ? '/repo/.git/index.lock' : null));
+
+ const result = await updateDefaultBranch('/repo');
+
+ expect(result).toMatchObject({ success: false, branch: 'main', conflict: true });
+ expect(result.error).toContain('/repo/.git/index.lock');
+ expect(commands()).toContain('rebase --abort');
+ expect(commands().filter((c) => c === 'pull --rebase --autostash origin main')).toHaveLength(1);
+ });
});