diff --git a/.changeset/quiet-trees-merge.md b/.changeset/quiet-trees-merge.md new file mode 100644 index 00000000..b6aea45c --- /dev/null +++ b/.changeset/quiet-trees-merge.md @@ -0,0 +1,4 @@ +--- +"@northguild/worktree": patch +--- +`worktree cleanup` now removes a squash-merged worktree even when the default branch changed lines near the branch's changes before the merge. It checks whether merging the branch would change anything, instead of matching patches. A worktree it still holds back for unpushed commits it cannot find in the base is now named in the output rather than skipped silently. diff --git a/docs/src/content/docs/commands/cleanup.mdx b/docs/src/content/docs/commands/cleanup.mdx index 5261c50d..d5c01497 100644 --- a/docs/src/content/docs/commands/cleanup.mdx +++ b/docs/src/content/docs/commands/cleanup.mdx @@ -44,8 +44,18 @@ carrying work for as long as it existed — on a repository that squash-merges i requests, that is every merged branch, and `cleanup` would find nothing to do ever again. So a worktree that is ahead of its base is asked a second question before anything is decided -about it: is the change it carries, taken as a whole, already applied in that base? Where it -is, the worktree is stale and says which base it landed in. Where it is not — including a +about it: is the change it carries, taken as a whole, already applied in that base? That is +asked by merging the branch into the base in memory, both ways round, and checking that +neither changes anything. So it does not matter that the base moved on lines near the branch's +change after it was cut, as it does whenever another pull request touches the same area. +Where that merge conflicts, or the git is older than 2.38 and cannot do it, `cleanup` falls +back to comparing the branch's diff against the base's commits. That is the weaker test: a +change to the lines around the branch's own defeats it, and so does a squash that carried a +conflict fix the branch itself does not have. Either way it fails towards keeping the worktree, +which is then named under one of the headings below. A merge that goes through cleanly and +does change the base is a no on its own, and the weaker test is not asked: a branch that was +squash-merged and then reverted on the base would bring its change back, and is kept. Where the change +is already applied, the worktree is stale and says which base it landed in. Where it is not — including a branch that was merged and has picked up a commit since — the commits are real work and hold it back exactly as before. @@ -75,7 +85,7 @@ its branch is still counted, from the repository, and it is removed only when th clear it. `cleanup` then drops git's record of it and its branch, and leaves the directory for you to check for uncommitted work before you delete it by hand. -`cleanup` also reports what it held back, under four headings: +`cleanup` also reports what it held back, under five headings: ```text Skipped 1 worktree branch that has uncommitted changes: @@ -86,23 +96,32 @@ Skipped 1 worktree branch with a live agent session: - feature/api (Remote removed, Agent: feature-api-1f) Skipped 1 worktree branch whose Linear issue is canceled but whose commits are not confirmed on its remote: - feature/eng-124-export (Ahead: 2, Linear ENG-124: canceled) +Skipped 1 worktree branch with unpushed commits not found in origin/main: +- feature/spike (Remote removed, Ahead: 3) ``` The second heading is the one that makes `No stale worktree branches found.` trustworthy in the way this matters: that line can no longer be produced by a worktree whose commits could not be counted. Such a worktree is always named. -**Those four headings are the whole of what `cleanup` reports.** A worktree carrying -unmerged commits that it *could* count is not stale, so it is neither removed nor listed — -it simply does not come up, and neither does a worktree tracking a live remote branch whose -Linear issue is not canceled. A branch whose issue is canceled is the exception: with -unmerged commits it is listed under the fourth heading, whether it tracks a live remote, has no -remote, or lost its remote. Use [`list`](/worktree/commands/list/) to see every worktree and what each one is carrying; +The fifth heading names a worktree whose remote branch is gone, or was never set, and which +carries commits that `cleanup` could not find in the base — the branch it was counted against, +which the heading names. Usually that is real work nobody else has. It can also be a branch +that was merged in a way `cleanup` could not see through, and the heading is what lets you check: +a line there is a worktree to look at, never one `cleanup` has quietly decided about. Before it +existed such a worktree was passed over without a word, and the run looked the same as one with +nothing to clean up. + +**Those five headings are the whole of what `cleanup` reports.** A worktree tracking a live +remote branch is active work, so it is neither removed nor listed — it simply does not come up. +A branch whose Linear issue is canceled is the exception: with unmerged commits it is listed under the +fourth heading, whether it tracks a live remote, has no remote, or lost its remote. Use +[`list`](/worktree/commands/list/) to see every worktree and what each one is carrying; `cleanup` only ever discusses the ones it would sweep and the ones it stopped short of. The count in every heading `cleanup` prints follows your system locale, so a large number is -grouped the way your locale writes it: `1,234` in English, `1.234` in German. That is all six: -`Found …`, the four `Skipped …` above, and the `Removing …` heading `--ignore-agents` prints (below). +grouped the way your locale writes it: `1,234` in English, `1.234` in German. That is all seven: +`Found …`, the five `Skipped …` above, and the `Removing …` heading `--ignore-agents` prints (below). ## Canceled Linear issues diff --git a/skills/worktree/SKILL.md b/skills/worktree/SKILL.md index d945b7c9..5b096ac9 100644 --- a/skills/worktree/SKILL.md +++ b/skills/worktree/SKILL.md @@ -573,7 +573,8 @@ identities, so counting alone reports a merged branch as carrying unpushed work for as long as the worktree exists; `cleanup` compares the change itself against the comparison base and names the base it landed in — `(Remote removed, merged into origin/main)`. A branch that has gained a commit since it was merged is -carrying real work again and is held back. +carrying real work again and is held back, and is named under `Skipped … with +unpushed commits not found in ` when its remote is gone or was never set. A branch made with `branch --linear` carries a record of its issue in git config (`branch..worktreeIssue`). When `linear.apiKey` is set, `cleanup` reads those diff --git a/src/commands/cleanup.test.ts b/src/commands/cleanup.test.ts index 161641c7..85c26e50 100644 --- a/src/commands/cleanup.test.ts +++ b/src/commands/cleanup.test.ts @@ -1244,6 +1244,83 @@ describe("cleanup command", () => { ); }); + // #382. A branch with no live remote, ahead of its base with nothing found + // there, reached none of the headings and was passed over in silence: the + // run looked like one with nothing to clean up. + describe("a branch whose commits were not found in the base", () => { + const unmerged = withVerdict({ + branchName: "feature/unmerged", + remote: "origin/feature/unmerged", + remoteExists: false, + ahead: 9, + mergedInto: undefined, + }); + + it("names it, and the base it was counted against", async () => { + vi.spyOn(git, "gitGetWorktreeList").mockResolvedValue([unmerged]); + vi.spyOn(git, "gitGetComparisonBase").mockResolvedValue("origin/main"); + const logSpy = vi.spyOn(cleanup, "log").mockImplementation(() => {}); + + (cleanup as any).parse = vi.fn().mockResolvedValue({ + flags: { force: false }, + }); + + await cleanup.run(); + + expect(spinnerMocks.succeed).not.toHaveBeenCalledWith( + "No stale worktree branches found.", + ); + expect(logSpy).toHaveBeenCalledWith( + "Skipped 1 worktree branch with unpushed commits not found in origin/main:", + ); + expect(logSpy).toHaveBeenCalledWith( + "- feature/unmerged (Remote removed, Ahead: 9)", + ); + }); + + // #368's record: its `.git` is gone but its branch was counted from the + // repository, so it is held back for the same reason and named the same way. + it("names a record whose directory lost its .git", async () => { + vi.spyOn(git, "gitGetWorktreeList").mockResolvedValue([ + { ...unmerged, pathExists: false, prunable: true }, + ]); + vi.spyOn(git, "gitGetComparisonBase").mockResolvedValue("origin/main"); + const logSpy = vi.spyOn(cleanup, "log").mockImplementation(() => {}); + + (cleanup as any).parse = vi.fn().mockResolvedValue({ + flags: { force: false }, + }); + + await cleanup.run(); + + expect(logSpy).toHaveBeenCalledWith( + "Skipped 1 worktree branch with unpushed commits not found in origin/main:", + ); + }); + + it("leaves a branch on a live remote unmentioned", async () => { + vi.spyOn(git, "gitGetWorktreeList").mockResolvedValue([ + withVerdict({ + branchName: "feature/active", + remote: "origin/feature/active", + remoteExists: true, + ahead: 2, + }), + ]); + const logSpy = vi.spyOn(cleanup, "log").mockImplementation(() => {}); + + (cleanup as any).parse = vi.fn().mockResolvedValue({ + flags: { force: false }, + }); + + await cleanup.run(); + + expect(logSpy).not.toHaveBeenCalledWith( + expect.stringContaining("not found in"), + ); + }); + }); + // The regression Phase 3 introduced: this worktree used to be named under // the uncommitted-changes heading and then appeared nowhere at all. it("names a worktree that is both dirty and uncountable", async () => { @@ -1462,6 +1539,24 @@ describe("cleanup command", () => { expect(removed).toEqual([]); }); + // #382: with no live remote and commits not found in the base, a canceled + // worktree also answers the unmerged heading's predicate. It is named once, + // under this heading, which outranks that one. + it("names a canceled worktree with no live remote under this heading only", async () => { + vi.spyOn(git, "gitGetComparisonBase").mockResolvedValue("origin/main"); + const wt = canceled( + "feature/eng-126", + "ENG-126", + { remoteExists: false, ahead: 2 }, + undefined, + ); + const { lines, removed } = await run([wt]); + + expect(lines).toContain(heading(1)); + expect(headings(lines)).toHaveLength(1); + expect(removed).toEqual([]); + }); + it("holds back one level with its tracking ref whose remote did not confirm the tip", async () => { const wt = canceled("feature/eng-125", "ENG-125", {}, false); const { lines, removed } = await run([wt]); diff --git a/src/commands/cleanup.ts b/src/commands/cleanup.ts index c634ffbd..68af047e 100644 --- a/src/commands/cleanup.ts +++ b/src/commands/cleanup.ts @@ -2,6 +2,7 @@ import { Flags } from "@oclif/core"; import { BaseCommand } from "../lib/base-command.js"; import chalk from "../lib/color.js"; import { + gitGetComparisonBase, gitGetWorktreeList, gitRemoveWorktreesWithProgress, hasLiveAgent, @@ -78,6 +79,23 @@ function isCanceledButUnconfirmed(wt: WorktreeListEntry): boolean { ); } +// #382: whatever the sets above did not claim, where the reason is that the +// branch carries commits the base does not have and nothing else keeps it. Its +// remote is gone or was never set, so `isSafeToRemove` reached the count and the +// count was a real, non-zero one with no merge found. Before this such a +// worktree reached none of the other headings and was passed over without a word +// — a run indistinguishable from one with nothing to clean up, which is the +// silence F-059 exists to break. A worktree whose remote is still live is simply +// active work and stays unmentioned, as it always was. `pathExists` is not +// asked: a directory that is gone is already safe, and a record whose `.git` is +// missing (#368) is counted from the repository and belongs here like any other. +// The caller excludes the other sets, so a worktree is under one heading. +function isHeldBackAsUnmerged(wt: WorktreeListEntry): boolean { + return ( + wt.safeToRemove !== true && !wt.remoteExists && !!wt.ahead && !wt.mergedInto + ); +} + // D6: why this worktree qualified, in the order isSafeToRemove decides it. // // Every branch returns a non-empty string, which is the whole point. After @@ -196,6 +214,22 @@ export default class Cleanup extends BaseCommand { }); } + // Held back because it carries commits the base does not have. The base is + // named, because that is the fact a reader can go and check — it is the one + // `ahead` was counted against for a branch with no live remote. Agents on, like + // the headings above, for the same reason. + private logUnmerged(unmerged: WorktreeListEntry[], base: string) { + const count = unmerged.length; + this.log( + `Skipped ${chalk.bold(formatCount(count))} worktree ${count === 1 ? "branch" : "branches"} with unpushed commits not found in ${base}:`, + ); + unmerged.forEach((wt) => { + this.log( + `- ${worktreeListEntryToListName(wt, "yellow", { agents: true })}`, + ); + }); + } + // Rendered with the ordinary detail list, the issue detail and the agent // detail: the details carry the count of unpushed commits or of uncommitted // changes, which is what tells a reader why the canceled issue did not decide, @@ -216,13 +250,15 @@ export default class Cleanup extends BaseCommand { } // Each section is guarded here rather than at the call sites, which carry one - // kind of hold-back far more often than all four at once. An unguarded + // kind of hold-back far more often than all five at once. An unguarded // heading would read "Skipped 0 worktree branches …". private logHeldBack( skipped: WorktreeListEntry[], agentSkipped: WorktreeListEntry[], uncountable: WorktreeListEntry[], canceledUnconfirmed: WorktreeListEntry[], + unmerged: WorktreeListEntry[], + unmergedBase: string, ) { if (skipped.length > 0) { this.logSkipped(skipped); @@ -236,6 +272,9 @@ export default class Cleanup extends BaseCommand { if (canceledUnconfirmed.length > 0) { this.logCanceledUnconfirmed(canceledUnconfirmed); } + if (unmerged.length > 0) { + this.logUnmerged(unmerged, unmergedBase); + } } public async run(): Promise { @@ -244,8 +283,8 @@ export default class Cleanup extends BaseCommand { // The override overrules the verdict, not the lookup (D6): sessions are // always gathered so that what it sweeps past can be named. The sweep itself // is classified on copies with the agent stripped and the verdict re-derived, - // so the removed set and the four hold-back headings are what they were - // before agents existed. `gathered` keeps the originals for the naming. + // so the removed set and the hold-back headings are what they would be + // without agents. `gathered` keeps the originals for the naming. const gathered = await gitGetWorktreeList({ includeAgents: true, // The Linear signal is read on every run and is silent without a key @@ -283,12 +322,28 @@ export default class Cleanup extends BaseCommand { !uncountable.includes(wt), ); + // Last of all, for the same reason. The base is asked for once, and only when + // something is under the heading: a branch with no live remote was counted + // against the comparison base, so that is the one to name. A truthy `ahead` + // guarantees it resolved (see `countAhead`). + const unmerged = allWorktrees.filter( + (wt) => + isHeldBackAsUnmerged(wt) && + !skipped.includes(wt) && + !agentSkipped.includes(wt) && + !uncountable.includes(wt) && + !canceledUnconfirmed.includes(wt), + ); + const unmergedBase = + unmerged.length > 0 ? await gitGetComparisonBase() : ""; + if ( worktrees.length === 0 && skipped.length === 0 && agentSkipped.length === 0 && uncountable.length === 0 && - canceledUnconfirmed.length === 0 + canceledUnconfirmed.length === 0 && + unmerged.length === 0 ) { spinner.succeed("No stale worktree branches found."); return; @@ -300,7 +355,14 @@ export default class Cleanup extends BaseCommand { // reach the success line above and look identical to a clean sweep. if (worktrees.length === 0) { spinner.info("No stale worktree branches can be removed safely."); - this.logHeldBack(skipped, agentSkipped, uncountable, canceledUnconfirmed); + this.logHeldBack( + skipped, + agentSkipped, + uncountable, + canceledUnconfirmed, + unmerged, + unmergedBase, + ); return; } @@ -318,7 +380,14 @@ export default class Cleanup extends BaseCommand { // Reported in both paths: --force means "do not ask me", not "do not tell // me". See CLEANUP-DATA-LOSS-PLAN §4.2. - this.logHeldBack(skipped, agentSkipped, uncountable, canceledUnconfirmed); + this.logHeldBack( + skipped, + agentSkipped, + uncountable, + canceledUnconfirmed, + unmerged, + unmergedBase, + ); // Only what the override swept past: removed here, but held back by the // agent-aware verdict. Without the flag that set is empty by construction, diff --git a/src/lib/git.test.ts b/src/lib/git.test.ts index c9c4421d..2ad892d3 100644 --- a/src/lib/git.test.ts +++ b/src/lib/git.test.ts @@ -123,31 +123,54 @@ vi.mock("./removal-progress.js", async (importOriginal) => ({ createRemovalWatcher: () => ({ countGone: removalProgressMocks.countGone }), })); -// The three calls the merged probe makes, and the answers they get. It runs for -// any worktree that is ahead of a comparison base and has no live remote branch, +// The calls the merged probe makes, and the answers they get. It runs for any +// worktree that is ahead of a comparison base and has no live remote branch, // which is every stale candidate — so the suites below that drive // `gitGetWorktreeList` have to account for it the way they account for the -// count itself. Kept as one pair so a change to the probe's argv is one edit -// here rather than a hunt through every fixture. +// count itself. Kept together so a change to the probe's argv is one edit here +// rather than a hunt through every fixture. +// +// The first question is whether merging the branch into the base changes +// anything (#382): `merge-tree --write-tree`, both ways round, compared with the +// base's own tree. The reverse merge is asked only once the forward one matched. +// A clean merge that differs is a no on its own; only a merge that gave no +// answer — a conflict, or a git too old for the flag — asks the patch probe. const MERGE_BASE_SHA = "a1b2c3d4"; const PROBE_COMMIT_SHA = "e5f6a7b8"; - -function mergedProbeCommands(worktreePath: string, base = "origin/main") { - return [ - `git merge-base ${base} HEAD (cwd: ${worktreePath})`, - `git commit-tree HEAD^{tree} -p ${MERGE_BASE_SHA} -m "merged probe" (cwd: ${worktreePath})`, - `git cherry ${base} ${PROBE_COMMIT_SHA} (cwd: ${worktreePath})`, +const BASE_TREE_SHA = "b4a3e2d1"; +const OTHER_TREE_SHA = "c9d8e7f6"; + +function mergedProbeCommands( + worktreePath: string, + base = "origin/main", + { merged = false }: { merged?: boolean } = {}, +) { + const tree = [ + `git merge-tree --write-tree ${base} HEAD (cwd: ${worktreePath})`, + `git rev-parse ${base}^{tree} (cwd: ${worktreePath})`, ]; + return merged + ? [ + ...tree, + `git merge-tree --write-tree HEAD ${base} (cwd: ${worktreePath})`, + ] + : tree; } -// `git cherry` answers one line per commit on the head side, and the probe puts -// exactly one there: `-` when the base already holds an equivalent patch, `+` -// when it does not. +// `merged` is the merge coming back with the base's tree both ways round; not +// merged is the forward merge coming back with a different one, which is a +// confident no and asks nothing further (#383 review). function mockMergedProbe(merged: boolean) { + if (merged) { + mockRun + .mockResolvedValueOnce(BASE_TREE_SHA) + .mockResolvedValueOnce(BASE_TREE_SHA) + .mockResolvedValueOnce(BASE_TREE_SHA); + return; + } mockRun - .mockResolvedValueOnce(MERGE_BASE_SHA) - .mockResolvedValueOnce(PROBE_COMMIT_SHA) - .mockResolvedValueOnce(`${merged ? "-" : "+"} ${PROBE_COMMIT_SHA}`); + .mockResolvedValueOnce(OTHER_TREE_SHA) + .mockResolvedValueOnce(BASE_TREE_SHA); } describe("git branch parsing", () => { @@ -1530,15 +1553,13 @@ describe("gitGetWorktreeList with a prunable record", () => { mockPreamble(`${porcelainRecord(brokenPath, "broken")}${prunableLine}\n`); expectCommands( "git rev-list --count origin/main..refs/heads/broken", - "git merge-base origin/main refs/heads/broken", - `git commit-tree refs/heads/broken^{tree} -p ${MERGE_BASE_SHA} -m "merged probe"`, - `git cherry origin/main ${PROBE_COMMIT_SHA}`, + "git merge-tree --write-tree origin/main refs/heads/broken", + "git rev-parse origin/main^{tree}", ); mockRun .mockResolvedValueOnce("2") - .mockResolvedValueOnce(MERGE_BASE_SHA) - .mockResolvedValueOnce(PROBE_COMMIT_SHA) - .mockResolvedValueOnce(`+ ${PROBE_COMMIT_SHA}`); + .mockResolvedValueOnce(OTHER_TREE_SHA) + .mockResolvedValueOnce(BASE_TREE_SHA); const [worktree] = await gitGetWorktreeList(); @@ -1776,7 +1797,7 @@ describe("gitGetWorktreeList ahead counting", () => { expectCommands( "git symbolic-ref --short refs/remotes/origin/HEAD", `git rev-list --count origin/main..HEAD (cwd: ${onePath})`, - ...mergedProbeCommands(onePath), + ...mergedProbeCommands(onePath, "origin/main", { merged: true }), `git status -s (cwd: ${onePath})`, ); mockRunPreamble("feature/one origin/feature/one"); @@ -1812,6 +1833,153 @@ describe("gitGetWorktreeList ahead counting", () => { expect(worktree.safeToRemove).toBe(false); }); + // #382: the base moved on a line next to the branch's diff before the squash + // landed, so the squash commit's patch has different context and `cherry` + // answers `+` for a branch that is fully merged. Asking whether merging it + // would change anything is not fooled by context, so the patch is never + // consulted. + it("marks a worktree merged when the base moved around its change", async () => { + expectPreamble(); + expectCommands( + "git symbolic-ref --short refs/remotes/origin/HEAD", + `git rev-list --count origin/main..HEAD (cwd: ${onePath})`, + ...mergedProbeCommands(onePath, "origin/main", { merged: true }), + `git status -s (cwd: ${onePath})`, + ); + mockRunPreamble("feature/one "); + mockRun.mockResolvedValueOnce("origin/main").mockResolvedValueOnce("9"); + mockMergedProbe(true); + mockRun.mockResolvedValueOnce(""); + + const [worktree] = await gitGetWorktreeList(); + + expect(worktree.mergedInto).toBe("origin/main"); + expect(worktree.safeToRemove).toBe(true); + expect( + mockRun.mock.calls.filter((call) => call[1]?.[0] === "cherry"), + ).toHaveLength(0); + }); + + // The fallback, reachable where the merge cannot be asked for: a squash that + // carried a conflict fix leaves a merge that conflicts (exit 1), and a git + // older than 2.38 does not know the flag. Both reject, and the patch + // comparison still gets its say. + it("falls back to patch equivalence when the merge cannot be taken", async () => { + expectPreamble(); + expectCommands( + "git symbolic-ref --short refs/remotes/origin/HEAD", + `git rev-list --count origin/main..HEAD (cwd: ${onePath})`, + `git merge-tree --write-tree origin/main HEAD (cwd: ${onePath})`, + `git merge-base origin/main HEAD (cwd: ${onePath})`, + `git commit-tree HEAD^{tree} -p ${MERGE_BASE_SHA} -m "merged probe" (cwd: ${onePath})`, + `git cherry origin/main ${PROBE_COMMIT_SHA} (cwd: ${onePath})`, + `git status -s (cwd: ${onePath})`, + ); + mockRunPreamble("feature/one "); + mockRun + .mockResolvedValueOnce("origin/main") + .mockResolvedValueOnce("4") + .mockRejectedValueOnce(new Error("conflict")) + .mockResolvedValueOnce(MERGE_BASE_SHA) + .mockResolvedValueOnce(PROBE_COMMIT_SHA) + .mockResolvedValueOnce(`- ${PROBE_COMMIT_SHA}`) + .mockResolvedValueOnce(""); + + const [worktree] = await gitGetWorktreeList(); + + expect(worktree.mergedInto).toBe("origin/main"); + expect(worktree.safeToRemove).toBe(true); + }); + + // A forward merge that matched and a reverse one that could not be taken is + // a merge that gave no answer, so the patch comparison is asked. + it("falls back to patch equivalence when only the reverse merge fails", async () => { + expectPreamble(); + expectCommands( + "git symbolic-ref --short refs/remotes/origin/HEAD", + `git rev-list --count origin/main..HEAD (cwd: ${onePath})`, + `git merge-tree --write-tree origin/main HEAD (cwd: ${onePath})`, + `git rev-parse origin/main^{tree} (cwd: ${onePath})`, + `git merge-tree --write-tree HEAD origin/main (cwd: ${onePath})`, + `git merge-base origin/main HEAD (cwd: ${onePath})`, + `git commit-tree HEAD^{tree} -p ${MERGE_BASE_SHA} -m "merged probe" (cwd: ${onePath})`, + `git cherry origin/main ${PROBE_COMMIT_SHA} (cwd: ${onePath})`, + `git status -s (cwd: ${onePath})`, + ); + mockRunPreamble("feature/one "); + mockRun + .mockResolvedValueOnce("origin/main") + .mockResolvedValueOnce("1") + .mockResolvedValueOnce(BASE_TREE_SHA) + .mockResolvedValueOnce(BASE_TREE_SHA) + .mockRejectedValueOnce(new Error("conflict")) + .mockResolvedValueOnce(MERGE_BASE_SHA) + .mockResolvedValueOnce(PROBE_COMMIT_SHA) + .mockResolvedValueOnce(`+ ${PROBE_COMMIT_SHA}`) + .mockResolvedValueOnce(""); + + const [worktree] = await gitGetWorktreeList(); + + expect(worktree.mergedInto).toBeUndefined(); + expect(worktree.safeToRemove).toBe(false); + }); + + // The #382 review: a merge driver that keeps one side (`merge=ours`) makes + // the forward merge drop the branch's change and come back with the base's + // tree. Merged the other way the branch's side is kept, so the reverse does + // not match, and that is a no without asking the patch comparison. + it("does not take a one-sided merge for merged", async () => { + expectPreamble(); + expectCommands( + "git symbolic-ref --short refs/remotes/origin/HEAD", + `git rev-list --count origin/main..HEAD (cwd: ${onePath})`, + `git merge-tree --write-tree origin/main HEAD (cwd: ${onePath})`, + `git rev-parse origin/main^{tree} (cwd: ${onePath})`, + `git merge-tree --write-tree HEAD origin/main (cwd: ${onePath})`, + `git status -s (cwd: ${onePath})`, + ); + mockRunPreamble("feature/one "); + mockRun + .mockResolvedValueOnce("origin/main") + .mockResolvedValueOnce("1") + .mockResolvedValueOnce(BASE_TREE_SHA) + .mockResolvedValueOnce(BASE_TREE_SHA) + .mockResolvedValueOnce(OTHER_TREE_SHA) + .mockResolvedValueOnce(""); + + const [worktree] = await gitGetWorktreeList(); + + expect(worktree.mergedInto).toBeUndefined(); + expect(worktree.safeToRemove).toBe(false); + }); + + // The #383 review: a branch squash-merged and then reverted on the base. The + // merge is clean and would bring the change back, so it differs from the + // base's tree, while `git cherry` would still find the squash commit's patch + // and say `-`. A clean merge that differs is the stronger answer, and the + // patch comparison is not asked to overrule it. + it("does not let the patch comparison overrule a merge that changes the base", async () => { + expectPreamble(); + expectCommands( + "git symbolic-ref --short refs/remotes/origin/HEAD", + `git rev-list --count origin/main..HEAD (cwd: ${onePath})`, + ...mergedProbeCommands(onePath), + `git status -s (cwd: ${onePath})`, + ); + mockRunPreamble("feature/one "); + mockRun.mockResolvedValueOnce("origin/main").mockResolvedValueOnce("2"); + mockMergedProbe(false); + mockRun.mockResolvedValueOnce(""); + + const [worktree] = await gitGetWorktreeList(); + + expect(worktree.mergedInto).toBeUndefined(); + expect(worktree.safeToRemove).toBe(false); + expect( + mockRun.mock.calls.filter((call) => call[1]?.[0] === "cherry"), + ).toHaveLength(0); + }); + // Fails closed like every other unknown in this file: a probe that cannot // answer is not an answer of "merged". `git cherry` is the only unbounded // call in the gather, so this is also what a timeout looks like. @@ -1820,6 +1988,7 @@ describe("gitGetWorktreeList ahead counting", () => { expectCommands( "git symbolic-ref --short refs/remotes/origin/HEAD", `git rev-list --count origin/main..HEAD (cwd: ${onePath})`, + `git merge-tree --write-tree origin/main HEAD (cwd: ${onePath})`, `git merge-base origin/main HEAD (cwd: ${onePath})`, `git status -s (cwd: ${onePath})`, ); @@ -1827,6 +1996,7 @@ describe("gitGetWorktreeList ahead counting", () => { mockRun .mockResolvedValueOnce("origin/main") .mockResolvedValueOnce("3") + .mockRejectedValueOnce(new Error("unrelated histories")) .mockRejectedValueOnce(new Error("no merge base")) .mockResolvedValueOnce(""); @@ -2255,7 +2425,7 @@ describe("gitRemoveWorktree prompt", () => { "git symbolic-ref --short refs/remotes/origin/HEAD", `git rev-list --count origin/main..HEAD (cwd: ${targetPath})`, "git config northguild.worktree.defaultSourceBranch", - ...mergedProbeCommands(targetPath), + ...mergedProbeCommands(targetPath, "origin/main", { merged }), `git status -s (cwd: ${targetPath})`, ); diff --git a/src/lib/git.ts b/src/lib/git.ts index e3a95061..aae15ade 100644 --- a/src/lib/git.ts +++ b/src/lib/git.ts @@ -649,26 +649,101 @@ async function countAhead( // repository that squash-merges everything gets a `cleanup` that never finds // anything. See GitHub issue #63 §5 R2, which named this risk before it landed. // -// So the question asked here is patch equivalence instead: `commit-tree` builds -// a throwaway commit carrying the branch's *cumulative* diff — its own tree, -// parented on the merge base — and `git cherry` marks that commit `-` when an -// equivalent patch already exists in the base. A squash merge is exactly one -// such patch, which is why this survives one where the count does not. A branch -// that has picked up even one commit since it was merged has a different -// cumulative diff and comes back `+`, so the #63 guard is untouched by this: +// So the question asked here is whether merging the branch into the base would +// change anything. `merge-tree --write-tree` performs that merge in memory, and +// when the tree it comes back with is the base's own tree, everything the +// branch carries is already in the base, however much the base moved on lines +// near it since. A squash merge is exactly that case, and so is a rebase. A +// branch that has picked up even one commit since it was merged brings a change +// the base lacks, so the merge result differs and the #63 guard is untouched: // what it protects is a branch carrying work nobody else has, and this only -// ever speaks for work everybody has. +// ever speaks for work everybody has. See GitHub issue #382, which found the +// patch-equivalence answer below failing on exactly this. +// +// The merge is asked in both directions, and both have to come back with the +// base's tree. One direction is not enough where a repository configures a +// merge driver that keeps one side, such as `merge=ours` in `.gitattributes`: +// merging the branch into the base would then drop the branch's side of a file +// both changed and look like no change at all. Merged the other way round the +// branch's side is the one kept, so the result differs and the answer is no. +// +// A clean merge that does not come back with the base's tree is a confident +// no, and nothing below is asked: the merge has found content the base lacks. +// A branch squash-merged and then reverted on the base is the case that makes +// this matter — the merge would bring the change back, while `git cherry` +// still finds the squash commit's patch and would answer yes. +// +// Patch equivalence stays as the fallback only where the merge gave no answer: +// the git that predates `merge-tree --write-tree` (2.38) and a merge that +// conflicts — which is what a squash carrying its own conflict fix leaves, and +// what the base reworking the squashed lines afterwards leaves too: `commit-tree` +// builds a throwaway commit carrying the branch's *cumulative* diff — its own +// tree, parented on the merge base — and `git cherry` marks that commit `-` when +// an equivalent patch exists in the base. It is the weaker question, because a +// patch-id includes the unchanged context lines around each change, so another +// pull request touching a line next to the branch's diff makes it answer `+` +// for a branch that is fully merged. It can only fail in that direction, which +// is why it is kept rather than dropped: a `-` is still a confident yes. // // Every exit that is not a confident "yes" is undefined, and undefined is not // safe. That covers unrelated histories (no merge base), a base that will not // resolve, an unconfigured committer identity, and the timeout below. const MERGED_PROBE_TIMEOUT_MS = 10_000; +// Whether merging the branch into the base, and the base into the branch, both +// come back with the base's own tree. `unknown` is a merge that gave no answer +// — a conflict exits 1, an old git does not know `--write-tree` — and is the +// only outcome the patch comparison is asked to settle. Never throws. +type MergeResult = "merged" | "differs" | "unknown"; + +async function compareMergeResult( + at: { cwd?: string }, + base: string, + rev: string, +): Promise { + // A clean merge prints the tree alone; a conflicted one exits non-zero and + // rejects. The first line is taken all the same, so a format that adds lines + // after the tree cannot turn into a mismatch that reads as anything else. + const mergedTree = async (ours: string, theirs: string) => + ( + await run("git", ["merge-tree", "--write-tree", ours, theirs], { + ...at, + timeout: MERGED_PROBE_TIMEOUT_MS, + }) + ) + .split("\n")[0] + ?.trim(); + try { + const forward = await mergedTree(base, rev); + if (!forward) { + return "unknown"; + } + const baseTree = await run("git", ["rev-parse", `${base}^{tree}`], at); + if (forward !== baseTree) { + return "differs"; + } + const reverse = await mergedTree(rev, base); + if (!reverse) { + return "unknown"; + } + return reverse === baseTree ? "merged" : "differs"; + } catch { + return "unknown"; + } +} + async function findMergedBase( probe: CommitProbe, base: string, ): Promise { const at = probe.cwd === undefined ? {} : { cwd: probe.cwd }; + const merge = await compareMergeResult(at, base, probe.rev); + if (merge === "merged") { + return base; + } + if (merge === "differs") { + return undefined; + } try { const mergeBase = await run("git", ["merge-base", base, probe.rev], at); // The probe commit is a real object in the repository — one per worktree @@ -688,12 +763,12 @@ async function findMergedBase( ], at, ); - // The only unbounded call in the gather: `cherry` computes a patch-id for - // every commit the base has gained since the merge base, so a worktree - // branched long ago from a busy default branch can make it expensive. It - // runs at most once per worktree and only where the answer can change a - // verdict, and the timeout bounds the pathological case to a held-back - // worktree rather than a `list` that appears to hang. + // `cherry` computes a patch-id for every commit the base has gained since + // the merge base, so a worktree branched long ago from a busy default + // branch can make it expensive. It runs at most once per worktree and only + // where the answer can change a verdict, and the timeout bounds the + // pathological case to a held-back worktree rather than a `list` that + // appears to hang. const cherry = await run("git", ["cherry", base, probeCommit], { ...at, timeout: MERGED_PROBE_TIMEOUT_MS,