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(git): preserve stopped Sync operations and resolution edits (#13418)

Adam Eivy9065fbf52bbc
diff --git a/server/services/git.js b/server/services/git.js
index 32e1298188..298b197750 100644
--- a/server/services/git.js
+++ b/server/services/git.js
@@ -1233,27 +1233,35 @@ async function syncBranchAdmitted(dir, branch = null) {
if (branch) assertSafeRef(branch);
const refused = error => ({ success: false, pulled: false, pushed: false, error });
const gitDir = (await execGit(['rev-parse', '--absolute-git-dir'], dir)).stdout.trim();
- if ([...SEQUENCER_STATE.map(([marker]) => marker), 'MERGE_HEAD', 'sequencer']
- .some(marker => existsSync(join(gitDir, marker)))) {
+ const operationInProgress = () => [...SEQUENCER_STATE.map(([marker]) => marker), 'MERGE_HEAD', 'sequencer']
+ .some(marker => existsSync(join(gitDir, marker)));
+ if (operationInProgress()) {
return refused('Finish the Git operation already in progress before syncing.');
}
const currentBranch = branch || await getBranch(dir);
const pullResult = await execGit(['pull', '--rebase', '--autostash', 'origin', currentBranch], dir, { ignoreExitCode: true });
if (pullResult.exitCode !== 0 || pullResult.terminated) {
- // Only a settled command can own recovery. An interrupted Git process may
- // still have hooks/helpers running; leave its state for explicit recovery.
+ // The API lane does not exclude Git CLI actors. Even a request-specific
+ // reflog proves only who started a rebase, not who now owns its edits. Git
+ // has no generation-conditioned abort, so a check followed by --abort can
+ // still discard another actor's work. Preserve shared-checkout recovery.
const settled = Number.isInteger(pullResult.exitCode) && !pullResult.terminated;
- const clearedLock = settled && clearStaleGitLock(pullResult.stderr);
- const aborted = settled && await rebaseInProgress(dir)
- ? await execGit(['rebase', '--abort'], dir, { ignoreExitCode: true }) : null;
- const recovery = aborted && aborted.exitCode !== 0
- ? ` Rebase abort failed: ${gitResultError(aborted, 'Inspect the checkout before retrying.')}` : '';
+ const activeOperation = operationInProgress();
+ const clearedLock = settled && !activeOperation && clearStaleGitLock(pullResult.stderr);
+ const recovery = activeOperation
+ ? ' Git operation state and any autostash were preserved. Inspect git status and save any conflict-resolution edits before explicitly continuing or aborting the operation; nothing was pushed.' : '';
const error = clearedLock
? `Cleared an abandoned git lock (${clearedLock}) left by a killed git process. The pull did not complete — inspect the checkout before retrying the sync.`
: gitResultError(pullResult, 'Pull failed; nothing was pushed.');
return refused(`${error}${recovery}`);
}
+ // A separate actor can start an operation during pull, including one with
+ // staged resolutions that lets pull exit zero. It still must not be pushed.
+ if (operationInProgress()) {
+ return refused('A Git operation is in progress after pulling. Its state and edits were preserved; inspect git status and finish that operation before syncing again. Nothing was pushed.');
+ }
+
// Autostash reapplication can conflict after Git has exited successfully.
// Preserve the conflicted files and Git's saved stash rather than aborting
// an already-completed rebase or attempting to apply/drop the stash again.
diff --git a/server/services/git.syncBranch.test.js b/server/services/git.syncBranch.test.js
index 16e79abc29..e2cf1109a5 100644
--- a/server/services/git.syncBranch.test.js
+++ b/server/services/git.syncBranch.test.js
@@ -3,14 +3,14 @@ import { mkdir, readFile, writeFile } from 'fs/promises';
import { existsSync } from 'fs';
import { join } from 'path';
-const observation = vi.hoisted(() => ({ commands: [], afterPull: null, pullOverride: null, abortOverride: null, pullExitCode: null }));
+const observation = vi.hoisted(() => ({ commands: [], beforePull: null, afterPull: null, pullOverride: null, pullExitCode: null }));
vi.mock('../lib/execGit.js', async importOriginal => {
const actual = await importOriginal();
return {
...actual,
execGit: async (...args) => {
observation.commands.push(args[0]);
- if (args[0].join(' ') === 'rebase --abort' && observation.abortOverride) return observation.abortOverride;
+ if (args[0][0] === 'pull') await observation.beforePull?.();
const result = await actual.execGit(...args);
if (args[0][0] === 'pull') {
observation.pullExitCode = result.exitCode;
@@ -29,9 +29,9 @@ import { checkout, syncBranch } from './git.js';
describe.skipIf(SKIP_HEAVY_INTEGRATION)('branch Sync', () => {
let sandbox;
afterEach(async () => {
+ observation.beforePull = null;
observation.afterPull = null;
observation.pullOverride = null;
- observation.abortOverride = null;
observation.pullExitCode = null;
observation.commands = [];
await destroyGitSandbox(sandbox?.scratch);
@@ -84,14 +84,19 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('branch Sync', () => {
expect(await syncBranch(repo, 'main')).toMatchObject({ success: true });
});
- it('aborts its own conflicting rebase and restores autostashed work without pushing', async () => {
+ it('preserves a conflicting rebase and its autostash for explicit recovery without pushing', async () => {
const repo = await prepare({ conflict: true });
await writeFile(join(repo, 'dirty.txt'), 'tracked work\n');
await execGit(['add', 'dirty.txt'], repo);
const [local, remote] = await Promise.all([head(repo), head(sandbox.origin)]);
observation.commands = [];
expect(await syncBranch(repo, 'main')).toMatchObject({ success: false, pulled: false, pushed: false, error: expect.stringMatching(/CONFLICT|could not apply/) });
- expect(observation.commands).toContainEqual(['rebase', '--abort']);
+ expect(observation.commands).not.toContainEqual(['rebase', '--abort']);
+ expect(existsSync(join(repo, '.git', 'rebase-merge'))).toBe(true);
+ const stash = (await readFile(join(repo, '.git', 'rebase-merge', 'autostash'), 'utf8')).trim();
+ expect((await execGit(['show', `${stash}:dirty.txt`], repo, { bufferOutput: true })).stdout).toEqual(Buffer.from('tracked work\n'));
+ // Explicit recovery still restores the original head and stashed bytes.
+ await execGit(['rebase', '--abort'], repo);
expect(observation.commands.some(args => args[0] === 'push')).toBe(false);
expect(await head(repo)).toBe(local);
expect(await head(sandbox.origin)).toBe(remote);
@@ -113,19 +118,69 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('branch Sync', () => {
expect(await head(sandbox.origin)).toBe(remote);
});
- it.each([
- { name: 'an interrupted pull', pullOverride: { exitCode: null, signal: 'SIGTERM', terminated: true, stdout: '', stderr: '' }, abortOverride: null, aborts: false, error: /Pull failed/ },
- { name: 'a failed abort', pullOverride: null, abortOverride: { exitCode: 1, stdout: '', stderr: 'error: abort failed' }, aborts: true, error: /Rebase abort failed: error: abort failed/ }
- ])('preserves recovery state after $name', async ({ pullOverride, abortOverride, aborts, error }) => {
+ it('preserves recovery state after an interrupted pull', async () => {
const repo = await prepare({ conflict: true });
const remote = await head(sandbox.origin);
- observation.pullOverride = pullOverride;
- observation.abortOverride = abortOverride;
+ observation.pullOverride = { exitCode: null, signal: 'SIGTERM', terminated: true, stdout: '', stderr: '' };
observation.commands = [];
- expect(await syncBranch(repo, 'main')).toMatchObject({ success: false, pushed: false, error: expect.stringMatching(error) });
- expect(observation.commands.some(args => args.join(' ') === 'rebase --abort')).toBe(aborts);
- expect(observation.commands.some(args => args[0] === 'push')).toBe(false);
+ expect(await syncBranch(repo, 'main')).toMatchObject({ success: false, pushed: false, error: expect.stringMatching(/Pull failed.*preserved/) });
+ expect(observation.commands.some(args => args[0] === 'rebase' || args[0] === 'push')).toBe(false);
+ expect(existsSync(join(repo, '.git', 'rebase-merge'))).toBe(true);
+ expect(await head(sandbox.origin)).toBe(remote);
+ });
+
+ it.each(['before pull', 'after failed pull', 'after failed pull with same operation'])(
+ "preserves an external actor's operation and raw resolution bytes %s", async boundary => {
+ const repo = await prepare({ conflict: true });
+ const remote = await head(sandbox.origin);
+ // Bypass the Sync adapter: these are independent real Git invocations.
+ const { execGit: externalGit } = await vi.importActual('../lib/execGit.js');
+ const resolution = Buffer.from('unfinished resolution\r\nno final newline');
+ const interfere = async () => {
+ if (boundary === 'after failed pull') await externalGit(['rebase', '--abort'], repo);
+ if (boundary !== 'after failed pull with same operation') {
+ await externalGit(['fetch', 'origin'], repo);
+ const rebased = await externalGit(['rebase', 'origin/main'], repo, { ignoreExitCode: true });
+ expect(rebased.exitCode).not.toBe(0);
+ }
+ await writeFile(join(repo, 'initial.txt'), resolution);
+ };
+ if (boundary === 'before pull') observation.beforePull = interfere;
+ else observation.afterPull = interfere;
+ observation.commands = [];
+ const result = await syncBranch(repo, 'main');
+ expect(await readFile(join(repo, 'initial.txt'))).toEqual(resolution);
+ expect(result).toMatchObject({
+ success: false, pulled: false, pushed: false, error: expect.stringContaining('preserved')
+ });
+ expect(observation.pullExitCode).not.toBe(0);
+ expect(observation.commands.some(args => args[0] === 'rebase' || args[0] === 'push')).toBe(false);
+ expect(existsSync(join(repo, '.git', 'rebase-merge'))).toBe(true);
+ expect(await head(sandbox.origin)).toBe(remote);
+ }
+ );
+
+ it('refuses to push when pull exits zero during an external rebase with staged resolutions', async () => {
+ const repo = await prepare({ conflict: true });
+ const remote = await head(sandbox.origin);
+ const { execGit: externalGit } = await vi.importActual('../lib/execGit.js');
+ const resolution = Buffer.from('staged external resolution\r\n');
+ observation.beforePull = async () => {
+ await externalGit(['fetch', 'origin'], repo);
+ const rebased = await externalGit(['rebase', 'origin/main'], repo, { ignoreExitCode: true });
+ expect(rebased.exitCode).not.toBe(0);
+ await writeFile(join(repo, 'initial.txt'), resolution);
+ await externalGit(['add', 'initial.txt'], repo);
+ };
+ observation.commands = [];
+ expect(await syncBranch(repo, 'main')).toMatchObject({
+ success: false, pulled: false, pushed: false, error: expect.stringContaining('preserved')
+ });
+ expect(observation.pullExitCode).toBe(0);
+ expect(observation.commands.some(args => args[0] === 'rebase' || args[0] === 'push')).toBe(false);
expect(existsSync(join(repo, '.git', 'rebase-merge'))).toBe(true);
+ expect(await readFile(join(repo, 'initial.txt'))).toEqual(resolution);
+ expect((await externalGit(['show', ':initial.txt'], repo, { bufferOutput: true })).stdout).toEqual(resolution);
expect(await head(sandbox.origin)).toBe(remote);
});