Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .changeset/quiet-trees-merge.md
Original file line number Diff line number Diff line change
@@ -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.
41 changes: 30 additions & 11 deletions docs/src/content/docs/commands/cleanup.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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:
Expand All @@ -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
Comment thread
baldurpan marked this conversation as resolved.
Resolved
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

Expand Down
3 changes: 2 additions & 1 deletion skills/worktree/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <base>` 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.<name>.worktreeIssue`). When `linear.apiKey` is set, `cleanup` reads those
Expand Down
95 changes: 95 additions & 0 deletions src/commands/cleanup.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down Expand Up @@ -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]);
Expand Down
81 changes: 75 additions & 6 deletions src/commands/cleanup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -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);
Expand All @@ -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<void> {
Expand All @@ -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
Expand Down Expand Up @@ -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;
Expand All @@ -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;
}

Expand All @@ -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,
Expand Down
Loading