Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(git): commit-push keeps ours when the remote brings back a blob this checkout replaced
garrytanc9b641843be2
diff --git a/docs/architecture/key-files/workspace-push-and-backup.md b/docs/architecture/key-files/workspace-push-and-backup.mdindex f3f5b53524..21e57ff229 100644--- a/docs/architecture/key-files/workspace-push-and-backup.md+++ b/docs/architecture/key-files/workspace-push-and-backup.md@@ -12,5 +12,5 @@ Key files:## Shared-checkout git writer-- `src/core/git/commit-push.ts` + `src/core/git/commit-guard.ts` — writer safety in a shared checkout (#7381). `integrate` replaces the tip 3-way merge when any local commit is patch-equivalent to an upstream one (`rev-list --cherry-mark`): it replays the local commits onto the remote tip in memory (`merge-tree --merge-base` on git 2.40+, a 3-way `read-tree` otherwise), leaving out the equivalent ones and clean merges, so a copy the remote edited never conflicts and one it reverted is never re-applied; the merge message lists what it left out. `commitPaths` refuses a path outside the source roots (`configuredSourceRoots`, git config `gbrain.sourceRoot`, recorded by `sources harden`'s `recordSourceRoot`) and a file another writer staged under a named directory (`commit_prestaged_paths`), and restores the exact index entries (`update-index --index-info`) when git refuses the commit. Every commit gbrain makes carries `GBRAIN_COMMIT_VIA=<lock path>`. `commitPathsLocked` (write-through) never commits without the lock: a busy lock or refused commit notes the file in `brain-writethrough-pending.log` (git dir, O_APPEND lines), which the next locked write-through and `commit-push --pending` commit and `settlePending` prunes. A publish refuses local non-merge commits outside the roots (`commit_outside_source_root`; `--allow-outside-source-root` lifts both refusals, and `sources harden` passes it for its root scaffolding). With git config `gbrain.quarantine` (opt-in) a content conflict publishes the remote's version of each conflicted file plus every other local change, names the local commit under `refs/gbrain/quarantine/<time>-<sha>` and appends it to `brain-quarantine.log` (`readQuarantine` lists entries whose ref still exists); structural conflicts still refuse. `commit-guard.ts` installs the opt-in `prepare-commit-msg` guard (`gbrain git guard`), which admits only commits naming a held commit lock, passes merges and in-progress operations, and honors `GBRAIN_COMMIT_GUARD=off`. The helper's no-gbrain fallback (`renderCommitPushHelper`) marks children with the absolute lock path and releases the commit lock before pushing under `brain-publish.lock`. Tests: `test/git-writer-safety-7381.serial.test.ts`.+- `src/core/git/commit-push.ts` + `src/core/git/commit-guard.ts` — writer safety in a shared checkout (#7381). `integrate` replaces the tip 3-way merge when any local commit is patch-equivalent to an upstream one (`rev-list --cherry-mark`): it replays the local commits onto the remote tip in memory (`merge-tree --merge-base` on git 2.40+, a 3-way `read-tree` otherwise), leaving out the equivalent ones and clean merges, so a copy the remote edited never conflicts and one it reverted is never re-applied; the merge message lists what it left out. `supersededPaths` resolves a content conflict to ours when the remote's blob is one the same path held earlier in ours' history (last 200 commits touching it) and a different blob replaced it there; the push reports them as `superseded_remote_paths`, and `integrate_conflict` lists only the rest (`detail.superseded` names them). `commitPaths` refuses a path outside the source roots (`configuredSourceRoots`, git config `gbrain.sourceRoot`, recorded by `sources harden`'s `recordSourceRoot`) and a file another writer staged under a named directory (`commit_prestaged_paths`), and restores the exact index entries (`update-index --index-info`) when git refuses the commit. Every commit gbrain makes carries `GBRAIN_COMMIT_VIA=<lock path>`. `commitPathsLocked` (write-through) never commits without the lock: a busy lock or refused commit notes the file in `brain-writethrough-pending.log` (git dir, O_APPEND lines), which the next locked write-through and `commit-push --pending` commit and `settlePending` prunes. A publish refuses local non-merge commits outside the roots (`commit_outside_source_root`; `--allow-outside-source-root` lifts both refusals, and `sources harden` passes it for its root scaffolding). With git config `gbrain.quarantine` (opt-in) a content conflict publishes the remote's version of each conflicted file plus every other local change, names the local commit under `refs/gbrain/quarantine/<time>-<sha>` and appends it to `brain-quarantine.log` (`readQuarantine` lists entries whose ref still exists); structural conflicts still refuse. `commit-guard.ts` installs the opt-in `prepare-commit-msg` guard (`gbrain git guard`), which admits only commits naming a held commit lock, passes merges and in-progress operations, and honors `GBRAIN_COMMIT_GUARD=off`. The helper's no-gbrain fallback (`renderCommitPushHelper`) marks children with the absolute lock path and releases the commit lock before pushing under `brain-publish.lock`. Tests: `test/git-writer-safety-7381.serial.test.ts`.- `src/commands/doctor/checks/git-writer.ts` — `checkout_lagging`, `dirty_age`, `commits_outside_source_root`, `quarantined_changes` (#7381, brain category, after `git_convergence`): over the unmanaged source checkouts with an upstream (`sourceRoots` from git-convergence, grouped by toplevel with each source's toplevel-relative root), never fetching, every git call bounded at 5 s. Lagging warns when `HEAD..@{u}` holds a commit over an hour old (fix: `gbrain git commit-push --pull --path <top>`, agent). Dirty age warns on pending write-through files older than 30 minutes (`pendingWriteThroughStillDirty`; fix: `commit-push --pending`, agent) and on files staged that long (ask_user: unstage or commit by name). Outside-root warns on unpushed non-merge commits that change files outside the DB source roots plus `gbrain.sourceRoot` (`localCommitsOutsideRoots`; ask_user fix with `--allow-outside-source-root`), and says when the checkout has no root recorded. Test: `test/doctor-git-writer-7381.test.ts`.diff --git a/docs/guides/shared-checkout-git.md b/docs/guides/shared-checkout-git.mdindex 55674ebf8e..85435170e7 100644--- a/docs/guides/shared-checkout-git.md+++ b/docs/guides/shared-checkout-git.md@@ -237,6 +237,20 @@ remote commits (in its `detail`), and a question to relay to the user. Until itis resolved, every later commit-push from this checkout hits the sameconflict, even for other files, because the unpushed commit is still waiting.+One kind of conflict settles itself on push. When the remote's version of a+file is one this checkout already had at that path and later replaced with+another version (a stale clone or writer pushed an old copy back, often inside+a merge), gbrain keeps this machine's version: the remote's copy is history+this checkout already moved past. It looks at the last 200 commits that+changed the file. The push lists those files in `superseded_remote_paths`+(`--json`) and a `[gbrain notice]` line, and the merge commit message names+them. A version this checkout never had, a file the remote deleted, and a file+you name with `--resolve` stay ordinary conflicts. When both kinds meet in one+push, the error lists only the real conflicts (its `detail.superseded` names+the others), and the `--resolve` run keeps this machine's version of the+superseded files. `--pull` still reports them as conflicts; a+`gbrain git commit-push --push-only` settles them.+To resolve:1. Ask the user which version of each file should win, or whether they wantdiff --git a/src/commands/git.ts b/src/commands/git.tsindex 0043f26736..3992bdd1f3 100644--- a/src/commands/git.ts+++ b/src/commands/git.ts@@ -198,6 +198,9 @@ export async function runGit(args: string[]): Promise<number> {if (result.quarantined && !json) {process.stderr.write(`[gbrain notice] quarantine: the remote also changed ${result.quarantined.paths.join(', ')}; its version was published and this machine's version is kept under ${result.quarantined.ref}. gbrain doctor lists it (quarantined_changes).\n`);}+ if (result.superseded_remote_paths && !json) {+ process.stderr.write(`[gbrain notice] kept this machine's version of ${result.superseded_remote_paths.join(', ')}: the remote held a version this checkout had already replaced. See docs/guides/shared-checkout-git.md#conflicts.\n`);+ }if (result.outcome === 'pushed_checkout_lagging' && !json) {process.stderr.write(`[gbrain notice] the push landed but this checkout was not advanced: ${result.lagging_reason}. The next commit-push or --pull catches it up.\n`);}diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex ec83bdc3d2..dc99420ba2 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1237,6 +1237,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.433.0', text: 'Hermes transcript import keeps the answers a user gave in a `clarify` form (answered responses of a submitted form, or the answers a timed-out form had already locked) as user turns, each after its question as the assistant\'s turn. A Hermes session imported before re-renders on its next import scan when it holds such answers, which can run fact extraction for that page again (#7396).' },{ since: '0.60.433.0', text: 'Fact subject inference links more facts and fewer wrong ones: a currency code next to an amount (`CHF 80`) and a record label opening a sentence (`Invoice ...`, `Work session ...`) no longer block a fact that names one person or company, and an entity introduced only as an example (`including X notes`, `for example, X`) is never chosen as the subject. A page named like the code or label still competes. A sentence that opens with `For example, X ...` no longer takes X as its subject (#7405).' },{ since: '0.60.433.0', text: '`gbrain think` gives reasoning models from gpt-5 on 16,000 output tokens behind any provider or router prefix, as it already did for gpt-5 and the o-series on their own provider; gpt-6 ids get it too. Before, those got 4,000 and long answers came back truncated (`LLM_OUTPUT_TRUNCATED`). Providers bill the tokens used, not the cap (#7421).' },+ // GBRA-133 G2 (superseded remote blobs). `since` is stamped at the merge slot.+ { since: 'TBD', text: '`gbrain git commit-push` now keeps this machine\'s version of a file the remote changed back to a version this checkout already had at that path and later replaced (a stale clone or writer pushing an old copy, often inside a merge), instead of stopping with `integrate_conflict`. It reads the last 200 commits that changed the file. The push lists those files in `superseded_remote_paths` and the merge message names them. A version this checkout never had, a remote deletion and a file named with `--resolve` still conflict; when both kinds meet, `integrate_conflict` lists only the real conflicts and `detail.superseded` names the others.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/git/commit-push.ts b/src/core/git/commit-push.tsindex 9cae295052..cedecf11b0 100644--- a/src/core/git/commit-push.ts+++ b/src/core/git/commit-push.ts@@ -74,6 +74,8 @@ export interface CommitPushResult {lagging_reason?: string;/** Opt-in quarantine (git config gbrain.quarantine): the local versions of conflicting files, parked under a ref; the remote's version was published. */quarantined?: QuarantineEntry;+ /** Conflicted files where the remote held a version this checkout had already replaced: this checkout's version was published. */+ superseded_remote_paths?: string[];}export interface PullResult {@@ -717,6 +719,30 @@ function blobConflict(root: string, base: string, ours: string, theirs: string,return true;}+const MAX_SUPERSEDED_HISTORY = 200;++/**+ * Content conflicts where the remote's blob is one this checkout held at the same path and then replaced with+ * another blob (a stale clone or writer brought an old copy back): the remote's version is history this side+ * already moved past, so these resolve to ours. Reads the last MAX_SUPERSEDED_HISTORY commits of `ours` that touch+ * the path. A blob ours never held there, a remote deletion, a structural conflict and a path the caller resolves+ * explicitly stay conflicts.+ */+function supersededPaths(root: string, ours: string, theirs: string, merged: MergeTree, explicit?: Map<string, Resolution>): string[] {+ const base = git(root, ['merge-base', ours, theirs]).stdout.trim();+ return merged.conflicts.filter(path => {+ if (explicit?.has(path) || merged.structural.includes(path) || path.includes('\n') || !blobConflict(root, base, ours, theirs, path)) return false;+ const remote = treeEntry(root, theirs, path);+ if (!remote) return false;+ const commits = git(root, ['--literal-pathspecs', 'log', '--format=%H', '-n', String(MAX_SUPERSEDED_HISTORY), ours, '--', path]).stdout.split('\n').filter(Boolean);+ const blobs = git(root, ['cat-file', '--batch-check=%(objectname) %(objecttype)'], { input: commits.map(c => `${c}:${path}\n`).join('') })+ .stdout.split('\n').slice(0, commits.length).map(line => (line.endsWith(' blob') ? line.split(' ')[0] : null));+ const held = [treeEntry(root, ours, path)?.sha ?? null, ...blobs];+ const at = held.indexOf(remote.sha);+ return at > 0 && held.slice(0, at).some(sha => sha && sha !== remote.sha);+ });+}+/** Apply `--resolve` choices on top of the merge's placeholder tree; structural conflicts are refused. */function resolvedTree(ctx: Ctx, ours: string, theirs: string, merged: MergeTree, resolutions: Map<string, Resolution>, cwd: string): string {if (merged.conflicts.some(p => !resolutions.has(p))) throw conflictError(ctx, ours, theirs, merged);@@ -748,7 +774,7 @@ function shellWord(v: string): string {return /^[A-Za-z0-9._\/@%+:-]+$/.test(v) ? v : `'${v.replace(/'/g, `'\\''`)}'`;}-function conflictError(ctx: Ctx, ours: string, theirs: string, merged: MergeTree, preface = ''): OperationError {+function conflictError(ctx: Ctx, ours: string, theirs: string, merged: MergeTree & { superseded?: string[] }, preface = ''): OperationError {const paths = merged.conflicts;const local = ours.slice(0, 12);const remote = theirs.slice(0, 12);@@ -757,7 +783,7 @@ function conflictError(ctx: Ctx, ours: string, theirs: string, merged: MergeTree? `${preface}The local commit ${local} stays local and the checkout is unchanged. ${merged.structural.map(shellWord).join(', ')} ${merged.structural.length === 1 ? 'is' : 'are'} a file/directory or rename conflict that a per-file choice cannot resolve. ${compare}, then move or remove the local path in a new commit (gbrain git commit-push -m "<msg>" -- <paths>) and rerun gbrain git commit-push --push-only. See docs/guides/shared-checkout-git.md#conflicts.`: `${preface}The local commit ${local} stays local and the checkout is unchanged. ${compare}, then run gbrain git commit-push --push-only${ctx.keepCheckout ? ' --keep-checkout' : ''} --expect-remote ${remote} ${paths.map(p => `--resolve ${shellWord(p)}=ours|theirs`).join(' ')} (ours = this machine's version, theirs = the remote's, or =file:<path> with a merged copy). Until then every push from this checkout reports this conflict. See docs/guides/shared-checkout-git.md#conflicts.`;return opError('integrate_conflict', `Local and remote commits both changed ${paths.length} file(s) on ${ctx.branch}; nothing was merged.`, fix,- { detail: JSON.stringify({ local: ours, remote: theirs, paths, structural: merged.structural }),+ { detail: JSON.stringify({ local: ours, remote: theirs, paths, structural: merged.structural, ...(merged.superseded?.length ? { superseded: merged.superseded } : {}) }),fix: { ask_user: true, consent: [], actor: 'user', requires_exclusive: false,why: 'Choosing which version of a file wins discards the other side; ask the user before resolving.',user_message: `Both this machine and the remote changed ${paths.join(', ')}. Which version should win, or should they be merged by hand?`,@@ -809,7 +835,7 @@ function remoteContains(ctx: Ctx, sha: string): boolean {return true;}-interface Published { sha: string; integrated: number; confirmed: 'push' | 'remote'; quarantined?: QuarantineEntry }+interface Published { sha: string; integrated: number; confirmed: 'push' | 'remote'; quarantined?: QuarantineEntry; superseded?: string[] }// ── Quarantine (opt-in) ─────────────────────────────────────────────────────@@ -856,14 +882,16 @@ function publish(ctx: Ctx, start: string, resolutions: Map<string, Resolution> |let lastError = '';let stalled = 0;let quarantined: QuarantineEntry | undefined;+ const superseded = new Set<string>();+ const notes = () => ({ ...(quarantined ? { quarantined } : {}), ...(superseded.size ? { superseded: [...superseded] } : {}) });const onRemote = (): Published => {const tip = fetchTracking(ctx);- return { sha: tip && isAncestor(ctx.root, candidate, tip) ? tip : candidate, integrated, confirmed: 'remote', ...(quarantined ? { quarantined } : {}) };+ return { sha: tip && isAncestor(ctx.root, candidate, tip) ? tip : candidate, integrated, confirmed: 'remote', ...notes() };};for (let attempt = 0; attempt < MAX_PUSH_ATTEMPTS; attempt++) {if (attempt) Atomics.wait(sleeper, 0, 0, Math.min(2000, 50 * 2 ** attempt) + Math.floor(Math.random() * 100));const push = remoteGit(ctx.root, 'push', [...(ctx.keepCheckout ? ['--no-verify'] : []), '--', ctx.remote, `${candidate}:${ctx.mergeRef}`]);- if (push.code === 0) return { sha: candidate, integrated, confirmed: 'push', ...(quarantined ? { quarantined } : {}) };+ if (push.code === 0) return { sha: candidate, integrated, confirmed: 'push', ...notes() };lastError = push.stderr.trim();if (remoteContains(ctx, candidate)) return onRemote();const remoteTip = fetchTracking(ctx);@@ -872,13 +900,19 @@ function publish(ctx: Ctx, start: string, resolutions: Map<string, Resolution> |if (++stalled > 1) break;continue;}- const merged = integrate(ctx.root, candidate, remoteTip);+ const raw = integrate(ctx.root, candidate, remoteTip);+ const kept = supersededPaths(ctx.root, candidate, remoteTip, raw, resolutions);+ const merged = kept.length+ ? { ...raw, superseded: kept, conflicts: raw.conflicts.filter(p => !kept.includes(p)),+ tree: resolvedTree(ctx, candidate, remoteTip, { ...raw, conflicts: kept }, new Map(kept.map(p => [p, { kind: 'ours' } as Resolution])), cwd) }+ : raw;let tree = merged.tree!;- let parkedNote: string[] = [];+ let mergeNotes: string[] = kept.length+ ? [`Kept this machine's version of ${kept.length} file(s) where the remote held a version this checkout had already replaced: ${kept.slice(0, 20).join(', ')}${kept.length > 20 ? ', ...' : ''}`] : [];if (merged.conflicts.length && !resolutions?.size && !merged.structural.length && quarantineEnabled(ctx.root)) {tree = resolvedTree(ctx, candidate, remoteTip, merged, new Map(merged.conflicts.map(p => [p, { kind: 'theirs' } as Resolution])), cwd);quarantined = parkLocalVersion(ctx.root, candidate, remoteTip, merged.conflicts);- parkedNote = [`Quarantined this machine's version of ${merged.conflicts.length} conflicting file(s) under ${quarantined.ref}: ${merged.conflicts.slice(0, 20).join(', ')}`];+ mergeNotes = [...mergeNotes, `Quarantined this machine's version of ${merged.conflicts.length} conflicting file(s) under ${quarantined.ref}: ${merged.conflicts.slice(0, 20).join(', ')}`];} else if (merged.conflicts.length) {if (!resolutions?.size) throw conflictError(ctx, candidate, remoteTip, merged);if (!expectRemote || !remoteTip.startsWith(expectRemote.toLowerCase())) {@@ -888,7 +922,8 @@ function publish(ctx: Ctx, start: string, resolutions: Map<string, Resolution> |tree = resolvedTree(ctx, candidate, remoteTip, merged, resolutions, cwd);}integrated += Number(git(ctx.root, ['rev-list', '--count', `${candidate}..${remoteTip}`]).stdout.trim() || 0);- candidate = buildMerge(ctx, candidate, remoteTip, tree, merged.skipped, parkedNote);+ candidate = buildMerge(ctx, candidate, remoteTip, tree, merged.skipped, mergeNotes);+ for (const p of kept) superseded.add(p);}if (remoteContains(ctx, candidate)) return onRemote();throw opError('push_unconfirmed', `The commit is durable locally but no push to ${ctx.remote}/${ctx.mergeRef.replace(/^refs\/heads\//, '')} was confirmed.`,@@ -1111,6 +1146,7 @@ export function commitAndPush(opts: CommitPushOptions): CommitPushResult {sha: published.sha, committed, branch: ctx.branch, remote: ctx.remote, paths: rel,integrated: published.integrated, confirmed: published.confirmed, checkout: moved.checkout, ...(moved.reason ? { lagging_reason: moved.reason } : {}),...(published.quarantined ? { quarantined: published.quarantined } : {}),+ ...(published.superseded ? { superseded_remote_paths: published.superseded } : {}),};}diff --git a/test/git-commit-push-6530.serial.test.ts b/test/git-commit-push-6530.serial.test.tsindex 9b578af9b8..04af6e5215 100644--- a/test/git-commit-push-6530.serial.test.ts+++ b/test/git-commit-push-6530.serial.test.ts@@ -265,6 +265,105 @@ describe('integrate in memory', () => {});});+describe('superseded remote blobs: a stale clone brings back a version this checkout replaced', () => {+ const P = 'notes/alice-example.md';+ const Q = 'notes/bob-example.md';++ function commitFiles(dir: string, files: Record<string, string | null>, message: string): void {+ for (const [f, body] of Object.entries(files)) {+ if (body === null) { git(dir, 'rm', '-q', '--', f); continue; }+ mkdirSync(join(dir, f, '..'), { recursive: true });+ writeFileSync(join(dir, f), body);+ git(dir, 'add', '--', f);+ }+ git(dir, 'commit', '-qm', message);+ }++ /**+ * a publishes A for P and Q, then commits `ours` locally, one commit per step. b, still at A, commits `theirs`+ * (with an unrelated y.md edit) on a side branch, as a stale writer replaying an old copy would, then+ * merges it over an unrelated z.md commit and publishes the merge.+ */+ function staleMerge(ours: Array<Record<string, string | null>>, theirs: Record<string, string | null>) {+ const { bare, a, b } = setup();+ commitFiles(a, { [P]: 'A\n', [Q]: 'A\n' }, 'A');+ git(a, 'push', '-q');+ git(b, 'pull', '-q', '--ff-only');+ ours.forEach((step, i) => commitFiles(a, step, `local ${i + 1}`));+ git(b, 'checkout', '-qb', 'stale');+ commitFiles(b, { ...theirs, 'y.md': 'stale writer\n' }, 'stale writer');+ git(b, 'checkout', '-q', 'main');+ commitFiles(b, { 'z.md': 'unrelated\n' }, 'unrelated');+ git(b, 'merge', '-q', '--no-ff', '-m', 'merge stale', 'stale');+ git(b, 'push', '-q', 'origin', 'main');+ return { bare, a, b };+ }++ for (const fallback of [false, true]) {+ test(`the remote's copy of an older blob this checkout replaced is resolved to ours and reported${fallback ? ' (git < 2.38 fallback)' : ''}`, () => {+ if (fallback) process.env.GBRAIN_GIT_NO_MERGE_TREE = '1';+ const { bare, a } = staleMerge([{ [P]: 'B\n' }, { [P]: 'C\n' }], { [P]: 'B\n' });+ const r = commitAndPush({ repo: a, pushOnly: true, cwd: a });+ expect(r).toMatchObject({ outcome: 'pushed', checkout: 'advanced', superseded_remote_paths: [P] });+ expect(git(bare, 'show', `main:${P}`)).toBe('C');+ expect(git(bare, 'show', 'main:y.md')).toBe('stale writer');+ expect(git(bare, 'show', 'main:z.md')).toBe('unrelated');+ expect(remoteHead(bare)).toBe(git(a, 'rev-parse', 'HEAD'));+ expect(git(a, 'log', '-1', '--format=%B')).toContain(P);+ expect(readIntegrateConflict(a)).toBeNull();+ });+ }++ test('a blob this checkout never held at the path is still a two-sided conflict, reported as before', () => {+ const { bare, a } = staleMerge([{ [P]: 'B\n' }, { [P]: 'C\n' }], { [P]: 'D\n' });+ const tip = remoteHead(bare);+ let error: { code?: string; detail?: string } = {};+ try { commitAndPush({ repo: a, pushOnly: true, cwd: a }); } catch (e) { error = e as typeof error; }+ expect(error.code).toBe('integrate_conflict');+ const detail = JSON.parse(error.detail!);+ expect(Object.keys(detail).sort()).toEqual(['local', 'paths', 'remote', 'structural']);+ expect(detail).toEqual({ local: git(a, 'rev-parse', 'HEAD'), remote: tip, paths: [P], structural: [] });+ expect(remoteHead(bare)).toBe(tip);+ });++ test('mixed: only the real conflict is reported; the --resolve run settles the superseded path to ours too', () => {+ const { bare, a } = staleMerge([{ [P]: 'B\n', [Q]: 'B\n' }, { [P]: 'C\n', [Q]: 'C\n' }], { [P]: 'B\n', [Q]: 'D\n' });+ const c = conflictOf(() => commitAndPush({ repo: a, pushOnly: true, cwd: a })) as ReturnType<typeof conflictOf> & { superseded?: string[] };+ expect(c.paths).toEqual([Q]);+ expect(c.superseded).toEqual([P]);+ expect(c.fix).toContain(`--resolve ${Q}=ours|theirs`);+ expect(c.fix).not.toContain(`--resolve ${P}=`);+ expect(readIntegrateConflict(a)).toEqual(expect.objectContaining({ paths: [Q] }));+ const r = commitAndPush({ repo: a, pushOnly: true, cwd: a, resolutions: new Map([[Q, { kind: 'theirs' }]]), expectRemote: c.remote });+ expect(r).toMatchObject({ outcome: 'pushed', superseded_remote_paths: [P] });+ expect(git(bare, 'show', `main:${P}`)).toBe('C');+ expect(git(bare, 'show', `main:${Q}`)).toBe('D');+ });++ test('an explicit --resolve choice for a superseded path wins over the automatic one', () => {+ const { bare, a } = staleMerge([{ [P]: 'B\n' }, { [P]: 'C\n' }], { [P]: 'B\n' });+ const r = commitAndPush({ repo: a, pushOnly: true, cwd: a, resolutions: new Map([[P, { kind: 'theirs' }]]), expectRemote: remoteHead(bare) });+ expect(r.outcome).toBe('pushed');+ expect(r.superseded_remote_paths).toBeUndefined();+ expect(git(bare, 'show', `main:${P}`)).toBe('B');+ });++ test('deletions: the remote deleting the path stays a conflict; a restored blob counts only when this checkout replaced it before deleting', () => {+ const deleted = staleMerge([{ [P]: 'B\n' }, { [P]: 'C\n' }], { [P]: null });+ expect(conflictOf(() => commitAndPush({ repo: deleted.a, pushOnly: true, cwd: deleted.a })).paths).toEqual([P]);+ rmSync(root, { recursive: true, force: true }); root = mkdtempSync(join(tmpdir(), 'cp6530-'));++ const heldThenDeleted = staleMerge([{ [P]: 'B\n' }, { [P]: null }], { [P]: 'B\n' });+ expect(conflictOf(() => commitAndPush({ repo: heldThenDeleted.a, pushOnly: true, cwd: heldThenDeleted.a })).paths).toEqual([P]);+ rmSync(root, { recursive: true, force: true }); root = mkdtempSync(join(tmpdir(), 'cp6530-'));++ const replacedThenDeleted = staleMerge([{ [P]: 'B\n' }, { [P]: 'C\n' }, { [P]: null }], { [P]: 'B\n' });+ const r = commitAndPush({ repo: replacedThenDeleted.a, pushOnly: true, cwd: replacedThenDeleted.a });+ expect(r.superseded_remote_paths).toEqual([P]);+ expect(git(replacedThenDeleted.bare, 'ls-tree', '--name-only', 'main', 'notes/')).toBe('notes/bob-example.md');+ });+});+describe('advance is a compare-and-swap', () => {test('a lockless commit that lands while the push is in flight survives (never checkout -B)', () => {const { bare, a, b } = setup();