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
5 changes: 5 additions & 0 deletions .changeset/prunable-worktree-entry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@northguild/worktree": patch
---

`remove`, `list` and `cleanup` no longer fail when a worktree directory has lost its `.git` file. Git's record of it is pruned on removal, and the directory is left on disk for you to check.
2 changes: 1 addition & 1 deletion docs/src/chat/docs-routes.generated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,5 +36,5 @@ export const VALID_DOC_ROUTES: ReadonlySet<string> = new Set([
/** What the Worker indexes: the hub's status line reads it. */
export const CORPUS_COUNTS: { pages: number; chunks: number } = {
pages: 29,
chunks: 222,
chunks: 223,
};
8 changes: 6 additions & 2 deletions docs/src/content/docs/commands/cleanup.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -65,11 +65,15 @@ Found 5 worktree branches that are marked safe to remove.
- feature/eng-123-dark-mode (Linear issue ENG-123 canceled, no unpushed commits)
```

Those five are the whole vocabulary. `merged into <base>` is the one that names a count rather
Those five are the whole vocabulary, with one more below for a directory that has lost its `.git` file. `merged into <base>` is the one that names a count rather
than denying one: that worktree *is* ahead of `origin/main`, and every commit in it is already
applied there. `Path does not exist` answers none of the checks above: a worktree whose
directory is already gone is removed before its commits are considered, because there is no
directory to count them in.
directory to count them in. `Not a git checkout (.git missing), directory kept` is a directory that is still on disk but
has lost its `.git` file, as an interrupted removal can leave it. Unlike a directory that is gone,
its branch is still counted, from the repository, and it is removed only when the checks above
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:

Expand Down
13 changes: 7 additions & 6 deletions docs/src/content/docs/commands/list.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ edits are not part of it; they are counted separately as `N uncommitted changes`
- **It sits beside `Ahead:` and is shown only where `Ahead:` is.** A worktree with nothing ahead, and one
whose branch is already merged, show no `Churn:` detail. The [JSON](#json-output) still carries what was
taken for a merged branch.
- **It is left out where it could not be taken** — no comparison base resolved, the directory is gone, or
- **It is left out where it could not be taken** — no comparison base resolved, the directory is gone or has lost its `.git` file, or
the diff failed, did not answer within 10 seconds or printed something unrecognised — rather than printed as `+0 -0`.
- **It costs one more git call per worktree**, which is why it is opt-in. Without `--churn`, `list` runs
exactly what it ran before, and [`remove`](/worktree/commands/remove/) and [`cleanup`](/worktree/commands/cleanup/)
Expand Down Expand Up @@ -135,7 +135,8 @@ unchanged. [`remove`](/worktree/commands/remove/) never reads them.
`Ahead:` counts commits this worktree carries that its comparison base does not.
**The count is taken for every worktree whose directory is present, including
one on a branch you have never pushed** — that is the case worth seeing, because
those commits exist in exactly one place.
those commits exist in exactly one place. A directory that has lost its `.git` file is
counted too, from the repository, against the branch git still holds for it.

The base depends on whether the branch tracks a remote:

Expand Down Expand Up @@ -190,18 +191,18 @@ and any warning go to stderr. It implies a [non-interactive run](/worktree/comma
| --- | --- |
| `branch`, `path` | the worktree's branch and absolute path |
| `current` | whether it is the worktree you are in |
| `pathExists` | whether its directory is still on disk |
| `pathExists` | whether its directory is still on disk as a git checkout. `false` also when the directory is there but has lost its `.git` file; `list` then shows it as `Not a git checkout (.git missing), directory kept` |
| `remote`, `remoteExists` | the upstream the branch tracks, `null` when it tracks none, and whether that remote branch still exists |
| `ahead`, `behind` | the [counts above](#ahead-and-behind-counts) as numbers |
| `mergedInto` | the base whose commits already contain all of this branch's changes; `null` when not known to be merged |
| `uncommittedChanges` | the number of uncommitted changes; `null` when the directory is gone, as there is nothing to count |
| `uncommittedChanges` | the number of uncommitted changes; `null` when `pathExists` is `false`, as there is nothing to count |
Comment thread
baldurpan marked this conversation as resolved.
Resolved
| `safeToRemove` | the verdict [`cleanup`](/worktree/commands/cleanup/) acts on, from the data this run gathered. `cleanup` weighs agent sessions and canceled Linear issues; `list` does so only with `--agents` and `--issues`, so without them it can report `false` for a worktree `cleanup` would remove through a canceled issue, and `true` for one it would hold back for a live session. With both flags it is `cleanup`'s verdict, except for the worktree you are in (`current: true`), which `cleanup` never considers |
| `churn` | only with `--churn`: `{files, insertions, deletions}` for the committed work, [as above](#showing-churn), or `null` when it could not be taken. All zeros means the diff was taken and was empty |
| `issue` | only with `--issues`: `null` when the branch has no recorded Linear issue, otherwise `{provider, key, state}`: `provider` is `"linear"`, `key` the identifier such as `ENG-123`, and `state` the issue's state type (`canceled`, `started`, ...) or `null` when it could not be read. Only the type is read, never the state's name |
| `agent` | only with `--agents`: `null` when no session lives in the worktree, otherwise `{name, sessionId, herdrAgent, live, interactive, waiting}`. `waiting` is `true` for a live session that is idle between turns or blocked on a question, whether or not it is interactive. `herdrAgent` is the name Herdr gives the agent, as `branch --json` reports it in `herdr.agent`, or the agent's pane id when Herdr reports no name |

**A count or flag that could not be taken is `null`, never `0` and never left out.** `ahead` and `uncommittedChanges` are
`null` when the directory is gone (and `ahead` also when no comparison base resolved), `behind` is `null` for a branch with no upstream, `churn` is `null` when no figure was taken for the worktree, `issue.state` is `null` when the type could not be read (a warning goes to stderr, and stdout is still one document), and
**A count or flag that could not be taken is `null`, never `0` and never left out.** `uncommittedChanges` is
`null` when `pathExists` is `false`, `ahead` is `null` when the directory is gone (but not when it has only lost its `.git` file, which is counted from the repository) and when no comparison base resolved, `behind` is `null` for a branch with no upstream, `churn` is `null` when no figure was taken for the worktree, `issue.state` is `null` when the type could not be read (a warning goes to stderr, and stdout is still one document), and
inside `agent` any of `sessionId`, `herdrAgent`, `live`, `interactive` and `waiting` is `null` when the
source did not say. A `0` always means the count was taken and is zero.

Expand Down
8 changes: 8 additions & 0 deletions docs/src/content/docs/commands/remove.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,14 @@ counted as ahead, because a squash merge and a rebase both give the same work ne
identities, but there is nothing in it to lose. Warning about those commits would teach you
that this prompt does not mean anything, which is how the one that does gets waved through.

## A directory that has lost its `.git` file

An interrupted removal, such as a stopped `rm -rf`, can leave a worktree's directory on disk without
the `.git` file that made it a checkout. Git still lists it, as `prunable`. Its unpushed commits are
still counted, from the repository against the branch git holds for it, so the prompt warns about
them as it would for any worktree. `remove` then drops git's record and deletes the branch. **The directory itself is kept**: without `.git` its contents can no longer be checked for
uncommitted work, so look through it before you delete it by hand.

## When an agent is working in the worktree

If an agent session is working in the worktree you name, the prompt opens with that fact and then
Expand Down
8 changes: 6 additions & 2 deletions src/commands/cleanup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,11 @@ import {
import { createSpinner } from "../lib/progress.js";
import { askConfirm } from "../lib/prompt.js";
import type { WorktreeListEntry } from "../lib/types.js";
import { formatCount, worktreeListEntryToListName } from "../lib/utils.js";
import {
formatCount,
missingPathDetail,
worktreeListEntryToListName,
} from "../lib/utils.js";

// A worktree cleanup would have swept but for the work sitting in it. Asking the
// predicate about a zeroed copy keeps the safety rule in one place rather than
Expand Down Expand Up @@ -88,7 +92,7 @@ function removalReason(wt: WorktreeListEntry): string {
if (!wt.pathExists) {
// Returned before any count is consulted, so this says nothing about
// commits — deliberately. See §9 Q5.
return "Path does not exist";
return missingPathDetail(wt);
}
if (wt.remoteExists && wt.issue?.state === "canceled") {
// A worktree on a live remote qualifies only through D4's last clause, and
Expand Down
213 changes: 213 additions & 0 deletions src/lib/git.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -767,6 +767,26 @@ describe("gitNukeWorktreeCmd", () => {
]);
});

// #368: an interrupted removal can leave the directory with no `.git` file.
// `git worktree remove` refuses it, and the record has to go by a prune.
it("prunes instead of removing when the directory has lost its .git file", async () => {
vi.spyOn(fs, "existsSync").mockImplementation(
(path) => path === worktreePath,
);
const runSpy = vi.spyOn(cli, "run").mockResolvedValue("");

await gitNukeWorktreeCmd(target);

// Nothing after the branch delete: the directory is left on disk.
expect(runSpy).toHaveBeenCalledTimes(2);
expect(runSpy).toHaveBeenNthCalledWith(1, "git", ["worktree", "prune"]);
expect(runSpy).toHaveBeenNthCalledWith(2, "git", [
"branch",
"-D",
branchName,
]);
});

it("appends --force to the remove when forced", async () => {
const runSpy = vi.spyOn(cli, "run").mockResolvedValue("");

Expand Down Expand Up @@ -1450,6 +1470,151 @@ describe("gitGetWorktreeList agent join", () => {
// those with an upstream. A branch nobody ever pushed is precisely the case
// the old `remoteExists` guard skipped, and skipping it is what let such a
// worktree read as empty.
// #368: a record git marks `prunable` has a directory that is no checkout, and
// every probe run in it would climb into the parents and fail the whole gather.
// Its branch is still in the repository, so its commits are counted from there.
describe("gitGetWorktreeList with a prunable record", () => {
const rootPath = "/repo/project";
const brokenPath = `${rootPath}.worktrees/broken`;
const prunableLine = "prunable gitdir file points to non-existent location";

beforeEach(() => {
vi.clearAllMocks();
vi.spyOn(fs, "existsSync").mockReturnValue(true);
});

function mockPreamble(record: string) {
expectCommands(
"git fetch --prune",
"git --no-pager branch -r",
'git for-each-ref "--format=%(refname:short) %(upstream:short)" refs/heads',
"git branch --show-current",
"git rev-parse --show-toplevel",
"git worktree list --porcelain",
"git symbolic-ref --short refs/remotes/origin/HEAD",
);
mockRun
.mockResolvedValueOnce("")
.mockResolvedValueOnce("")
.mockResolvedValueOnce("")
.mockResolvedValueOnce("main")
.mockResolvedValueOnce(rootPath)
.mockResolvedValueOnce(record)
.mockResolvedValueOnce("origin/main");
}

it("counts its branch from the repository and runs nothing in the directory", async () => {
mockPreamble(`${porcelainRecord(brokenPath, "broken")}${prunableLine}\n`);
expectCommands("git rev-list --count origin/main..refs/heads/broken");
mockRun.mockResolvedValueOnce("0");

const [worktree] = await gitGetWorktreeList();

expect(worktree?.branchName).toBe("broken");
expect(worktree?.pathExists).toBe(false);
expect(worktree?.ahead).toBe(0);
expect(worktree?.safeToRemove).toBe(true);
expect(mockRun).toHaveBeenCalledWith(
"git",
["rev-list", "--count", "origin/main..refs/heads/broken"],
undefined,
);
for (const [, , options] of mockRun.mock.calls) {
expect(options?.cwd).not.toBe(brokenPath);
}
});

// The review of #372: before this, the missing-path clause let such a branch
// through, and `cleanup` ran `branch -D` on commits that exist nowhere else.
it("holds back a prunable branch that carries unmerged commits", async () => {
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}`,
);
mockRun
.mockResolvedValueOnce("2")
.mockResolvedValueOnce(MERGE_BASE_SHA)
.mockResolvedValueOnce(PROBE_COMMIT_SHA)
.mockResolvedValueOnce(`+ ${PROBE_COMMIT_SHA}`);

const [worktree] = await gitGetWorktreeList();

expect(worktree?.ahead).toBe(2);
expect(worktree?.mergedInto).toBeUndefined();
expect(worktree?.safeToRemove).toBe(false);
});

// #372 review: git calls a record whose whole directory is gone prunable too.
// That one keeps the missing-path verdict it always had, uncounted.
it("leaves a prunable record whose directory is gone uncounted and safe", async () => {
vi.spyOn(fs, "existsSync").mockReturnValue(false);
mockPreamble(`${porcelainRecord(brokenPath, "broken")}${prunableLine}\n`);

const [worktree] = await gitGetWorktreeList();

expect(worktree?.prunable).toBeUndefined();
expect(worktree?.ahead).toBeUndefined();
expect(worktree?.safeToRemove).toBe(true);
expect(mockRun).not.toHaveBeenCalledWith(
"git",
["rev-list", "--count", "origin/main..refs/heads/broken"],
undefined,
);
});

it("counts a prunable branch with a live upstream against that upstream", async () => {
expectCommands(
"git fetch --prune",
"git --no-pager branch -r",
'git for-each-ref "--format=%(refname:short) %(upstream:short)" refs/heads',
"git branch --show-current",
"git rev-parse --show-toplevel",
"git worktree list --porcelain",
"git symbolic-ref --short refs/remotes/origin/HEAD",
"git rev-list --count broken@{u}..refs/heads/broken",
);
mockRun
.mockResolvedValueOnce("")
.mockResolvedValueOnce("origin/broken")
.mockResolvedValueOnce("broken origin/broken")
.mockResolvedValueOnce("main")
.mockResolvedValueOnce(rootPath)
.mockResolvedValueOnce(
`${porcelainRecord(brokenPath, "broken")}${prunableLine}\n`,
)
.mockResolvedValueOnce("origin/main")
.mockResolvedValueOnce("1");

const [worktree] = await gitGetWorktreeList();

expect(worktree?.remoteExists).toBe(true);
expect(worktree?.ahead).toBe(1);
expect(worktree?.safeToRemove).toBe(false);
});

it("counts a prunable detached record from the commit git recorded for it", async () => {
const sha = "abc1234abc1234abc1234abc1234abc1234abc1234";
mockPreamble(
`worktree ${brokenPath}\nHEAD ${sha}\ndetached\n${prunableLine}\n`,
);
expectCommands(`git rev-list --count origin/main..${sha}`);
mockRun.mockResolvedValueOnce("0");

const [worktree] = await gitGetWorktreeList();

expect(worktree?.branchName).toBe("(detached HEAD)");
expect(worktree?.ahead).toBe(0);
expect(mockRun).toHaveBeenCalledWith(
"git",
["rev-list", "--count", `origin/main..${sha}`],
undefined,
);
});
});

describe("gitGetWorktreeList ahead counting", () => {
const rootPath = "/repo/project";
const onePath = `${rootPath}.worktrees/feature/one`;
Expand Down Expand Up @@ -2675,6 +2840,27 @@ describe("what the removal helpers report", () => {
expect(progressMocks.start.mock.calls[0][0]).toBe(41);
});

// #372 review: a directory that lost its `.git` is pruned, not deleted,
// so walking it would draw a bar that nothing ever moves.
it("weighs a kept directory with no .git as one entry", async () => {
vi.spyOn(fs, "existsSync").mockImplementation(
(candidate) => candidate !== `${twoPath}/.git`,
);
removalProgressMocks.measureTree.mockResolvedValueOnce({
total: 40,
checkpoints: [],
coveredFraction: 0,
});

await gitRemoveWorktreesWithProgress([entry(), two]);

expect(removalProgressMocks.measureTree).toHaveBeenCalledTimes(1);
expect(removalProgressMocks.measureTree).not.toHaveBeenCalledWith(
twoPath,
);
expect(progressMocks.start.mock.calls[0][0]).toBe(41);
});

it("falls back to a spinner line per worktree when the count throws, and still removes", async () => {
removalProgressMocks.measureTree.mockRejectedValue(
new Error("EACCES: permission denied"),
Expand Down Expand Up @@ -2997,11 +3183,38 @@ describe("gitGetWorktrees", () => {
);
vi.spyOn(fs, "existsSync").mockReturnValue(false);

// The directory is gone, which git also calls prunable. It keeps the
// missing-path verdict it always had, so it is not marked (#372 review).
expect(await gitGetWorktrees()).toEqual([
{
path: `${treesPath}/prun`,
branchName: "prun",
pathExists: false,
isCurrent: false,
},
]);
});

it("marks a prunable worktree whose directory is still on disk", async () => {
mockList(
porcelain(
mainRecord,
linked(
`${treesPath}/prun`,
"prun",
"prunable gitdir file points to non-existent location",
),
),
);
vi.spyOn(fs, "existsSync").mockReturnValue(true);

expect(await gitGetWorktrees()).toEqual([
{
path: `${treesPath}/prun`,
branchName: "prun",
pathExists: false,
prunable: true,
head: hash,
isCurrent: false,
},
]);
Expand Down
Loading