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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: preserve shared-checkout Git recovery state and edits (#13524)
[._.]/ Adam Eivy6c8b6744c04b
diff --git a/server/services/git.ensureLatest.test.js b/server/services/git.ensureLatest.test.jsindex 3b63371972..3fc3fda282 100644--- a/server/services/git.ensureLatest.test.js+++ b/server/services/git.ensureLatest.test.js@@ -53,19 +53,17 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('ensureLatest on a diverged checkout', (expect(r.conflict).toBe(true);expect(r.error).not.toMatch(/rebase-merge directory/);expect(r.error).not.toMatch(/hint:/);- expect(r.error).toMatch(/CONFLICT|could not apply/);+ expect(r.error).toMatch(/CONFLICT|could not apply|already in progress/);}- expect(rebaseDirExists(repo)).toBe(false);+ expect(rebaseDirExists(repo)).toBe(true);});- it('drops local commits that only touch PortOS-owned .quality.json and lands on origin', async () => {+ it('preserves conflicting PortOS-owned commits for explicit recovery', async () => {const repo = await diverge('.quality.json');- const r = await ensureLatest(repo);- expect(r).toMatchObject({ success: true, conflict: false });- expect(r.droppedLocalCommits).toHaveLength(1);- const head = (await execGit(['rev-parse', 'HEAD'], repo)).stdout.trim();- const upstream = (await execGit(['rev-parse', 'origin/main'], repo)).stdout.trim();- expect(head).toBe(upstream);+ const before = (await execGit(['rev-parse', 'HEAD'], repo)).stdout.trim();+ expect(await ensureLatest(repo)).toMatchObject({ success: false, conflict: true, error: expect.stringContaining('preserved') });+ expect((await execGit(['rev-parse', 'refs/heads/main'], repo)).stdout.trim()).toBe(before);+ expect(rebaseDirExists(repo)).toBe(true);});it('keeps local commits that touch anything besides PortOS-owned files', async () => {@@ -74,7 +72,7 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('ensureLatest on a diverged checkout', (const before = (await execGit(['rev-parse', 'HEAD'], repo)).stdout.trim();const r = await ensureLatest(repo);expect(r.conflict).toBe(true);- expect((await execGit(['rev-parse', 'HEAD'], repo)).stdout.trim()).toBe(before);+ expect((await execGit(['rev-parse', 'refs/heads/main'], repo)).stdout.trim()).toBe(before);});it('leaves someone else\'s in-progress rebase alone', async () => {diff --git a/server/services/git.js b/server/services/git.jsindex 298b197750..d7b76f39a7 100644--- a/server/services/git.js+++ b/server/services/git.js@@ -1015,8 +1015,8 @@ async function updatePinnedSubmodules(dir) {* refuse outright with DIRTY_WORKTREE.* 4. Reconcile submodules again after the parent pull, because a new commit* can advance a gitlink while leaving its worktree at the old commit.- * 5. On conflict, abort any in-progress rebase and report `conflict: true`- * rather than throwing, so the caller can hand the mess to a CoS agent.+ * 5. On conflict, preserve the operation and report `conflict: true`+ * so an agent or operator can inspect it and explicitly recover.** A zero exit status is NOT enough to call the rebase clean. `--autostash`* re-applies the stash after the rebase finishes, and git only WARNS when that@@ -1024,8 +1024,7 @@ async function updatePinnedSubmodules(dir) {* exits 0 with conflict markers in the working tree. So a successful rebase is* confirmed by asking git for unmerged paths, not by its exit code; otherwise* the caller would build and restart on a broken tree. There is no rebase to- * abort in that state (it already completed), which is why the abort below sits- * on the non-zero path only.+ * abort in that state (it already completed).** @param {string} dir* @returns {Promise<{success: boolean, branch: string, output: string, conflict: boolean, rebased?: boolean, error?: string}>}@@ -1034,7 +1033,14 @@ export async function updateDefaultBranch(dir) {return withCheckoutMutation(dir, () => updateDefaultBranchAdmitted(dir));}+// Process-local lanes cannot exclude CLI actors or their conflict-resolution+// edits, even within a rebase this request started. Git has no conditional abort.+const SHARED_REBASE_RECOVERY = 'Git operation state and any autostash were preserved. Inspect git status and save any conflict-resolution edits before explicitly continuing or aborting the operation.';+async function updateDefaultBranchAdmitted(dir) {+ if (await rebaseInProgress(dir)) {+ return { success: false, branch: await getBranch(dir), output: '', conflict: true, error: `A rebase is already in progress. ${SHARED_REBASE_RECOVERY}` };+ }// Git splits a failed pull across both streams — fetch progress and rebase// instructions on stderr, the `CONFLICT (content): …` lines naming the files// on stdout — so an `stderr || stdout` pick would drop exactly the part that@@ -1104,6 +1110,9 @@ async function updateDefaultBranchAdmitted(dir) {const fastForward = await execGit(['pull', '--ff-only', 'origin', branch], dir, { ignoreExitCode: true });output += fastForward.stdout + fastForward.stderr;+ if (await rebaseInProgress(dir) || fastForward.terminated) {+ return { success: false, branch, output, conflict: true, error: `${bothStreams(fastForward, 'Pull did not complete.')} ${SHARED_REBASE_RECOVERY}` };+ }if (fastForward.exitCode === 0) {const submoduleError = await reconcileSubmodules();if (submoduleError) return submoduleError;@@ -1123,10 +1132,11 @@ async function updateDefaultBranchAdmitted(dir) {const rebase = await execGit(['pull', '--rebase', '--autostash', 'origin', branch], dir, { ignoreExitCode: true });output += rebase.stdout + rebase.stderr;- if (rebase.exitCode === 0) {+ const activeRebase = await rebaseInProgress(dir);+ if (rebase.exitCode === 0 && !rebase.terminated && !activeRebase) {const unmerged = await execGit(['diff', '--name-only', '--diff-filter=U'], dir, { ignoreExitCode: true });const conflicted = unmerged.stdout.trim().split('\n').filter(Boolean);- if (!conflicted.length) {+ if (unmerged.exitCode === 0 && !unmerged.terminated && !conflicted.length) {const submoduleError = await reconcileSubmodules();if (submoduleError) return submoduleError;return { success: true, branch, output, conflict: false, rebased: true };@@ -1136,31 +1146,22 @@ async function updateDefaultBranchAdmitted(dir) {branch,output,conflict: true,- error: `re-applying the autostashed local changes conflicted in: ${conflicted.join(', ')}`+ error: conflicted.length+ ? `re-applying the autostashed local changes conflicted in: ${conflicted.join(', ')}`+ : bothStreams(unmerged, 'Could not verify local changes after rebasing.')};}- 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.`- };- }+ const rebaseLock = Number.isInteger(rebase.exitCode) && !rebase.terminated && !activeRebase+ && clearStaleGitLock(rebase.stderr);return {success: false,branch,output,conflict: true,- error: bothStreams(rebase, `rebase onto origin/${branch} failed`)+ error: rebaseLock+ ? `Cleared an abandoned git lock (${rebaseLock}). The rebase did not complete; inspect the checkout before retrying. ${SHARED_REBASE_RECOVERY}`+ : `${bothStreams(rebase, `rebase onto origin/${branch} did not complete`)} ${SHARED_REBASE_RECOVERY}`};}@@ -1208,12 +1209,8 @@ async function rebaseAndPushDefaultBranchAdmitted(dir) {// Fetch + rebase is the explicit-origin equivalent of pull --rebase. Avoid// pull.ff / upstream configuration and never move dirty work via autostash.const rebased = await execGit(['rebase', '--no-autostash', remoteRef], dir, { ignoreExitCode: true });- if (rebased.exitCode !== 0) {- const aborted = Number.isInteger(rebased.exitCode) && !rebased.terminated && 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.')}` : '';- return refused(`${gitResultError(rebased, 'Rebase failed; nothing was pushed.')}${recovery}`);+ if (rebased.exitCode !== 0 || rebased.terminated || await rebaseInProgress(dir)) {+ return refused(`${gitResultError(rebased, 'Rebase did not complete.')} ${SHARED_REBASE_RECOVERY} Nothing was pushed.`);}if (await getBranch(dir) !== branch) return refused('The checked-out branch changed; nothing was pushed.');const verifiedHead = (await execGit(['rev-parse', '--verify', `refs/heads/${branch}^{commit}`], dir)).stdout.trim();@@ -1302,9 +1299,8 @@ export function hasChangelogDir(dir) {*/// One pre-task pull per checkout at a time. Several agents for the same app-// prep concurrently; without this the second one's `rebase` hits the first's-// `.git/rebase-merge` and its failure-path `rebase --abort` then tears down the-// FIRST agent's in-flight rebase.+// prep concurrently; serialize them so a later request sees any stopped+// operation at preflight instead of launching Git on top of it.const ensureLatestTails = new Map();export async function ensureLatest(dir) {@@ -1329,16 +1325,6 @@ function ensureLatestAdmitted(dir) {return run;}-// Files PortOS itself owns in a managed app's checkout. The quality publisher-// lands them through a PR, so origin is authoritative; a local commit that only-// touches them is a stale leftover (an older publisher committed on the live-// checkout) and is safe to drop when it blocks the pull. Imported lazily: only-// a conflicting pull needs it, and git.js is reached by hundreds of suites.-async function portosOwnedCheckoutFiles() {- const { APP_QUALITY_SNAPSHOT_FILENAME, APP_QUALITY_LEGACY_SNAPSHOT_FILENAME } = await import('./appQualitySnapshotFormat.js');- return new Set([APP_QUALITY_SNAPSHOT_FILENAME, APP_QUALITY_LEGACY_SNAPSHOT_FILENAME]);-}-async function rebaseInProgress(dir) {for (const name of ['rebase-merge', 'rebase-apply']) {const res = await execGit(['rev-parse', '--git-path', name], dir, { ignoreExitCode: true });@@ -1348,23 +1334,6 @@ async function rebaseInProgress(dir) {return false;}-// When the only thing the local branch adds over origin is PortOS-owned files,-// move the branch to origin (`reset --keep` refuses rather than clobbering-// anything uncommitted). Returns the dropped commit subjects, or null when the-// local side carries anything else.-async function dropPortosOwnedLocalCommits(dir, branch) {- const upstream = `origin/${branch}`;- const changed = await execGit(['diff', '--name-only', `${upstream}...HEAD`], dir, { ignoreExitCode: true });- if (changed.exitCode !== 0) return null;- const files = changed.stdout.split('\n').map(f => f.trim()).filter(Boolean);- const owned = await portosOwnedCheckoutFiles();- if (!files.length || !files.every(f => owned.has(f))) return null;- const log = await execGit(['log', '--format=%h %s', `${upstream}..HEAD`], dir, { ignoreExitCode: true });- const reset = await execGit(['reset', '--keep', upstream], dir, { ignoreExitCode: true });- if (reset.exitCode !== 0) return null;- return log.stdout.split('\n').map(l => l.trim()).filter(Boolean);-}-// git's rebase failure output is a multi-line block of `hint:` advice with a// `\r`-overwritten progress line glued in front — the part worth logging is// the error plus the CONFLICT lines naming the files.@@ -1427,7 +1396,10 @@ async function ensureLatestUnserialized(dir) {// Try fast-forward merge first (safest — no rewrite)const mergeResult = await execGit(['merge', '--ff-only', `origin/${currentBranch}`], dir, { ignoreExitCode: true });- const mergeOk = !mergeResult.stderr?.includes('fatal') && !mergeResult.stderr?.includes('Not possible to fast-forward');+ if (await rebaseInProgress(dir) || mergeResult.terminated) {+ return { success: false, branch: currentBranch, conflict: true, error: `${summarizeRebaseConflict(mergeResult)} ${SHARED_REBASE_RECOVERY}` };+ }+ const mergeOk = mergeResult.exitCode === 0;if (mergeOk) {return { success: true, branch: currentBranch, conflict: false, error: null };@@ -1448,37 +1420,17 @@ async function ensureLatestUnserialized(dir) {// Fast-forward failed — local branch has diverged. Try rebase.const rebaseResult = await execGit(['rebase', `origin/${currentBranch}`], dir, { ignoreExitCode: true });- // `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) {- // 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.`- };- }- const dropped = await dropPortosOwnedLocalCommits(dir, currentBranch);- if (dropped) {- console.warn(`⚠️ Dropped ${dropped.length} stale local PortOS-owned commit(s) on ${currentBranch} in ${dir} to match origin: ${dropped.join('; ')}`);- return { success: true, branch: currentBranch, conflict: false, error: null, droppedLocalCommits: dropped };- }+ const activeRebase = await rebaseInProgress(dir);+ if (rebaseResult.exitCode !== 0 || rebaseResult.terminated || activeRebase) {+ const rebaseLock = Number.isInteger(rebaseResult.exitCode) && !rebaseResult.terminated && !activeRebase+ && clearStaleGitLock(rebaseResult.stderr);return {success: false,branch: currentBranch,conflict: true,- error: `branch ${currentBranch} has diverged from origin and rebase has conflicts: ${summarizeRebaseConflict(rebaseResult)}`+ error: rebaseLock+ ? `Cleared an abandoned git lock (${rebaseLock}). The rebase did not complete; inspect the checkout before retrying. ${SHARED_REBASE_RECOVERY}`+ : `branch ${currentBranch} has diverged from origin and rebase did not complete: ${summarizeRebaseConflict(rebaseResult)} ${SHARED_REBASE_RECOVERY}`};}diff --git a/server/services/git.rebasePush.test.js b/server/services/git.rebasePush.test.jsindex 1352340fde..ad2093eb1d 100644--- a/server/services/git.rebasePush.test.js+++ b/server/services/git.rebasePush.test.js@@ -6,7 +6,7 @@ import { execGit } from '../lib/execGit.js';import { makeGitSandbox, destroyGitSandbox, SKIP_HEAVY_INTEGRATION } from '../lib/gitTestRepo.js';import { getGitInfo, rebaseAndPushDefaultBranch } from './git.js';-// Real Git pins preservation, rebase conflict cleanup and the exact push target.+// Real Git pins preservation, rebase conflict recovery and the exact push target.describe.skipIf(SKIP_HEAVY_INTEGRATION)('rebase and push the default branch', () => {let sandbox;afterEach(async () => {@@ -71,16 +71,16 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('rebase and push the default branch', ()expect(await rebaseAndPushDefaultBranch(repo)).toMatchObject({ success: false, error: expect.stringContaining('no local commits') });});- it('aborts its conflicting rebase, preserving local and remote heads', async () => {+ it('preserves its conflicting rebase and original branch for explicit recovery', async () => {const repo = await prepare({ conflict: true });const [local, remote] = await Promise.all([head(repo), head(sandbox.origin)]);const result = await rebaseAndPushDefaultBranch(repo);expect(result).toMatchObject({ success: false, pushed: false });expect(result.error).toMatch(/CONFLICT|could not apply/);- expect(await head(repo)).toBe(local);+ expect((await execGit(['rev-parse', 'refs/heads/main'], repo)).stdout.trim()).toBe(local);expect(await head(sandbox.origin)).toBe(remote);- expect(existsSync(join(repo, '.git', 'rebase-merge'))).toBe(false);- expect((await execGit(['status', '--porcelain'], repo)).stdout).toBe('');+ expect(existsSync(join(repo, '.git', 'rebase-merge'))).toBe(true);+ expect((await execGit(['status', '--porcelain'], repo)).stdout).toContain('UU initial.txt');});it('refuses a local merge containing work recorded only in the merge commit', async () => {diff --git a/server/services/git.sharedRecovery.test.js b/server/services/git.sharedRecovery.test.jsnew file mode 100644index 0000000000..fadd925bc3--- /dev/null+++ b/server/services/git.sharedRecovery.test.js@@ -0,0 +1,163 @@+import { afterEach, describe, expect, it as vitestIt, vi } from 'vitest';+import { readFile, readdir, writeFile } from 'fs/promises';+import { join } from 'path';++const observation = vi.hoisted(() => ({ commands: [], target: null, before: null, after: null, override: null }));+vi.mock('../lib/execGit.js', async importOriginal => {+ const actual = await importOriginal();+ return {+ ...actual,+ execGit: async (...args) => {+ observation.commands.push(args[0]);+ const target = observation.target?.(args[0]);+ if (target) await observation.before?.();+ const result = await actual.execGit(...args);+ if (target) {+ await observation.after?.(result);+ return observation.override ?? result;+ }+ return result;+ }+ };+});+import { execGit } from '../lib/execGit.js';+import { makeGitSandbox, destroyGitSandbox, SKIP_HEAVY_INTEGRATION } from '../lib/gitTestRepo.js';+import { ownTestBodies } from '../lib/mockPathsDataRoot.js';+import { ensureLatest, rebaseAndPushDefaultBranch, updateDefaultBranch } from './git.js';++const workflows = [+ { name: 'Update App', run: updateDefaultBranch, target: args => args[0] === 'pull' && args.includes('--rebase') },+ { name: 'Rebase and Push', run: rebaseAndPushDefaultBranch, target: args => args[0] === 'rebase' && args.includes('--no-autostash') },+ { name: 'pre-task update', run: ensureLatest, target: args => args[0] === 'rebase' && args[1] === 'origin/main' },+];++// The adapter pauses only at process boundaries; all operation state and edits+// come from real Git children outside the service's process-local mutation lane.+describe.skipIf(SKIP_HEAVY_INTEGRATION)('shared-checkout recovery', () => {+ const owned = ownTestBodies(vitestIt);+ const it = owned.it;+ let sandbox;+ afterEach(async () => {+ try {+ await owned.drain();+ } finally {+ Object.assign(observation, { commands: [], target: null, before: null, after: null, override: null });+ await destroyGitSandbox(sandbox?.scratch);+ sandbox = null;+ }+ });+ const head = async (dir, ref = 'HEAD') => (await execGit(['rev-parse', ref], dir)).stdout.trim();+ const commitFile = async (dir, file, contents) => {+ await writeFile(join(dir, file), contents);+ await execGit(['add', file], dir);+ await execGit(['commit', '-m', `Update ${file}`], dir);+ };+ const prepare = async ({ conflict = true } = {}) => {+ sandbox = await makeGitSandbox({ origin: true });+ const { repo, origin, scratch } = sandbox;+ const other = join(scratch, 'other');+ await execGit(['clone', origin, other], scratch);+ await execGit(['config', 'user.email', '[email protected]'], other);+ await execGit(['config', 'user.name', 'Example Agent'], other);+ await execGit(['config', 'commit.gpgsign', 'false'], other);+ await commitFile(other, conflict ? 'initial.txt' : 'remote.txt', 'remote change\n');+ await execGit(['push', 'origin', 'main'], other);+ await commitFile(repo, conflict ? 'initial.txt' : 'local.txt', 'local change\n');+ observation.commands = [];+ return repo;+ };+ const operationBytes = async repo => {+ const dir = join(repo, '.git', 'rebase-merge');+ const names = (await readdir(dir)).sort();+ return Promise.all(names.map(async name => [name, await readFile(join(dir, name))]));+ };+ const expectNoRecoveryOrPush = () => {+ expect(observation.commands).not.toContainEqual(['rebase', '--abort']);+ expect(observation.commands.some(args => ['reset', 'push', 'stash'].includes(args[0]))).toBe(false);+ };++ for (const workflow of workflows) {+ for (const boundary of ['before command', 'replacement after failure', 'resolution after failure']) {+ it(`${workflow.name} preserves external state and resolution bytes at ${boundary}`, async () => {+ const repo = await prepare();+ const [local, remote] = await Promise.all([head(repo), head(sandbox.origin)]);+ const { execGit: externalGit } = await vi.importActual('../lib/execGit.js');+ const resolution = Buffer.from('unfinished resolution\r\nno final newline');+ let operation;+ let index;+ const interfere = async () => {+ if (boundary === 'replacement after failure') await externalGit(['rebase', '--abort'], repo);+ if (boundary !== 'resolution after failure') {+ await externalGit(['fetch', 'origin'], repo);+ const result = await externalGit(['rebase', 'origin/main'], repo, { ignoreExitCode: true });+ expect(result.exitCode).not.toBe(0);+ }+ // After settlement, retain both staged resolution and newer unsaved work.+ if (boundary !== 'before command') {+ await writeFile(join(repo, 'initial.txt'), 'staged resolution\n');+ await externalGit(['add', 'initial.txt'], repo);+ }+ await writeFile(join(repo, 'initial.txt'), resolution);+ operation = await operationBytes(repo);+ index = await readFile(join(repo, '.git', 'index'));+ };+ observation.target = workflow.target;+ if (boundary === 'before command') observation.before = interfere;+ else observation.after = async result => {+ expect(result.exitCode).not.toBe(0);+ await interfere();+ };+ const result = await workflow.run(repo);+ expect(result).toMatchObject({ success: false, error: expect.stringContaining('preserved') });+ if (workflow.run === rebaseAndPushDefaultBranch) expect(result.pushed).toBe(false);+ expect(await readFile(join(repo, 'initial.txt'))).toEqual(resolution);+ expect(await operationBytes(repo)).toEqual(operation);+ expect(await readFile(join(repo, '.git', 'index'))).toEqual(index);+ expect(await head(repo, 'refs/heads/main')).toBe(local);+ expect(await head(sandbox.origin)).toBe(remote);+ expectNoRecoveryOrPush();+ });+ }++ it(`${workflow.name} preserves stopped state on a terminated process result`, async () => {+ const repo = await prepare();+ const remote = await head(sandbox.origin);+ let operation;+ observation.target = workflow.target;+ observation.after = async result => {+ expect(result.exitCode).not.toBe(0);+ operation = await operationBytes(repo);+ };+ // Runner termination can have empty streams; stderr keywords do not+ // establish successful completion or permission to mutate recovery state.+ observation.override = { exitCode: null, terminated: true, signal: 'SIGTERM', stdout: '', stderr: '' };+ expect(await workflow.run(repo)).toMatchObject({ success: false, error: expect.stringContaining('preserved') });+ expect(await operationBytes(repo)).toEqual(operation);+ expect(await head(sandbox.origin)).toBe(remote);+ expectNoRecoveryOrPush();+ });++ it(`${workflow.name} still reconciles nonconflicting divergence`, async () => {+ const repo = await prepare({ conflict: false });+ expect(await workflow.run(repo)).toMatchObject({ success: true });+ expect(await readFile(join(repo, 'local.txt'), 'utf8')).toBe('local change\n');+ expect(await readFile(join(repo, 'remote.txt'), 'utf8')).toBe('remote change\n');+ });+ }++ it('Update App retains the autostash and supports explicit abort after a conflict', async () => {+ const repo = await prepare();+ const local = await head(repo);+ const dirty = Buffer.from('tracked dirty bytes\r\nwithout final newline');+ await writeFile(join(repo, 'dirty.txt'), dirty);+ await execGit(['add', 'dirty.txt'], repo);+ expect(await updateDefaultBranch(repo)).toMatchObject({ success: false, conflict: 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(dirty);+ expectNoRecoveryOrPush();+ const { execGit: externalGit } = await vi.importActual('../lib/execGit.js');+ await externalGit(['rebase', '--abort'], repo);+ expect(await head(repo)).toBe(local);+ expect(await readFile(join(repo, 'dirty.txt'))).toEqual(dirty);+ });+});diff --git a/server/services/git.staleLock.test.js b/server/services/git.staleLock.test.jsindex 896dea5813..b3fa2a1cc4 100644--- a/server/services/git.staleLock.test.js+++ b/server/services/git.staleLock.test.js@@ -202,7 +202,7 @@ describe('ensureLatest', () => {expect(commands()).not.toContain('rebase origin/main');});- it('clears an abandoned rebase lock, aborts the rebase, and does not retry', async () => {+ it('clears an abandoned rebase lock without aborting or retrying', 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")@@ -215,7 +215,7 @@ describe('ensureLatest', () => {expect(result).toMatchObject({ success: false, branch: 'main', conflict: true });expect(result.error).toContain('/repo/.git/index.lock');- expect(commands()).toContain('rebase --abort');+ expect(commands()).not.toContain('rebase --abort');});it('reports a genuine rebase conflict unchanged when there is no lock', async () => {@@ -227,7 +227,7 @@ describe('ensureLatest', () => {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');+ expect(result.error).toContain('diverged from origin and rebase did not complete');+ expect(commands()).not.toContain('rebase --abort');});});diff --git a/server/services/git.updateDefaultBranch.test.js b/server/services/git.updateDefaultBranch.test.jsindex 1d109f80db..68c5e0c27a 100644--- a/server/services/git.updateDefaultBranch.test.js+++ b/server/services/git.updateDefaultBranch.test.js@@ -59,7 +59,7 @@ describe('updateDefaultBranch', () => {'checkout main','pull --ff-only origin main']));- expect(commands().some(command => command.includes('rebase'))).toBe(false);+ expect(commands().some(command => command.startsWith('rebase ') || command.startsWith('pull --rebase'))).toBe(false);});it('repairs pinned submodules before and after pulling the parent repository', async () => {@@ -104,7 +104,7 @@ describe('updateDefaultBranch', () => {expect(commands()).not.toContain('rebase --abort');});- it('reports a conflict and aborts the rebase when --autostash cannot reconcile', async () => {+ it('reports a conflict and preserves the rebase when --autostash cannot reconcile', async () => {withGit({'pull --ff-only origin main': fail('fatal: Not possible to fast-forward, aborting.'),// Git splits a failed pull across both streams: fetch progress on stderr,@@ -123,7 +123,7 @@ describe('updateDefaultBranch', () => {// actionable content of the CoS task the caller queues from this.expect(result.error).toContain('CONFLICT (content): Merge conflict in server/index.js');expect(result.error).toContain('could not apply 1a2b3c4');- expect(commands()).toContain('rebase --abort');+ expect(commands()).not.toContain('rebase --abort');});it('reports a conflict when the autostash re-apply collides, which git exits 0 on', async () => {@@ -222,7 +222,7 @@ describe('updateDefaultBranch', () => {expect(commands()).not.toContain('pull --rebase --autostash origin main');});- it('clears an abandoned rebase lock, aborts the rebase, and does not retry', async () => {+ it('clears an abandoned rebase lock without aborting or retrying', 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")@@ -235,7 +235,7 @@ describe('updateDefaultBranch', () => {expect(result).toMatchObject({ success: false, branch: 'main', conflict: true });expect(result.error).toContain('/repo/.git/index.lock');- expect(commands()).toContain('rebase --abort');+ expect(commands()).not.toContain('rebase --abort');expect(commands().filter((c) => c === 'pull --rebase --autostash origin main')).toHaveLength(1);});});