From 67e52b467e0c754e14420fcdd4a31933c7089fe2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Baldur=20P=C3=A1ll=20H=C3=B3lmgeirsson?= Date: Mon, 30 Nov 2026 15:48:44 +0000 Subject: [PATCH 1/8] feat(claude-hook): hidden claude-hook command handling WorktreeCreate (#279) Phase 1 of #279. A hidden `worktree claude-hook` reads Claude Code's hook input on stdin (64 KiB cap, TTY refused, zod-validated, name checked as a branch and a path segment), creates `.worktrees/` from the configured source with env copy and install on stderr, reopens an existing one, and prints only the worktree's realpath on stdout. WorktreeRemove still exits 2 until Phase 2. Gate 1: pnpm check, typecheck (root + docs), build, docs:build, worker:bundle-check, docs:audit-dist, test (4208 passed), docs:test (1861 passed), test-markers grep, all exit 0. Gate 2: reviewer subagent, FAIL then PASS WITH NOTES after one loopback (install-failure message now names `worktree remove -f`; the postCreate refusal names only `worktree config --approve`). Notes in context/notes.md. --- context/notes.md | 13 ++ src/commands/claude-hook.test.ts | 370 ++++++++++++++++++++++++++++++ src/commands/claude-hook.ts | 161 +++++++++++++ src/lib/claude-hook-input.test.ts | 149 ++++++++++++ src/lib/claude-hook-input.ts | 161 +++++++++++++ 5 files changed, 854 insertions(+) create mode 100644 context/notes.md create mode 100644 src/commands/claude-hook.test.ts create mode 100644 src/commands/claude-hook.ts create mode 100644 src/lib/claude-hook-input.test.ts create mode 100644 src/lib/claude-hook-input.ts diff --git a/context/notes.md b/context/notes.md new file mode 100644 index 0000000..3f8e393 --- /dev/null +++ b/context/notes.md @@ -0,0 +1,13 @@ +# Notes — claude-code-worktree-hooks (#279) + +Non-blocking observations from the gates. Branch-local; `/feature-close` deletes this file. + +## Phase 1 — Hook input and `WorktreeCreate` + +- Spinner-on-stderr is true by construction (`progress.ts`) but untested: `gitCreateWorktree` is mocked in `claude-hook.test.ts`. +- The checkout-elsewhere and dangling-record refusals are asserted only as exit 2, not by message. +- The description's exit-2 line omits the dangling worktree record that D3 refuses (Phase 4 rewrites the help). +- `hasControlCharacter` lets C1 controls (U+0080–U+009F) through; git accepts them, Claude may mangle the printed path. +- Untested orderings: `--source` resolved after the fetch; D4's "one stderr line"; D2's "no opener or agent". +- The postCreate refusal replaces the original `MissingValueError` without keeping it as `cause` (deliberate: its advice was wrong here). +- On main, not this feature: the name containment check is textual (a symlinked dir under `.worktrees/` could escape it; `branch` shares it); `isValidBranchName` accepts some names git refuses (`a/.b`), exiting 1 instead of 2; a failing `gitListIgnoredEnvFiles` after the tree exists exits 1 without naming the tree (`env.ts:168-175`). diff --git a/src/commands/claude-hook.test.ts b/src/commands/claude-hook.test.ts new file mode 100644 index 0000000..307234d --- /dev/null +++ b/src/commands/claude-hook.test.ts @@ -0,0 +1,370 @@ +/** biome-ignore-all lint/suspicious/noExplicitAny: Allow any in tests */ +import { + mkdirSync, + mkdtempSync, + realpathSync, + rmSync, + symlinkSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { Readable } from "node:stream"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import * as gitConfig from "../lib/config.js"; +import { copyEnvFilesFromRootPath } from "../lib/env.js"; +import * as git from "../lib/git.js"; +import { runInstall } from "../lib/install.js"; +import { resetProjectConfigCache } from "../lib/project-config.js"; +import { + captureOutput, + expectCommands, + loadConfig, + mockRun, +} from "../test-setup.js"; +import ClaudeHook from "./claude-hook.js"; + +vi.mock("../lib/env.js", () => ({ + copyEnvFilesFromRootPath: vi.fn().mockResolvedValue([]), +})); +vi.mock("../lib/install.js", () => ({ + runInstall: vi.fn().mockResolvedValue({ ran: false, reason: "skipped" }), +})); + +const realStdin = Object.getOwnPropertyDescriptor(process, "stdin"); + +// Expected values: the plan's §4.1 contract and the "Done when" list of phase 1 +// (a to g), never what the command printed. +describe("claude-hook command", () => { + let sandbox: string; + let worktreesRoot: string; + let originalExitCode: typeof process.exitCode; + let output: ReturnType; + const mockCopy = vi.mocked(copyEnvFilesFromRootPath); + const mockInstall = vi.mocked(runInstall); + + function pipe(text: string, isTTY?: boolean) { + const stdin = Object.assign(Readable.from([text]), { isTTY }); + Object.defineProperty(process, "stdin", { + value: stdin, + configurable: true, + }); + } + + const create = (name: unknown, extra: Record = {}) => + JSON.stringify({ hook_event_name: "WorktreeCreate", name, ...extra }); + + async function runHook(stdin: string, flags: Record = {}) { + pipe(stdin); + const command = new ClaudeHook([], await loadConfig()); + (command as any).parse = vi.fn().mockResolvedValue({ args: {}, flags }); + (command as any).parsed = true; + await (command as any)._run(); + } + + const gitWrites = () => + vi.mocked(git.gitCreateWorktree).mock.calls.length + + mockRun.mock.calls.filter(([, args]) => args?.[0] === "worktree").length; + + beforeEach(() => { + // The real path sits behind a symlink, so the command has to resolve it. + const real = mkdtempSync(join(tmpdir(), "claude-hook-real-")); + sandbox = join(mkdtempSync(join(tmpdir(), "claude-hook-link-")), "repo"); + symlinkSync(real, sandbox); + worktreesRoot = `${sandbox}.worktrees`; + mkdirSync(`${realpathSync(real)}.worktrees`, { recursive: true }); + symlinkSync(`${realpathSync(real)}.worktrees`, worktreesRoot); + + originalExitCode = process.exitCode; + process.exitCode = undefined; + output = captureOutput(); + resetProjectConfigCache(); + mockCopy.mockResolvedValue([]); + mockInstall.mockResolvedValue({ ran: false, reason: "skipped" }); + mockRun.mockResolvedValue(""); + expectCommands( + "git rev-parse --show-toplevel", + "git rev-parse --verify --quiet --end-of-options HEAD^{commit}", + "git rev-parse --verify --quiet --end-of-options nope^{commit}", + "git config --local northguild.worktree.postCreateApproval", + ); + + vi.spyOn(gitConfig, "gitGetConfigValue").mockResolvedValue(""); + vi.spyOn(git, "gitGetAbsoluteWorktreesPath").mockResolvedValue( + worktreesRoot, + ); + vi.spyOn(git, "gitFindBranchCheckout").mockResolvedValue(undefined); + vi.spyOn(git, "gitGetLocalBranches").mockResolvedValue([]); + vi.spyOn(git, "gitFetch").mockResolvedValue(""); + vi.spyOn(git, "gitResolveOriginHead").mockResolvedValue("origin/main"); + vi.spyOn(git, "gitReadBlobAtRef").mockResolvedValue({ + status: "absent-path", + }); + vi.spyOn(git, "gitHasOriginRemote").mockResolvedValue(true); + vi.spyOn(git, "gitCreateWorktree").mockImplementation(async (name) => { + mkdirSync(join(realpathSync(`${worktreesRoot}`), name), { + recursive: true, + }); + return `${worktreesRoot}/${name}`; + }); + }); + + afterEach(() => { + output.restore(); + process.exitCode = originalExitCode; + if (realStdin) Object.defineProperty(process, "stdin", realStdin); + rmSync(realpathSync(worktreesRoot), { recursive: true, force: true }); + vi.restoreAllMocks(); + }); + + describe("WorktreeCreate with valid input (a)", () => { + it("prints the realpath as the only stdout line and creates from the default source", async () => { + await runHook(create("feature-auth", { session_id: "s", cwd: "/x" })); + + const expected = join(realpathSync(worktreesRoot), "feature-auth"); + expect(output.stdout()).toBe(`${expected}\n`); + expect(output.stdout()).not.toMatch(/\/\.\.?(\/|$)/); + expect(git.gitCreateWorktree).toHaveBeenCalledWith( + "feature-auth", + "origin/main", + { fetch: false }, + ); + expect(process.exitCode).toBeUndefined(); + }); + + it("passes the report to stderr and the project's copy patterns through", async () => { + await runHook(create("feature-auth")); + + expect(mockCopy).toHaveBeenCalledWith(`${worktreesRoot}/feature-auth`, { + report: "stderr", + copy: undefined, + }); + expect(mockInstall).toHaveBeenCalledWith( + `${worktreesRoot}/feature-auth`, + undefined, + ); + }); + + it("uses the configured defaultSourceBranch when --source is not given", async () => { + vi.spyOn(gitConfig, "gitGetConfigValue").mockImplementation( + async (key: string) => + key === "defaultSourceBranch" ? "origin/develop" : "", + ); + + await runHook(create("x")); + + expect(git.gitCreateWorktree).toHaveBeenCalledWith( + "x", + "origin/develop", + { fetch: false }, + ); + }); + + it("uses a --source that resolves as a commit", async () => { + await runHook(create("x"), { source: "HEAD" }); + + expect(mockRun).toHaveBeenCalledWith("git", [ + "rev-parse", + "--verify", + "--quiet", + "--end-of-options", + "HEAD^{commit}", + ]); + expect(git.gitCreateWorktree).toHaveBeenCalledWith("x", "HEAD", { + fetch: false, + }); + }); + }); + + describe("--source that does not resolve (b)", () => { + it("exits 2 with no worktree add and empty stdout", async () => { + mockRun.mockRejectedValue(new Error("exit 1")); + + await runHook(create("x"), { source: "nope" }); + + expect(process.exitCode).toBe(2); + expect(output.stdout()).toBe(""); + expect(output.stderr()).toContain("nope"); + expect(gitWrites()).toBe(0); + }); + }); + + describe("bad input exits 2 with empty stdout and no git write (c)", () => { + it.each([ + ["invalid JSON", "{nope"], + ["a non-object", "[1]"], + ["a missing name", JSON.stringify({ hook_event_name: "WorktreeCreate" })], + ["a non-string name", create(7)], + ["an empty name", create("")], + ["a parent segment", create("../x")], + ["an absolute name", create("/x")], + ["a leading dash", create("-D")], + ["a double dot", create("a..b")], + ["a control character", create("a\u0007b")], + ["an unknown event", JSON.stringify({ hook_event_name: "Stop" })], + [ + "a WorktreeRemove (Phase 2)", + JSON.stringify({ + hook_event_name: "WorktreeRemove", + worktree_path: "/x", + }), + ], + ["input over the cap", create("x", { pad: "y".repeat(70000) })], + ])("%s", async (_label, stdin) => { + await runHook(stdin); + + expect(process.exitCode).toBe(2); + expect(output.stdout()).toBe(""); + expect(output.stderr()).not.toBe(""); + expect(gitWrites()).toBe(0); + expect(git.gitFetch).not.toHaveBeenCalled(); + expect(mockCopy).not.toHaveBeenCalled(); + expect(mockInstall).not.toHaveBeenCalled(); + }); + + it("a terminal on stdin", async () => { + pipe("", true); + const command = new ClaudeHook([], await loadConfig()); + (command as any).parse = vi + .fn() + .mockResolvedValue({ args: {}, flags: {} }); + (command as any).parsed = true; + await (command as any)._run(); + + expect(process.exitCode).toBe(2); + expect(output.stdout()).toBe(""); + expect(gitWrites()).toBe(0); + }); + }); + + describe("a name that is already taken (d)", () => { + it("reopens a worktree under the worktrees directory: prints its path, exit 0, copies and installs nothing", async () => { + const existing = join(realpathSync(worktreesRoot), "again"); + mkdirSync(existing, { recursive: true }); + vi.spyOn(git, "gitFindBranchCheckout").mockResolvedValue({ + path: `${worktreesRoot}/again`, + pathExists: true, + inWorktreesRoot: true, + }); + + await runHook(create("again")); + + expect(output.stdout()).toBe(`${existing}\n`); + expect(process.exitCode).toBeUndefined(); + expect(gitWrites()).toBe(0); + expect(mockCopy).not.toHaveBeenCalled(); + expect(mockInstall).not.toHaveBeenCalled(); + }); + + it("refuses a branch with no worktree, exit 2", async () => { + vi.spyOn(git, "gitGetLocalBranches").mockResolvedValue(["taken"]); + + await runHook(create("taken")); + + expect(process.exitCode).toBe(2); + expect(output.stdout()).toBe(""); + expect(output.stderr()).toContain("no worktree"); + expect(gitWrites()).toBe(0); + }); + + it("refuses a branch checked out outside the worktrees directory, exit 2", async () => { + vi.spyOn(git, "gitFindBranchCheckout").mockResolvedValue({ + path: "/elsewhere/taken", + pathExists: true, + inWorktreesRoot: false, + }); + + await runHook(create("taken")); + + expect(process.exitCode).toBe(2); + expect(output.stdout()).toBe(""); + expect(gitWrites()).toBe(0); + }); + + it("refuses a record whose directory is gone, exit 2", async () => { + vi.spyOn(git, "gitFindBranchCheckout").mockResolvedValue({ + path: `${worktreesRoot}/gone`, + pathExists: false, + inWorktreesRoot: true, + }); + + await runHook(create("gone")); + + expect(process.exitCode).toBe(2); + expect(output.stdout()).toBe(""); + expect(gitWrites()).toBe(0); + }); + }); + + describe("an unapproved postCreate (e)", () => { + it("exits 2 before worktree add", async () => { + vi.spyOn(git, "gitReadBlobAtRef").mockResolvedValue({ + status: "found", + content: "postCreate:\n - pnpm install\n", + }); + + await runHook(create("x")); + + expect(process.exitCode).toBe(2); + expect(output.stdout()).toBe(""); + expect(gitWrites()).toBe(0); + expect(mockInstall).not.toHaveBeenCalled(); + // The next step is one this command offers: no --no-install flag exists. + expect(output.stderr()).toContain("worktree config --approve"); + expect(output.stderr()).not.toContain("--no-install"); + }); + }); + + describe("a failed install (f)", () => { + it("exits 1 with empty stdout and names the kept worktree on stderr", async () => { + mockInstall.mockResolvedValue({ + ran: true, + ok: false, + command: "pnpm install", + reason: "exited with code 1", + steps: ["pnpm install"], + from: "lockfile", + inferred: true, + } as any); + + await runHook(create("x")); + + expect(process.exitCode).toBe(1); + expect(output.stdout()).toBe(""); + expect(output.stderr()).toContain(`${worktreesRoot}/x`); + // Plan §5: the failure message names the removal command. + expect(output.stderr()).toContain("worktree remove x -f"); + }); + }); + + describe("visibility (g)", () => { + it("is not listed by `worktree --help`, though a listed command is", async () => { + // oclif's help filters on each command's `hidden` (D9); ours is read from + // the class, a visible command stands beside it. + const config = await loadConfig(); + const loadable = (id: string, hidden: boolean) => + ({ + id, + hidden, + aliases: [], + hiddenAliases: [], + flags: {}, + args: {}, + summary: `the ${id} command`, + pluginAlias: "@northguild/worktree", + pluginType: "core", + }) as any; + Object.defineProperty(config, "commands", { + value: [ + loadable("claude-hook", ClaudeHook.hidden === true), + loadable("open", false), + ], + }); + const { Help } = await import("@oclif/core"); + + await new Help(config).showHelp([]); + + expect(output.stdout()).toContain("open"); + expect(output.stdout()).not.toContain("claude-hook"); + }); + }); +}); diff --git a/src/commands/claude-hook.ts b/src/commands/claude-hook.ts new file mode 100644 index 0000000..8ae0236 --- /dev/null +++ b/src/commands/claude-hook.ts @@ -0,0 +1,161 @@ +import { realpathSync } from "node:fs"; +import { Flags } from "@oclif/core"; +import { BaseCommand } from "../lib/base-command.js"; +import { + parseHookInput, + readHookStdin, + resolveWorktreeName, +} from "../lib/claude-hook-input.js"; +import { run } from "../lib/cli.js"; +import { copyEnvFilesFromRootPath } from "../lib/env.js"; +import { + gitCreateWorktree, + gitFetch, + gitFindBranchCheckout, + gitGetAbsoluteWorktreesPath, + gitGetLocalBranches, +} from "../lib/git.js"; +import { runInstall } from "../lib/install.js"; +import { + ensurePostCreateApproved, + getTeamConfigValue, + loadProjectConfig, +} from "../lib/project-config.js"; +import { InvalidValueError, MissingValueError } from "../lib/prompt.js"; + +export default class ClaudeHook extends BaseCommand { + // D9: kept out of `worktree --help` until its docs land (Phase 4). + static override hidden = true; + static override description = + `The command behind Claude Code's WorktreeCreate hook: reads the hook's JSON from stdin and creates a worktree. + +WorktreeCreate reads "name" from stdin, plus --source from the command line. +It creates the branch "name" like \`worktree branch\` without its prompts, +issue lookup and opener, or reopens the worktree that name already has. +Stdout is the worktree's real path, one line, and empty on failure; the +spinner, the env-file report and everything else go to stderr. + +Exit codes: +0 created, or reopened +1 git, copy or install failed (a worktree that was made is kept and its path +named on stderr) +2 bad input, a --source that is not a commit, an unapproved postCreate, or a +name taken by a branch with no worktree or a checkout elsewhere`; + static override examples = [ + "<%= config.bin %> <%= command.id %> --source HEAD", + ]; + + static override flags = { + source: Flags.string({ + char: "s", + description: + "Ref to create the worktree from (default: branch's default)", + }), + }; + + public async run(): Promise { + const { flags } = await this.parse(ClaudeHook); + const input = parseHookInput(await readHookStdin(process.stdin)); + if (input.event !== "WorktreeCreate") { + // Phase 2 adds remove; until then it is refused like an unknown event. + throw new InvalidValueError( + `The ${input.event} hook event is not supported yet.`, + ); + } + + const name = input.name; + resolveWorktreeName(name, await gitGetAbsoluteWorktreesPath()); + + const existing = await this.findExistingWorktree(name); + if (existing) { + this.log(existing); + return; + } + + // One fetch, before the project file is read from origin/HEAD and before a + // --source such as origin/x can be looked up. + await gitFetch(); + const project = await loadProjectConfig(); + for (const warning of project.warnings) { + this.warn(warning); + } + + const source = await this.resolveSource(flags.source); + try { + await ensurePostCreateApproved({}); + } catch (error) { + // The stock message advises `--no-install`, a flag this command does not + // have; the settings command line cannot answer a prompt either. + if (error instanceof MissingValueError) { + throw new InvalidValueError( + "This project's postCreate steps in .worktree.yml are not approved. Approve them once in a terminal with `worktree config --approve`, then retry.", + ); + } + throw error; + } + + const projectPath = await gitCreateWorktree(name, source, { fetch: false }); + await copyEnvFilesFromRootPath(projectPath, { + report: "stderr", + copy: project.status === "loaded" ? project.config.copy : undefined, + }); + + const installed = await runInstall(projectPath, undefined); + if (installed.ran && !installed.ok) { + this.error( + `\`${installed.command}\` failed (${installed.reason}). The worktree was created at ${projectPath} and kept. Fix the install there, or run \`worktree remove ${name} -f\` and re-run.`, + { exit: 1 }, + ); + } + + this.log(realpathSync(projectPath)); + } + + /** + * D3: a name that already has a worktree under `.worktrees/` is + * reopened — its path is the answer and nothing is copied or installed. The + * other states of a taken name are refused with `branch`'s messages. + */ + private async findExistingWorktree(name: string) { + const checkout = await gitFindBranchCheckout(name); + + if (!checkout) { + if ((await gitGetLocalBranches()).includes(name)) { + throw new InvalidValueError( + `Branch "${name}" already exists but has no worktree. Choose another name, or delete the branch with \`git branch -d ${name}\`.`, + ); + } + return undefined; + } + if (!checkout.inWorktreesRoot) { + throw new InvalidValueError( + `Branch "${name}" is already checked out at ${checkout.path}, outside the worktrees directory. Choose another name.`, + ); + } + if (!checkout.pathExists) { + throw new InvalidValueError( + `Branch "${name}" has a worktree record at ${checkout.path}, but that directory no longer exists. Run \`git worktree prune\` to clear it, then re-run.`, + ); + } + return realpathSync(checkout.path); + } + + /** D2: `--source` must be a commit; without it, `branch`'s own default. */ + private async resolveSource(source: string | undefined) { + if (source === undefined) { + return (await getTeamConfigValue("defaultSourceBranch")) || "origin/main"; + } + try { + await run("git", [ + "rev-parse", + "--verify", + "--quiet", + "--end-of-options", + `${source}^{commit}`, + ]); + } catch { + throw new InvalidValueError(`--source "${source}" is not a commit.`); + } + return source; + } +} diff --git a/src/lib/claude-hook-input.test.ts b/src/lib/claude-hook-input.test.ts new file mode 100644 index 0000000..dd2efc6 --- /dev/null +++ b/src/lib/claude-hook-input.test.ts @@ -0,0 +1,149 @@ +import { Readable } from "node:stream"; +import { describe, expect, it } from "vitest"; +import { + CLAUDE_HOOK_INPUT_MAX_BYTES, + parseHookInput, + readHookStdin, + resolveWorktreeName, +} from "./claude-hook-input.js"; + +// Expected values come from the plan's D4 (what is accepted and refused) and +// §4.1 (exit 2 for bad input), not from the implementation. +function piped(text: string | string[]) { + return Object.assign(Readable.from(Array.isArray(text) ? text : [text]), { + isTTY: undefined, + }); +} + +describe("readHookStdin", () => { + it("returns what was piped, whole", async () => { + expect(await readHookStdin(piped('{"a":1}'))).toBe('{"a":1}'); + }); + + it("refuses a terminal rather than waiting for a person", async () => { + const stdin = Object.assign(Readable.from([]), { isTTY: true }); + await expect(readHookStdin(stdin)).rejects.toThrow(/terminal/); + }); + + it("refuses input over the 64 KiB cap", async () => { + expect(CLAUDE_HOOK_INPUT_MAX_BYTES).toBe(65536); + const over = "x".repeat(CLAUDE_HOOK_INPUT_MAX_BYTES + 1); + await expect(readHookStdin(piped(over))).rejects.toThrow(/65536/); + }); + + it("stops at the cap across chunks", async () => { + const half = "x".repeat(CLAUDE_HOOK_INPUT_MAX_BYTES / 2 + 1); + await expect(readHookStdin(piped([half, half]))).rejects.toThrow(/65536/); + }); + + it("accepts input of exactly the cap", async () => { + const exact = "x".repeat(CLAUDE_HOOK_INPUT_MAX_BYTES); + expect(await readHookStdin(piped(exact))).toHaveLength( + CLAUDE_HOOK_INPUT_MAX_BYTES, + ); + }); +}); + +describe("parseHookInput", () => { + it("reads a WorktreeCreate input and ignores unknown fields", () => { + expect( + parseHookInput( + JSON.stringify({ + hook_event_name: "WorktreeCreate", + name: "feature-auth", + session_id: "s1", + cwd: "/elsewhere", + extra: { a: 1 }, + }), + ), + ).toEqual({ + event: "WorktreeCreate", + name: "feature-auth", + sessionId: "s1", + }); + }); + + it("reads a WorktreeRemove input with an absolute worktree_path", () => { + expect( + parseHookInput( + JSON.stringify({ + hook_event_name: "WorktreeRemove", + worktree_path: "/repo.worktrees/x", + }), + ), + ).toEqual({ + event: "WorktreeRemove", + worktreePath: "/repo.worktrees/x", + sessionId: undefined, + }); + }); + + it.each([ + ["invalid JSON", "{nope"], + ["empty input", ""], + ["a non-object (array)", "[]"], + ["a non-object (string)", '"WorktreeCreate"'], + ["null", "null"], + ["no event", '{"name":"x"}'], + ["a non-string event", '{"hook_event_name":1,"name":"x"}'], + ["an unknown event", '{"hook_event_name":"SessionStart","name":"x"}'], + ["a create with no name", '{"hook_event_name":"WorktreeCreate"}'], + [ + "a create with a non-string name", + '{"hook_event_name":"WorktreeCreate","name":5}', + ], + [ + "a non-string session_id", + '{"hook_event_name":"WorktreeCreate","name":"x","session_id":3}', + ], + ["a remove with no worktree_path", '{"hook_event_name":"WorktreeRemove"}'], + [ + "a remove with a relative worktree_path", + '{"hook_event_name":"WorktreeRemove","worktree_path":"x/y"}', + ], + ])("refuses %s", (_label, text) => { + expect(() => parseHookInput(text)).toThrow(); + }); + + it("marks a refusal as a usage error, exit 2", () => { + try { + parseHookInput("{nope"); + expect.unreachable(); + } catch (error) { + expect((error as { oclif?: { exit?: number } }).oclif?.exit).toBe(2); + } + }); +}); + +describe("resolveWorktreeName", () => { + const root = "/work/repo.worktrees"; + + it("puts a plain name directly under the worktrees directory", () => { + expect(resolveWorktreeName("feature-auth", root)).toBe( + "/work/repo.worktrees/feature-auth", + ); + }); + + it("allows a slash-separated branch name", () => { + expect(resolveWorktreeName("feat/x", root)).toBe( + "/work/repo.worktrees/feat/x", + ); + }); + + it.each([ + ["empty", ""], + ["a parent segment", "../x"], + ["an inner parent segment", "a/../../x"], + ["a current-directory segment", "a/./b"], + ["an absolute path", "/x"], + ["a leading dash", "-D"], + ["a double dot", "a..b"], + ["a newline", "a\nb"], + ["a NUL", "a\0b"], + ["a DEL", "a\u007fb"], + ["a tab", "a\tb"], + ["a space", "a b"], + ])("refuses %s", (_label, name) => { + expect(() => resolveWorktreeName(name, root)).toThrow(); + }); +}); diff --git a/src/lib/claude-hook-input.ts b/src/lib/claude-hook-input.ts new file mode 100644 index 0000000..512bcc7 --- /dev/null +++ b/src/lib/claude-hook-input.ts @@ -0,0 +1,161 @@ +import path from "node:path"; +import { z } from "zod"; +import { InvalidValueError } from "./prompt.js"; +import { isValidBranchName } from "./validators.js"; + +/** + * The input of a Claude Code worktree hook is untrusted (plan #279 D4): + * settings, plugins and `remote-control` all feed the pipe, and the remove + * event deletes. Everything here refuses with an `InvalidValueError`, which + * `BaseCommand.catch` turns into one stderr line and exit 2, before anything + * has run. + */ + +/** This plan's number: the documented inputs are a few short fields. */ +export const CLAUDE_HOOK_INPUT_MAX_BYTES = 65536; + +export type HookStdin = AsyncIterable & { isTTY?: boolean }; + +export type HookInput = + | { event: "WorktreeCreate"; name: string; sessionId: string | undefined } + | { + event: "WorktreeRemove"; + worktreePath: string; + sessionId: string | undefined; + }; + +const eventSchema = z.object({ hook_event_name: z.string() }); + +const createSchema = z.object({ + name: z.string({ error: "WorktreeCreate input needs a string `name`" }), + session_id: z.string().optional(), +}); + +const removeSchema = z.object({ + worktree_path: z + .string({ error: "WorktreeRemove input needs a string `worktree_path`" }) + .refine((value) => path.isAbsolute(value), { + error: "`worktree_path` must be an absolute path", + }), + session_id: z.string().optional(), +}); + +/** Reads stdin to the cap, as `readBriefStdin` does for `--agent-stdin`. */ +export async function readHookStdin(stdin: HookStdin): Promise { + // Reading a terminal would wait for a person who was never told to type. + if (stdin.isTTY) { + throw new InvalidValueError( + "The hook input must be piped in, but stdin is a terminal.", + ); + } + + const chunks: Buffer[] = []; + let bytes = 0; + for await (const chunk of stdin) { + const buffer = typeof chunk === "string" ? Buffer.from(chunk) : chunk; + bytes += buffer.length; + // Stops at the cap rather than buffering what will be refused anyway. + if (bytes > CLAUDE_HOOK_INPUT_MAX_BYTES) { + throw new InvalidValueError( + `The hook input is over ${CLAUDE_HOOK_INPUT_MAX_BYTES} bytes.`, + ); + } + chunks.push(buffer); + } + return Buffer.concat(chunks).toString("utf8"); +} + +function firstIssue(error: z.ZodError) { + return error.issues[0]?.message ?? "the hook input is not valid"; +} + +/** One JSON object, dispatched on `hook_event_name` (D1); unknown fields are ignored. */ +export function parseHookInput(text: string): HookInput { + let json: unknown; + try { + json = JSON.parse(text); + } catch { + throw new InvalidValueError("The hook input is not valid JSON."); + } + + const base = eventSchema.safeParse(json); + if (!base.success) { + throw new InvalidValueError( + "The hook input must be a JSON object with a string `hook_event_name`.", + ); + } + + switch (base.data.hook_event_name) { + case "WorktreeCreate": { + const input = createSchema.safeParse(json); + if (!input.success) { + throw new InvalidValueError(firstIssue(input.error)); + } + return { + event: "WorktreeCreate", + name: input.data.name, + sessionId: input.data.session_id, + }; + } + case "WorktreeRemove": { + const input = removeSchema.safeParse(json); + if (!input.success) { + throw new InvalidValueError(firstIssue(input.error)); + } + return { + event: "WorktreeRemove", + worktreePath: input.data.worktree_path, + sessionId: input.data.session_id, + }; + } + default: + throw new InvalidValueError( + `Unsupported hook event "${base.data.hook_event_name}"; expected WorktreeCreate or WorktreeRemove.`, + ); + } +} + +function hasControlCharacter(value: string) { + for (const char of value) { + const code = char.charCodeAt(0); + if (code < 0x20 || code === 0x7f) { + return true; + } + } + return false; +} + +/** + * Checks a worktree name and returns the directory it will live in, which is + * inside `worktreesRoot` (`.worktrees`) or the name is refused (D4). The + * branch rules come first; the rest closes what they allow and a path would + * not: a leading dash (read as an option), a control character, and a `.` or + * `..` segment that resolves out of, or sideways inside, the root. + */ +export function resolveWorktreeName( + name: string, + worktreesRoot: string, +): string { + const refuse = (reason: string) => + new InvalidValueError(`Invalid worktree name: ${reason}.`); + + const valid = isValidBranchName(name); + if (valid !== true) { + throw refuse(valid.replace(/^Branch name /, "").toLowerCase()); + } + if (name.startsWith("-")) { + throw refuse("it starts with a dash"); + } + if (hasControlCharacter(name)) { + throw refuse("it contains a control character"); + } + if (name.split("/").some((part) => part === "." || part === "..")) { + throw refuse("it has a `.` or `..` segment"); + } + + const target = path.resolve(worktreesRoot, name); + if (!target.startsWith(`${path.resolve(worktreesRoot)}${path.sep}`)) { + throw refuse("it does not resolve inside the worktrees directory"); + } + return target; +} From d435cd937c7302c7d9f958fc691e05dca229ed90 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Baldur=20P=C3=A1ll=20H=C3=B3lmgeirsson?= Date: Mon, 30 Nov 2026 15:56:13 +0000 Subject: [PATCH 2/8] feat(env): copy gitignored files a root .worktreeinclude matches (#279) Phase 3 of #279. Patterns in a root `.worktreeinclude` join the env-file and `copy` selection for every command that copies: a file is copied when git lists it as untracked, ignored and matching the patterns (git's own matcher, so `!` works; tracked and un-ignored files never are; node_modules stays excluded). Without the file nothing changes. Docs (env-files guide, project configuration, branch page), README and the worktree skill describe it; the Dox eval baseline was regenerated (MRR 0.719 -> 0.716). Gate 1: pnpm check, typecheck (root + docs), build, docs:build, worker:bundle-check, docs:audit-dist, test (4216 passed), docs:test (1861 passed), test-markers grep, all exit 0. Gate 2: reviewer subagent, FAIL then PASS WITH NOTES after one loopback (the `**/` difference from Claude Code was described backwards). Notes in context/notes.md. --- README.md | 2 +- context/notes.md | 12 +++ docs/evals/baseline.json | 4 +- docs/src/content/docs/commands/branch.mdx | 7 +- docs/src/content/docs/guides/env-files.mdx | 24 +++++ .../content/docs/project-configuration.mdx | 4 + skills/worktree/SKILL.md | 9 +- src/lib/env.copy.test.ts | 89 +++++++++++++++++++ src/lib/env.ts | 60 ++++++++++++- 9 files changed, 198 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index bec2e81..be44f2b 100644 --- a/README.md +++ b/README.md @@ -123,7 +123,7 @@ That will: 1. create a new branch from your configured source branch 2. add a Git worktree under `.worktrees/feature/improve-readme` -3. copy the gitignored env files from the main repository — `.env*`, `.dev.vars*` and `.envrc` — and any gitignored file `.worktree.yml` lists under `copy` +3. copy the gitignored env files from the main repository — `.env*`, `.dev.vars*` and `.envrc` — any gitignored file `.worktree.yml` lists under `copy`, and any gitignored file a root `.worktreeinclude` matches 4. install dependencies — by default when non-interactive, and on a terminal when `postCreate` is set or `--install` is given (`--no-install` skips it); the command is your `postCreate`, else the steps under `postCreate` in `.worktree.yml` (run in order, after you approve them: checked before anything is created, asked on a terminal, exit `2` with `missing_value` when nothing can be asked, so approve with `worktree config --approve` or skip with `--no-install`), else the `postCreate` steps in your user config file (no approval), else inferred from the lockfile (`pnpm-lock.yaml`, `package-lock.json`, `yarn.lock`, `bun.lock`); a failure stops the remaining steps, keeps the worktree, opens nothing and exits `1` 5. open the new worktree in your configured editor, if one is set — or as a Herdr space when `opener` is `herdr`, or as a Rex session when it is `rex`; with `auto`, in the Herdr or Rex the command runs inside, else the editor diff --git a/context/notes.md b/context/notes.md index 3f8e393..c71728e 100644 --- a/context/notes.md +++ b/context/notes.md @@ -11,3 +11,15 @@ Non-blocking observations from the gates. Branch-local; `/feature-close` deletes - Untested orderings: `--source` resolved after the fetch; D4's "one stderr line"; D2's "no opener or agent". - The postCreate refusal replaces the original `MissingValueError` without keeping it as `cause` (deliberate: its advice was wrong here). - On main, not this feature: the name containment check is textual (a symlinked dir under `.worktrees/` could escape it; `branch` shares it); `isValidBranchName` accepts some names git refuses (`a/.b`), exiting 1 instead of 2; a failing `gitListIgnoredEnvFiles` after the tree exists exits 1 without naming the tree (`env.ts:168-175`). + +## Phase 3 — `.worktreeinclude` in the copy + +- No test pins dedup (a path both env shapes/`copy` and `.worktreeinclude` select is copied once), though `envFilesCopied` is JSON contract. +- The heading switch from "env files" to "files" when `.worktreeinclude` exists is untested. +- The tracked-match test uses a file that is also not ignored; a tracked-and-ignored (`git add -f`) file would isolate "tracked is never copied". +- No test pins the `**/` behaviour (`vendor/` ignored, `**/config.json` → `vendor/x/config.json` copied). +- `env.ts`'s doc comment on the selection now sits on the merge function; `gitListIgnored` has four positional params and no comment. +- With a `.worktreeinclude`, every ignored untracked file is stat'd before the intersection; intersect first for large `target/`/`.next/`. +- Spinner and failure text still say "env files"; `env-files.mdx` "The same applies to a file named under `copy`" omits `.worktreeinclude`. +- `fs.existsSync(.worktreeinclude)` is evaluated twice (`env.ts:100`, `:234`). +- The `**/` bullet's "or is named after the `**/`" compresses Claude's "first name after `**/` is in the directory's path". diff --git a/docs/evals/baseline.json b/docs/evals/baseline.json index 0d6d502..b58bc5a 100644 --- a/docs/evals/baseline.json +++ b/docs/evals/baseline.json @@ -18,14 +18,14 @@ "metrics": { "fit.kept": 0.962, "refusal.quiet": 1, - "retrieval.mrr": 0.719, + "retrieval.mrr": 0.716, "retrieval.recallAt10": 0.888, "retrieval.withinK": 1, "vocabulary.hit": 1 }, "ranks": { "fault-every-command": [2], - "fault-long-how-to": [3], + "fault-long-how-to": [4], "follow-up-undo-that": [null], "injection-outside-link": [2], "lookup-flag-agent": [1], diff --git a/docs/src/content/docs/commands/branch.mdx b/docs/src/content/docs/commands/branch.mdx index 01797d8..43b0004 100644 --- a/docs/src/content/docs/commands/branch.mdx +++ b/docs/src/content/docs/commands/branch.mdx @@ -631,8 +631,9 @@ With `--dry-run`, steps 2 to 10 do not happen: the command stops after naming, s [Moving the issue to started](#moving-the-issue-to-started), [Moving the ClickUp task to in progress](#moving-the-clickup-task-to-in-progress) and [Moving the Jira issue to in progress](#moving-the-jira-issue-to-in-progress). A failure warns and the run carries on. -7. Copies the gitignored env files into the new worktree, and the gitignored files the project file lists - under `copy` — see [Environment Files](/worktree/guides/env-files/) and +7. Copies the gitignored env files into the new worktree, the gitignored files the project file lists + under `copy`, and the gitignored files a `.worktreeinclude` at the repository root matches — see + [Environment Files](/worktree/guides/env-files/) and [Copy files](/worktree/project-configuration/#copy-files). 8. Installs dependencies in it, when [enabled](#installing-dependencies). A failure stops here with exit `1`. 9. Opens the worktree in your configured editor (if configured), or as a Herdr space when `opener` is `herdr`, or as a Rex session when it is `rex`; with `auto`, in the Herdr or Rex the command runs inside (Herdr first if both, and only when its CLI is installed), else the editor; with `opener` `none` or `--no-open`, opens nothing and prints `Worktree created at `. @@ -680,7 +681,7 @@ person goes to stderr instead: the spinner lines, the env-file list, notes and w | `issue` | `{provider:"github", number, url}`, `{provider:"jira", key, url}`, `{provider:"linear", key, url}`, `{provider:"clickup", key, url}` or `{provider:"custom", name, key, url}` for `--issue`; `null` when no issue was used. `url` is `null` when it is not known. `name` is `issueProvider.name`, `null` when none is set, and `provider` is always the word `custom`, never the name | | `assigned` | `true` once the issue is yours (assigned, or already yours); `false` when it is not (the attempt failed, an issue is held by someone else, or Jira does not show a Jira issue's assignee); `null` when none was (no issue, `--no-assign`, a configured `false`, or a `--issue` provider that does not assign) | | `started` | `true` once the Linear issue, ClickUp task, Jira issue or `--issue` issue is in a started state (moved, or already there); `false` when it is not (left alone, no started state to move to, or the attempt failed); `null` when none was attempted (none of `--linear`, `--clickup`, `--jira` or `--issue`, `--no-start`, a configured `false`, a `--issue` provider that does not start, or a declined prompt) | -| `envFilesCopied` | the env files and `copy` files copied, relative to the repository root; `[]` when there were none | +| `envFilesCopied` | the env files, `copy` files and `.worktreeinclude` files copied, relative to the repository root; `[]` when there were none | | `installed` | `{ran:true, command, steps, from, inferred, ok}`, plus `reason` when `ok` is `false`; `{ran:false, reason}` when the step was skipped. `steps` are the commands that ran, in order, and `command` is the one that failed, else the last that ran. `from` is `"git-config"` (your `postCreate`), `"project"` (the steps in `.worktree.yml`), `"user"` (the steps in your user config file) or `"lockfile"` | | `herdr` | `{space, pane, agent}` for the Herdr space that was opened; `null` when Herdr was not opened. `agent` is Herdr's handle, `null` when no agent was started in the pane | | `rex` | `{session, block}` for the Rex session that was opened; `null` when no Rex session was opened. `block` is the session's first terminal as `rex new` reported it, `null` when the session was found instead: one that was already open, or one whose `rex new` timed out and turned up after. Whether an agent started is `agent`'s to say | diff --git a/docs/src/content/docs/guides/env-files.mdx b/docs/src/content/docs/guides/env-files.mdx index d20665b..a83162c 100644 --- a/docs/src/content/docs/guides/env-files.mdx +++ b/docs/src/content/docs/guides/env-files.mdx @@ -46,6 +46,30 @@ matched by your ignore rules. **A `copy` path must be gitignored to be copied** the new worktree, and a file git neither tracks nor ignores is left behind. These files are reported in the same list as env files, and `worktree checkout` copies them too. +### Other files, from `.worktreeinclude` + +A repository can also name files in a `.worktreeinclude` at its root, the file Claude Code reads for the same +job. It uses `.gitignore` syntax, and a file is copied only when it is **both** gitignored and matched by a +pattern in it: + +```gitignore +config/master.key +certs/*.pem +!certs/old.pem +``` + +- Git reads the patterns, so `!`, `**` and a trailing `/` mean what they mean in `.gitignore`. A `!` pattern + leaves out a file an earlier line matched. +- A tracked file is never copied, and neither is a file git neither tracks nor ignores: add it to + `.gitignore` first. +- These files join the env files and the `copy` entries in the one list, and `worktree branch`, + `worktree checkout` and `worktree claude-hook` all copy them. +- `node_modules` is still never copied. +- One difference from Claude Code: for a `**/` pattern, Claude Code skips files inside a wholly gitignored + directory unless that directory matches the pattern or is named after the `**/`. This copies every + gitignored file the pattern matches, wherever it sits: `vendor/x/config.json` for `**/config.json`, even + when `vendor/` is gitignored. + ## Check What Gets Copied Every copied file is listed by path, so the output is worth a glance: diff --git a/docs/src/content/docs/project-configuration.mdx b/docs/src/content/docs/project-configuration.mdx index 1f98c37..b9486ea 100644 --- a/docs/src/content/docs/project-configuration.mdx +++ b/docs/src/content/docs/project-configuration.mdx @@ -329,6 +329,10 @@ copy: `envFilesCopied` of the `--json` document. - **An entry that starts with `/` or `:`, or has a `..` segment, is an error** when the file is read, so a pattern cannot reach outside the repository. +- **`copy` and `.worktreeinclude` add to each other.** A `.worktreeinclude` at the repository root, in + `.gitignore` syntax, selects further gitignored files; a file either one names is copied once. `copy` lives in + this file and only globs; `.worktreeinclude` is the file Claude Code reads, with `!` patterns. See + [Environment Files](/worktree/guides/env-files/#other-files-from-worktreeinclude). - **Nothing is asked first.** Unlike steps that run commands, copying executes nothing and stays within your own clone, so no approval is needed. - **`worktree branch --dry-run` copies nothing**, like everything else it skips. diff --git a/skills/worktree/SKILL.md b/skills/worktree/SKILL.md index d945b7c..a34c11d 100644 --- a/skills/worktree/SKILL.md +++ b/skills/worktree/SKILL.md @@ -61,8 +61,8 @@ worktree branch feature/add-bulk-actions --source origin/release/1.4 Creates a branch, adds a worktree under `.worktrees/feature/add-bulk-actions`, copies the gitignored env files from the root worktree (plus any gitignored -file the project's `.worktree.yml` lists under `copy`, which `checkout` copies -too), and opens the directory +file the project's `.worktree.yml` lists under `copy` or a root +`.worktreeinclude` matches, which `checkout` copies too), and opens the directory in the configured `codeEditor` — or, when `opener` is `herdr`, as a Herdr space, or, when it is `rex`, as a Rex session, labelled with the branch name. With `opener` `auto` it opens in the Herdr or Rex the command runs inside (Herdr @@ -722,8 +722,9 @@ command stops with exit `2`: on such a user file before it does anything, on suc The file's `copy` list (relative globs such as `config/master.key`) names extra files for `branch` and `checkout` to copy with the env files. A path must be -gitignored to be copied; a tracked file never is. Copied files are listed in -`envFilesCopied`, and `branch --dry-run` copies nothing. +gitignored to be copied; a tracked file never is. A `.worktreeinclude` at the +repository root (`.gitignore` syntax, `!` allowed) adds the gitignored files it +matches in the same way. Copied files are listed in `envFilesCopied`, and `branch --dry-run` copies nothing. | Key | Example value | Required for | |---|---|---| diff --git a/src/lib/env.copy.test.ts b/src/lib/env.copy.test.ts index 818e29b..c37f1f2 100644 --- a/src/lib/env.copy.test.ts +++ b/src/lib/env.copy.test.ts @@ -133,6 +133,95 @@ describe("copyEnvFilesFromRootPath — copy patterns, against a real repository" }); }); +// #279 Phase 3 (D8): a file is copied when it is gitignored AND matches a +// pattern in the root `.worktreeinclude`, Claude Code's rule (worktrees.md, +// "Copy gitignored files into worktrees"). Expected values are that rule's +// own wording, not read back from the implementation. +describe("copyEnvFilesFromRootPath — .worktreeinclude, against a real repository", () => { + it("copies and lists a gitignored file that matches a pattern", async () => { + write(repo, ".gitignore", "config/master.key\n"); + write(repo, ".worktreeinclude", "config/master.key\n"); + write(repo, "config/master.key", "abc123"); + + const copied = await copyEnvFilesFromRootPath(destination); + + expect(copied).toEqual(["config/master.key"]); + expect( + fs.readFileSync(path.join(destination, "config/master.key"), "utf8"), + ).toBe("abc123"); + }); + + it("does not copy a tracked file that matches a pattern", async () => { + write(repo, ".worktreeinclude", "config/master.key\n"); + write(repo, "config/master.key"); + git("add", "config/master.key"); + git("commit", "-q", "-m", "track it"); + + expect(await copyEnvFilesFromRootPath(destination)).toEqual([]); + expect(fs.existsSync(path.join(destination, "config/master.key"))).toBe( + false, + ); + }); + + it("does not copy an untracked file that is not gitignored", async () => { + write(repo, ".worktreeinclude", "config/master.key\n"); + write(repo, "config/master.key"); + + expect(await copyEnvFilesFromRootPath(destination)).toEqual([]); + }); + + it("does not copy a gitignored file no pattern names", async () => { + write(repo, ".gitignore", "*.key\n"); + write(repo, ".worktreeinclude", "a.key\n"); + write(repo, "a.key"); + write(repo, "b.key"); + + expect(await copyEnvFilesFromRootPath(destination)).toEqual(["a.key"]); + }); + + it("lets a ! pattern exclude a file an earlier pattern matched", async () => { + write(repo, ".gitignore", "*.key\n"); + write(repo, ".worktreeinclude", "*.key\n!b.key\n"); + write(repo, "a.key"); + write(repo, "b.key"); + + expect(await copyEnvFilesFromRootPath(destination)).toEqual(["a.key"]); + }); + + it("copies nothing under node_modules, whatever the pattern", async () => { + write(repo, ".gitignore", "node_modules/\n*.key\n"); + write(repo, ".worktreeinclude", "**/*.key\n"); + write(repo, "node_modules/dep/x.key"); + write(repo, "config/master.key"); + + expect(await copyEnvFilesFromRootPath(destination)).toEqual([ + "config/master.key", + ]); + }); + + it("joins the env files and the copy patterns in one list", async () => { + write(repo, ".gitignore", ".env\n*.key\n*.pem\n"); + write(repo, ".worktreeinclude", "*.key\n"); + write(repo, ".env"); + write(repo, "a.key"); + write(repo, "c.pem"); + + const copied = await copyEnvFilesFromRootPath(destination, { + copy: ["c.pem"], + }); + + expect(copied.sort()).toEqual([".env", "a.key", "c.pem"]); + }); + + it("treats an empty .worktreeinclude as no patterns", async () => { + write(repo, ".gitignore", "*.key\n"); + write(repo, ".worktreeinclude", ""); + write(repo, "a.key"); + + expect(await copyEnvFilesFromRootPath(destination)).toEqual([]); + }); +}); + // #202: git lists a gitignored nested repository as one directory entry ending // in `/`, and the pathspecs do not filter it. Expected values are the real // files only: `.env` and the `.dev.vars` beside the nested repositories. diff --git a/src/lib/env.ts b/src/lib/env.ts index 269f3ae..afc31b4 100644 --- a/src/lib/env.ts +++ b/src/lib/env.ts @@ -30,6 +30,13 @@ const ENV_FILE_PATHSPECS = [ */ const NODE_MODULES_PATHSPEC = ":(glob,exclude)**/node_modules/**"; +/** + * The root file whose gitignore-syntax patterns choose more files to copy. It + * is Claude Code's name and rule: a file is copied when it is gitignored *and* + * matches a pattern here. + */ +const WORKTREEINCLUDE_FILE = ".worktreeinclude"; + /** * Whether copyFileSync can copy this path as a file. A link to nothing (ENOENT) * or a link loop (ELOOP) is not one. Any other stat error keeps the path, so @@ -71,6 +78,49 @@ function isRegularFile(filePath: string) { async function gitListIgnoredEnvFiles( gitRootPath: string, copyPatterns: readonly string[], +) { + const [selected, included] = await Promise.all([ + gitListIgnored(gitRootPath, copyPatterns), + gitListWorktreeInclude(gitRootPath), + ]); + const seen = new Set(selected); + return [...selected, ...included.filter((entry) => !seen.has(entry))]; +} + +/** + * The files `.worktreeinclude` selects: gitignored, and matching its patterns. + * + * git parses the patterns, so gitignore syntax (`!`, `**`, a trailing `/`) is + * git's rather than ours. `--exclude-from` alone lists the untracked files the + * patterns match, which is not yet "and ignored"; the intersection with what + * git ignores on its own is what keeps a tracked file, or an untracked one + * nobody ignored, out. Without the file there is nothing to ask git. + */ +async function gitListWorktreeInclude(gitRootPath: string) { + if (!fs.existsSync(path.join(gitRootPath, WORKTREEINCLUDE_FILE))) { + return []; + } + const [matching, ignored] = await Promise.all([ + gitListFiles(gitRootPath, [`--exclude-from=${WORKTREEINCLUDE_FILE}`]), + gitListFiles(gitRootPath, ["--exclude-standard"]), + ]); + const ignoredSet = new Set(ignored); + return matching.filter((entry) => ignoredSet.has(entry)); +} + +/** + * `ls-files --others --ignored` under `excludeArgs`, with `node_modules` out + * and the nested-repository and broken-link entries dropped, as below. + */ +function gitListFiles(gitRootPath: string, excludeArgs: readonly string[]) { + return gitListIgnored(gitRootPath, [], excludeArgs, []); +} + +async function gitListIgnored( + gitRootPath: string, + copyPatterns: readonly string[], + excludeArgs: readonly string[] = ["--exclude-standard"], + envPathspecs: readonly string[] = ENV_FILE_PATHSPECS, ) { const result = await run( "git", @@ -78,10 +128,10 @@ async function gitListIgnoredEnvFiles( "ls-files", "--others", "--ignored", - "--exclude-standard", + ...excludeArgs, "-z", "--", - ...ENV_FILE_PATHSPECS, + ...envPathspecs, ...copyPatterns.map((pattern) => `:(glob)${pattern}`), NODE_MODULES_PATHSPEC, ], @@ -179,7 +229,11 @@ export async function copyEnvFilesFromRootPath( // env file someone expected looks identical to one that never needed any, and // this line is what separates "none found" from "the copy never ran". // With patterns the list is no longer only env files, so it says "files". - const noun = copy.length > 0 ? "file" : "env file"; + const noun = + copy.length > 0 || + fs.existsSync(path.join(gitRootPath, WORKTREEINCLUDE_FILE)) + ? "file" + : "env file"; if (envFiles.length === 0) { say(`No ${noun}s to copy from ${gitRootPath}`); return []; From 6b6ee00790ce3cbcdd75d1647b74cdbed8ef0a5b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Baldur=20P=C3=A1ll=20H=C3=B3lmgeirsson?= Date: Mon, 30 Nov 2026 16:12:40 +0000 Subject: [PATCH 3/8] feat(claude-hook): WorktreeRemove deletes only when nothing would be lost (#279) Phase 2 of #279. `worktree claude-hook` now handles WorktreeRemove: it matches `worktree_path` by realpath against this repository's listed worktrees under `.worktrees/`, and removes one with `git worktree remove` (never --force) and `git branch -D`, run from the main checkout, only when it has no uncommitted or untracked changes, nothing unmerged ahead, and no blocking agent session other than the caller's. Otherwise it exits 1 naming the reasons and `worktree remove -f`. A directory already gone exits 0. The predicate `losesNothingOnRemove` sits beside `isSafeToRemove`; cleanup is unchanged. Gate 1: pnpm check, typecheck (root + docs), build, docs:build, worker:bundle-check, docs:audit-dist, test (4249 passed), docs:test (1861 passed), test-markers grep, all exit 0. Gate 2: reviewer subagent, FAIL then PASS WITH NOTES after one loopback (the caller's own session was named as "another session"; a second blocking session behind the caller's own was missed). Notes in context/notes.md. --- context/notes.md | 11 ++ src/commands/claude-hook.test.ts | 290 ++++++++++++++++++++++++++++++- src/commands/claude-hook.ts | 138 ++++++++++++++- src/lib/git.test.ts | 143 +++++++++++++++ src/lib/git.ts | 57 ++++-- 5 files changed, 613 insertions(+), 26 deletions(-) diff --git a/context/notes.md b/context/notes.md index c71728e..8d86b70 100644 --- a/context/notes.md +++ b/context/notes.md @@ -23,3 +23,14 @@ Non-blocking observations from the gates. Branch-local; `/feature-close` deletes - Spinner and failure text still say "env files"; `env-files.mdx` "The same applies to a file named under `copy`" omits `.worktreeinclude`. - `fs.existsSync(.worktreeinclude)` is evaluated twice (`env.ts:100`, `:234`). - The `**/` bullet's "or is named after the `**/`" compresses Claude's "first name after `**/` is in the directory's path". + +## Phase 2 — `WorktreeRemove` + +- The hook gates the delete on `risks.length > 0`, not on `losesNothingOnRemove` directly; they agree today, but a drift in `describeRisks` would delete a refused tree. +- The hook's "untracked files" row is the same input as the uncommitted row; the real pin is `git.test.ts` counting `?? c.ts` (on main). `git worktree remove` without `--force` is a second guard. +- "ahead of its base" is counted against `@{u}` where an upstream exists; "upstream or base" would be accurate. +- Untested: a detached HEAD target (the `-f` hint names the path); a `prunable` entry whose directory is still on disk (pruned and `branch -D`'d, directory left). +- If `branch -D` fails after `git worktree remove` succeeded, the message still says git refused to remove the worktree. +- `removeCalls`' `args?.[0] === "prune"` can never match (dead, harmless). +- The re-scan's realpath step is untested (test paths are already real); sessions with no `sessionId` count as "other" and refuse (fails safe); a failed session listing reads as no sessions, as in the gather. +- On main: a gone directory under a symlinked prefix is compared as written, so the hook exits 1 instead of 0 (fails safe). diff --git a/src/commands/claude-hook.test.ts b/src/commands/claude-hook.test.ts index 307234d..f6be361 100644 --- a/src/commands/claude-hook.test.ts +++ b/src/commands/claude-hook.test.ts @@ -5,16 +5,19 @@ import { realpathSync, rmSync, symlinkSync, + writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { Readable } from "node:stream"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import * as agent from "../lib/agent.js"; import * as gitConfig from "../lib/config.js"; import { copyEnvFilesFromRootPath } from "../lib/env.js"; import * as git from "../lib/git.js"; import { runInstall } from "../lib/install.js"; import { resetProjectConfigCache } from "../lib/project-config.js"; +import type { WorktreeListEntry } from "../lib/types.js"; import { captureOutput, expectCommands, @@ -201,13 +204,6 @@ describe("claude-hook command", () => { ["a double dot", create("a..b")], ["a control character", create("a\u0007b")], ["an unknown event", JSON.stringify({ hook_event_name: "Stop" })], - [ - "a WorktreeRemove (Phase 2)", - JSON.stringify({ - hook_event_name: "WorktreeRemove", - worktree_path: "/x", - }), - ], ["input over the cap", create("x", { pad: "y".repeat(70000) })], ])("%s", async (_label, stdin) => { await runHook(stdin); @@ -336,6 +332,286 @@ describe("claude-hook command", () => { }); }); + describe("WorktreeRemove (Phase 2)", () => { + // Expected values: §4.1's remove column and D5/D6 of plan #279, never the + // command's own output. + let worktree: string; + let main: string; + + const remove = ( + worktreePath: unknown, + extra: Record = {}, + ) => + JSON.stringify({ + hook_event_name: "WorktreeRemove", + worktree_path: worktreePath, + ...extra, + }); + + const entry = (overrides: Partial = {}) => + ({ + path: worktree, + branchName: "feat", + remote: "", + ahead: 0, + uncommittedChanges: 0, + pathExists: true, + isCurrent: false, + ...overrides, + }) as WorktreeListEntry; + + const listed = (...entries: WorktreeListEntry[]) => + vi.spyOn(git, "gitGetWorktreeList").mockResolvedValue(entries); + + const removeCalls = () => + mockRun.mock.calls.filter( + ([, args]) => + args?.[0] === "branch" || + args?.[0] === "worktree" || + args?.[0] === "prune", + ); + + const kept = (reason: string | RegExp) => { + expect(process.exitCode).toBe(1); + expect(output.stdout()).toBe(""); + expect(output.stderr()).toMatch(reason); + expect(output.stderr()).toContain("worktree remove feat -f"); + expect(removeCalls()).toEqual([]); + }; + + beforeEach(() => { + worktree = join(realpathSync(worktreesRoot), "feat"); + mkdirSync(worktree, { recursive: true }); + writeFileSync(join(worktree, ".git"), "gitdir: /x\n"); + main = realpathSync(sandbox); + vi.spyOn(git, "gitGetRootPath").mockResolvedValue(main); + vi.spyOn(agent, "getAgentSessions").mockResolvedValue([]); + expectCommands( + `git worktree remove ${worktree}`, + `git worktree remove ${worktree} --force`, + "git worktree prune", + "git branch -D feat", + ); + }); + + it("removes a clean worktree without --force, then its branch, prints nothing", async () => { + listed(entry()); + + await runHook(remove(worktree, { session_id: "mine" })); + + expect(process.exitCode).toBeUndefined(); + expect(output.stdout()).toBe(""); + expect(removeCalls()).toEqual([ + ["git", ["worktree", "remove", worktree], { cwd: main }], + ["git", ["branch", "-D", "feat"], { cwd: main }], + ]); + }); + + it("lists the worktrees from the main checkout's view, the current one included, with sessions", async () => { + const list = listed(entry()); + + await runHook(remove(worktree)); + + expect(list).toHaveBeenCalledWith({ + includeCurrent: true, + includeAgents: true, + }); + }); + + it("runs the removal from the main checkout when the process cwd is inside the worktree", async () => { + listed(entry()); + const home = process.cwd(); + const config = await loadConfig(); + process.chdir(worktree); + try { + pipe(remove(worktree)); + const command = new ClaudeHook([], config); + (command as any).parse = vi + .fn() + .mockResolvedValue({ args: {}, flags: {} }); + (command as any).parsed = true; + await (command as any)._run(); + } finally { + process.chdir(home); + } + + expect(process.exitCode).toBeUndefined(); + expect(removeCalls()).toEqual([ + ["git", ["worktree", "remove", worktree], { cwd: main }], + ["git", ["branch", "-D", "feat"], { cwd: main }], + ]); + }); + + it.each([ + ["uncommitted changes", { uncommittedChanges: 2 }, /uncommitted/], + [ + "untracked files (counted with the changes by git status -s)", + { uncommittedChanges: 1 }, + /uncommitted/, + ], + ["an unmerged ahead", { ahead: 3 }, /3 commits/], + [ + "an ahead that was not counted", + { + ahead: undefined, + aheadUnknownReason: "origin/main could not be resolved", + }, + /could not be counted/, + ], + [ + "another blocking session", + { agent: { name: "claude", sessionId: "theirs", live: true } }, + /session/, + ], + ])("keeps the worktree and branch with %s, exit 1", async (_l, overrides, reason) => { + listed(entry(overrides as Partial)); + + await runHook(remove(worktree, { session_id: "mine" })); + + kept(reason); + }); + + it("is not blocked by the caller's own session", async () => { + listed( + entry({ agent: { name: "claude", sessionId: "mine", live: true } }), + ); + + await runHook(remove(worktree, { session_id: "mine" })); + + expect(process.exitCode).toBeUndefined(); + expect(removeCalls()).toHaveLength(2); + }); + + it("does not call the caller's own session another one when changes keep the worktree", async () => { + listed( + entry({ + uncommittedChanges: 2, + agent: { name: "claude", sessionId: "mine", live: true }, + }), + ); + + await runHook(remove(worktree, { session_id: "mine" })); + + kept(/uncommitted/); + expect(output.stderr()).not.toContain("another session"); + }); + + // D6: "no blocking agent session other than the caller's", even when the + // entry's one session slot holds the caller's own. + it("keeps the worktree when another blocking session shares it with the caller's own", async () => { + const own = { name: "claude", sessionId: "mine", live: true }; + listed(entry({ agent: own })); + vi.spyOn(agent, "getAgentSessions").mockResolvedValue([ + { name: "claude", sessionId: "mine", cwd: worktree }, + { name: "other-claude", sessionId: "theirs", cwd: worktree }, + ]); + + await runHook(remove(worktree, { session_id: "mine" })); + + kept(/another session \(other-claude\)/); + }); + + it("removes when the only other session in the worktree is idle", async () => { + listed( + entry({ agent: { name: "claude", sessionId: "mine", live: true } }), + ); + vi.spyOn(agent, "getAgentSessions").mockResolvedValue([ + { name: "claude", sessionId: "mine", cwd: worktree }, + { name: "idle", sessionId: "theirs", cwd: worktree, status: "idle" }, + ]); + + await runHook(remove(worktree, { session_id: "mine" })); + + expect(process.exitCode).toBeUndefined(); + expect(removeCalls()).toHaveLength(2); + }); + + it("removes a merged branch whose ahead is not zero", async () => { + listed(entry({ ahead: 4, mergedInto: "origin/main" })); + + await runHook(remove(worktree)); + + expect(process.exitCode).toBeUndefined(); + expect(removeCalls()).toHaveLength(2); + }); + + it.each([ + ["the main checkout", () => main], + ["a path outside the worktrees directory", () => "/etc"], + ["a sibling `.worktrees-old/x`", () => `${main}.worktrees-old/x`], + ])("does not touch %s: exit 1, nothing deleted", async (_l, target) => { + listed(entry()); + + await runHook(remove(target())); + + expect(process.exitCode).toBe(1); + expect(output.stdout()).toBe(""); + expect(output.stderr()).toContain("not a worktree"); + expect(removeCalls()).toEqual([]); + }); + + it("exits 2 for a relative worktree_path, with nothing run", async () => { + const list = listed(entry()); + + await runHook(remove("feat")); + + expect(process.exitCode).toBe(2); + expect(output.stdout()).toBe(""); + expect(output.stderr()).not.toBe(""); + expect(list).not.toHaveBeenCalled(); + expect(removeCalls()).toEqual([]); + }); + + it("matches a symlink to a listed worktree by its real path", async () => { + listed(entry()); + const link = join( + mkdtempSync(join(tmpdir(), "claude-hook-ln-")), + "alias", + ); + symlinkSync(worktree, link); + + await runHook(remove(link)); + + expect(process.exitCode).toBeUndefined(); + expect(removeCalls()).toHaveLength(2); + }); + + it("exits 0 with no git write when the directory is already gone", async () => { + listed(entry({ pathExists: false, ahead: undefined })); + rmSync(worktree, { recursive: true }); + + await runHook(remove(worktree)); + + expect(process.exitCode).toBeUndefined(); + expect(output.stdout()).toBe(""); + expect(removeCalls()).toEqual([]); + }); + + it("exits 1 with git's reason when git refuses", async () => { + listed(entry()); + mockRun.mockImplementation(async (_file: string, args?: string[]) => { + if (args?.[0] === "worktree") { + throw Object.assign(new Error("Command failed"), { + stderr: "fatal: cannot remove a locked working tree\n", + }); + } + return ""; + }); + + await runHook(remove(worktree)); + + expect(process.exitCode).toBe(1); + expect(output.stdout()).toBe(""); + expect(output.stderr()).toContain("cannot remove a locked working tree"); + expect(output.stderr()).toContain("worktree remove feat -f"); + expect(mockRun).not.toHaveBeenCalledWith( + "git", + ["branch", "-D", "feat"], + expect.anything(), + ); + }); + }); + describe("visibility (g)", () => { it("is not listed by `worktree --help`, though a listed command is", async () => { // oclif's help filters on each command's `hidden` (D9); ours is read from diff --git a/src/commands/claude-hook.ts b/src/commands/claude-hook.ts index 8ae0236..c93fa26 100644 --- a/src/commands/claude-hook.ts +++ b/src/commands/claude-hook.ts @@ -1,5 +1,11 @@ import { realpathSync } from "node:fs"; import { Flags } from "@oclif/core"; +import { + findSessionForPath, + getAgentSessions, + isSessionBlocking, + toRealPath, +} from "../lib/agent.js"; import { BaseCommand } from "../lib/base-command.js"; import { parseHookInput, @@ -9,11 +15,19 @@ import { import { run } from "../lib/cli.js"; import { copyEnvFilesFromRootPath } from "../lib/env.js"; import { + DETACHED_LABEL, + findWorktreeByTarget, gitCreateWorktree, gitFetch, gitFindBranchCheckout, gitGetAbsoluteWorktreesPath, gitGetLocalBranches, + gitGetRootPath, + gitGetWorktreeList, + gitNukeWorktreeCmd, + hasLiveAgent, + losesNothingOnRemove, + toGitReason, } from "../lib/git.js"; import { runInstall } from "../lib/install.js"; import { @@ -22,12 +36,13 @@ import { loadProjectConfig, } from "../lib/project-config.js"; import { InvalidValueError, MissingValueError } from "../lib/prompt.js"; +import type { WorktreeListEntry } from "../lib/types.js"; export default class ClaudeHook extends BaseCommand { // D9: kept out of `worktree --help` until its docs land (Phase 4). static override hidden = true; static override description = - `The command behind Claude Code's WorktreeCreate hook: reads the hook's JSON from stdin and creates a worktree. + `The command behind Claude Code's WorktreeCreate and WorktreeRemove hooks: reads the hook's JSON from stdin and creates or removes a worktree. WorktreeCreate reads "name" from stdin, plus --source from the command line. It creates the branch "name" like \`worktree branch\` without its prompts, @@ -35,10 +50,19 @@ issue lookup and opener, or reopens the worktree that name already has. Stdout is the worktree's real path, one line, and empty on failure; the spinner, the env-file report and everything else go to stderr. +WorktreeRemove reads "worktree_path" and "session_id". It removes only a +worktree git lists for this repository under .worktrees/, and only +when nothing would be lost: no uncommitted or untracked changes, no commits +that exist nowhere else, no other agent session working in it (the caller's +own session does not count). Then it deletes the worktree and its branch. +Anything else is kept and the reason is on stderr, with the \`worktree remove + -f\` that discards it. Stdout is always empty. + Exit codes: -0 created, or reopened -1 git, copy or install failed (a worktree that was made is kept and its path -named on stderr) +0 created, reopened, removed, or the directory was already gone +1 create: git, copy or install failed (a worktree that was made is kept and +its path named on stderr). remove: not a worktree of this repository, would +lose work, or git refused 2 bad input, a --source that is not a commit, an unapproved postCreate, or a name taken by a branch with no worktree or a checkout elsewhere`; static override examples = [ @@ -56,11 +80,9 @@ name taken by a branch with no worktree or a checkout elsewhere`; public async run(): Promise { const { flags } = await this.parse(ClaudeHook); const input = parseHookInput(await readHookStdin(process.stdin)); - if (input.event !== "WorktreeCreate") { - // Phase 2 adds remove; until then it is refused like an unknown event. - throw new InvalidValueError( - `The ${input.event} hook event is not supported yet.`, - ); + if (input.event === "WorktreeRemove") { + await this.removeWorktree(input.worktreePath, input.sessionId); + return; } const name = input.name; @@ -111,6 +133,72 @@ name taken by a branch with no worktree or a checkout elsewhere`; this.log(realpathSync(projectPath)); } + /** + * D5 and D6: only a worktree git lists under `.worktrees/`, and only + * when nothing would be lost. The list is gathered with the current worktree + * kept, since the hook usually runs inside the one it removes, and git is + * run from the main checkout, since that directory is about to go. + */ + private async removeWorktree( + worktreePath: string, + sessionId: string | undefined, + ) { + const root = await gitGetRootPath(); + const worktrees = await gitGetWorktreeList({ + includeCurrent: true, + includeAgents: true, + }); + const worktree = findWorktreeByTarget(worktrees, worktreePath); + if (!worktree) { + this.error( + `${worktreePath} is not a worktree of this repository under ${root}.worktrees/, so nothing was removed. Check the path Claude Code passed, or list this repository's worktrees with \`worktree list\`.`, + { exit: 1 }, + ); + } + + // Nothing is left to delete; the record and branch are for `remove` and + // `cleanup` to clear. + if (!worktree.pathExists && !worktree.prunable) { + return; + } + + const target = + worktree.branchName === DETACHED_LABEL + ? worktree.path + : worktree.branchName; + const risks = describeRisks(worktree, sessionId); + // The entry holds one session, and when that is the caller's own another + // blocking one may sit behind it (D6): look again without the caller's. + if ( + risks.length === 0 && + sessionId !== undefined && + worktree.agent?.sessionId === sessionId + ) { + const others = (await getAgentSessions()).filter( + (session) => session.sessionId !== sessionId, + ); + const other = findSessionForPath(others, await toRealPath(worktree.path)); + if (other && isSessionBlocking(other)) { + risks.push(`another session (${other.name}) is working in it`); + } + } + if (risks.length > 0) { + this.error( + `Kept the worktree ${target} at ${worktree.path}: ${risks.join("; ")}. Nothing was removed. If that work is not needed, run \`worktree remove ${target} -f\`.`, + { exit: 1 }, + ); + } + + try { + await gitNukeWorktreeCmd(worktree, { cwd: root }); + } catch (error) { + this.error( + `Git refused to remove the worktree ${target} at ${worktree.path}: ${toGitReason(error)}. Fix that, or run \`worktree remove ${target} -f\` to discard it.`, + { exit: 1 }, + ); + } + } + /** * D3: a name that already has a worktree under `.worktrees/` is * reopened — its path is the answer and nothing is copied or installed. The @@ -159,3 +247,35 @@ name taken by a branch with no worktree or a checkout elsewhere`; return source; } } + +/** Why `losesNothingOnRemove` says no, in words; empty when it says yes. */ +function describeRisks(worktree: WorktreeListEntry, sessionId?: string) { + if (losesNothingOnRemove(worktree, sessionId)) { + return []; + } + const risks: string[] = []; + if (worktree.uncommittedChanges === undefined) { + risks.push("its uncommitted changes could not be counted"); + } else if (worktree.uncommittedChanges > 0) { + risks.push( + `it has ${worktree.uncommittedChanges} uncommitted or untracked change${worktree.uncommittedChanges > 1 ? "s" : ""}`, + ); + } + if (worktree.ahead === undefined && !worktree.mergedInto) { + risks.push( + `its unpushed commits could not be counted${worktree.aheadUnknownReason ? ` (${worktree.aheadUnknownReason})` : ""}`, + ); + } else if (worktree.ahead && !worktree.mergedInto) { + risks.push( + `it is ${worktree.ahead} commit${worktree.ahead > 1 ? "s" : ""} ahead of its base and not merged`, + ); + } + if ( + hasLiveAgent(worktree) && + worktree.agent && + worktree.agent.sessionId !== sessionId + ) { + risks.push(`another session (${worktree.agent.name}) is working in it`); + } + return risks; +} diff --git a/src/lib/git.test.ts b/src/lib/git.test.ts index c9c4421..35972de 100644 --- a/src/lib/git.test.ts +++ b/src/lib/git.test.ts @@ -34,6 +34,7 @@ import { gitRenameWorktree, gitResolveOriginHead, isSafeToRemove, + losesNothingOnRemove, } from "./git.js"; import { setNonInteractive } from "./interaction.js"; import * as issueLink from "./issue-link.js"; @@ -713,6 +714,127 @@ describe("gitCreateWorktree", () => { }); }); +// Plan #279 D6: the hook's predicate. Each expected value is D6's own wording +// ("no uncommitted or untracked changes; `ahead` was counted and is 0, or the +// branch is `mergedInto` its base; no blocking agent session other than the +// caller's"), never what the function returned. +describe("losesNothingOnRemove", () => { + function entry( + overrides: Partial = {}, + ): WorktreeListEntry { + return { + path: "/repo/project.worktrees/test", + branchName: "feature/test", + pathExists: true, + remote: "", + ahead: 0, + uncommittedChanges: 0, + ...overrides, + }; + } + + function session(overrides: Partial = {}): WorktreeAgent { + return { + name: "claude", + pid: 9187, + sessionId: "theirs", + live: true, + ...overrides, + }; + } + + it("holds for a clean worktree with a counted zero and no session", () => { + expect(losesNothingOnRemove(entry())).toBe(true); + }); + + // `git status -s` lists untracked files, so one count carries both of D6's + // "uncommitted or untracked" clauses. + it("fails on uncommitted or untracked changes", () => { + expect(losesNothingOnRemove(entry({ uncommittedChanges: 1 }))).toBe(false); + }); + + it("fails when the change count was not taken", () => { + expect(losesNothingOnRemove(entry({ uncommittedChanges: undefined }))).toBe( + false, + ); + }); + + it("fails on commits ahead that are not merged", () => { + expect(losesNothingOnRemove(entry({ ahead: 2 }))).toBe(false); + }); + + it("holds on commits ahead when the branch is merged into its base", () => { + expect( + losesNothingOnRemove(entry({ ahead: 2, mergedInto: "origin/main" })), + ).toBe(true); + }); + + it("fails when ahead was never counted", () => { + expect( + losesNothingOnRemove( + entry({ ahead: undefined, aheadUnknownReason: "no comparison base" }), + ), + ).toBe(false); + }); + + // D6 sets this apart from `isSafeToRemove`, which keeps a pushed branch on a + // live remote: only the new predicate lets it go, because `ahead` is 0. + it("holds for a pushed branch on a live remote, where isSafeToRemove does not", () => { + const pushed = entry({ remote: "origin/feature/test", remoteExists: true }); + expect(isSafeToRemove(pushed)).toBe(false); + expect(losesNothingOnRemove(pushed)).toBe(true); + }); + + it("fails on another blocking session", () => { + expect(losesNothingOnRemove(entry({ agent: session() }), "mine")).toBe( + false, + ); + }); + + it("fails on a session that records no id", () => { + expect( + losesNothingOnRemove( + entry({ agent: session({ sessionId: undefined }) }), + "mine", + ), + ).toBe(false); + }); + + it("fails on a session when the caller named none", () => { + expect(losesNothingOnRemove(entry({ agent: session() }))).toBe(false); + }); + + it("holds when the only blocking session is the caller's own", () => { + expect( + losesNothingOnRemove( + entry({ agent: session({ sessionId: "mine" }) }), + "mine", + ), + ).toBe(true); + }); + + it("holds when the other session is idle or finished", () => { + expect( + losesNothingOnRemove( + entry({ agent: session({ blocks: false }) }), + "mine", + ), + ).toBe(true); + expect( + losesNothingOnRemove(entry({ agent: session({ live: false }) }), "mine"), + ).toBe(true); + }); + + it("still fails on the caller's own session when work is at risk", () => { + expect( + losesNothingOnRemove( + entry({ agent: session({ sessionId: "mine" }), uncommittedChanges: 3 }), + "mine", + ), + ).toBe(false); + }); +}); + describe("gitNukeWorktreeCmd", () => { const branchName = "feature/test"; // Deliberately unlike the branch name: the remove has to take the path and @@ -731,6 +853,27 @@ describe("gitNukeWorktreeCmd", () => { ); }); + // The hook removes the worktree its own process sits in; both commands then + // have to run from a directory that survives it. + it("runs both commands from the given cwd", async () => { + const runSpy = vi.spyOn(cli, "run").mockResolvedValue(""); + + await gitNukeWorktreeCmd(target, { cwd: "/repo/project" }); + + expect(runSpy).toHaveBeenNthCalledWith( + 1, + "git", + ["worktree", "remove", worktreePath], + { cwd: "/repo/project" }, + ); + expect(runSpy).toHaveBeenNthCalledWith( + 2, + "git", + ["branch", "-D", branchName], + { cwd: "/repo/project" }, + ); + }); + // A prune here would also drop the record of every other worktree whose // directory is gone, and the next `remove` in a cleanup run would fail on it // (#214). diff --git a/src/lib/git.ts b/src/lib/git.ts index e3a9506..388e8f2 100644 --- a/src/lib/git.ts +++ b/src/lib/git.ts @@ -509,6 +509,36 @@ export function isSafeToRemove(wt: WorktreeListEntry): boolean { ); } +/** + * Plan #279 D6: the verdict behind Claude Code's `WorktreeRemove` hook, which + * deletes only where nothing would be lost. Stricter than `isSafeToRemove`, + * which is cleanup's *stale* verdict and keeps a pushed branch on a live + * remote: here the branch is deleted with the worktree, so its commits must be + * counted as zero ahead or be merged into the base. Unknown is never safe, for + * the change count as for `ahead`. `git status -s` lists untracked files, so + * the one count covers uncommitted and untracked alike. + * + * The caller's own session does not block: Claude Code is the one asking, from + * inside the worktree. `hasLiveAgent` already leaves an idle session out. An + * entry carries one session, and `findSessionForPath` may pick the caller's own + * when another blocking one shares the worktree, so a caller that names its + * session must look for the others itself (`claude-hook` does). + */ +export function losesNothingOnRemove( + wt: WorktreeListEntry, + ownSessionId?: string, +): boolean { + if (wt.uncommittedChanges !== 0) { + return false; + } + if (!carriesNoKnownWork(wt)) { + return false; + } + const own = + ownSessionId !== undefined && wt.agent?.sessionId === ownSessionId; + return !hasLiveAgent(wt) || own; +} + interface GitGetWorktreeListOptions extends GitGetWorktreesOptions { includeAgents?: boolean; includeChurn?: boolean; @@ -926,6 +956,12 @@ type WorktreeTarget = Pick; interface GitNukeWorktreeCmdOptions { force?: boolean; + /** + * Where both git commands run. Unset, the process's own directory, which is + * wrong for a caller standing inside the worktree it removes: the second + * command could not start in a directory that no longer exists. + */ + cwd?: string; } // Sequential awaits stand in for the `&&` chain: a rejection stops the sequence @@ -945,26 +981,27 @@ interface GitNukeWorktreeCmdOptions { // (#214). A worktree whose directory is already gone is pruned instead. export async function gitNukeWorktreeCmd( { branchName, path }: WorktreeTarget, - { force = false }: GitNukeWorktreeCmdOptions = {}, + { force = false, cwd }: GitNukeWorktreeCmdOptions = {}, ) { + // Third argument only when given, so every other caller's call is unchanged. + const at = cwd === undefined ? [] : [{ cwd }]; // A directory without its `.git` file is not a working tree git can remove, // so it is pruned like a missing one. The directory is left where it is. if (fs.existsSync(path) && fs.existsSync(`${path}/.git`)) { - await run("git", [ - "worktree", - "remove", - path, - ...(force ? ["--force"] : []), - ]); + await run( + "git", + ["worktree", "remove", path, ...(force ? ["--force"] : [])], + ...at, + ); } else { // The directory is already gone, and an earlier prune in the same run may // already have dropped git's record of it, in which case `remove` refuses // with "is not a working tree". Pruning drops the record either way, which // is what frees the branch for the delete below. - await run("git", ["worktree", "prune"]); + await run("git", ["worktree", "prune"], ...at); } if (branchName !== DETACHED_LABEL) { - await run("git", ["branch", "-D", branchName]); + await run("git", ["branch", "-D", branchName], ...at); } } @@ -1014,7 +1051,7 @@ export function findWorktreeByTarget( * What git said when a command failed: its stderr on one line, or Node's own * message when there is none. execFile puts the captured stderr on the error. */ -function toGitReason(error: unknown): string { +export function toGitReason(error: unknown): string { const stderr = error instanceof Error && "stderr" in error && From 440542117c28e1347d4f202cc0f383151811e26c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Baldur=20P=C3=A1ll=20H=C3=B3lmgeirsson?= Date: Mon, 30 Nov 2026 16:31:31 +0000 Subject: [PATCH 4/8] feat(claude-hook): document the Claude Code hooks and un-hide the command (#279) Phase 4 of #279. `worktree claude-hook` is listed in `worktree --help`. A new docs page, commands/claude-hook, gives the settings JSON for WorktreeCreate and WorktreeRemove with a raised timeout, both contracts and exit codes, how it differs from Claude Code's defaults, when remove refuses, and the Claude Code pages (as of 2026-11-30) it follows. The commands index, FAQ, cleanup page, README and the worktree skill point at it. Every pinned page count moves 29 -> 30; the Dox routes are regenerated and the eval baseline rewritten (refusal.quiet 1, retrieval.mrr 0.716 -> 0.682 from corpus growth). Gate 1: pnpm check, typecheck (root + docs), build, docs:build, worker:bundle-check, docs:audit-dist (on a temporary commit, as verify.md requires for a new page), test (4249 passed), docs:test (1861 passed), test-markers grep, all exit 0. Gate 2: reviewer subagent, FAIL then PASS WITH NOTES after one loopback (Claude's default removal and the cleanup comparison were described wrongly; a page count left at 29; the page title pulled off-topic queries; two empty table headers). Notes in context/notes.md. --- README.md | 1 + context/notes.md | 11 ++ context/stack.md | 2 +- context/verify.md | 8 +- docs/README.md | 14 +-- docs/astro.config.mjs | 1 + docs/evals/baseline.json | 8 +- docs/scripts/audit-dist.mjs | 25 ++-- docs/scripts/audit-dist.test.mjs | 21 ++-- docs/src/chat/components/DoxChat.test.tsx | 4 +- docs/src/chat/docs-routes.generated.ts | 5 +- docs/src/chat/docs-routes.test.ts | 3 +- .../src/content/docs/commands/claude-hook.mdx | 108 ++++++++++++++++++ docs/src/content/docs/commands/cleanup.mdx | 4 + docs/src/content/docs/commands/index.mdx | 3 +- docs/src/content/docs/faq.mdx | 6 + docs/src/lib/llms-txt.test.ts | 10 +- docs/src/lib/og-art.test.ts | 2 +- docs/src/lib/og-cards.test.ts | 10 +- docs/worker/chat-handler.test.ts | 2 +- docs/worker/retrieval/search.test.ts | 6 +- skills/worktree/SKILL.md | 31 +++++ src/commands/claude-hook.test.ts | 13 ++- src/commands/claude-hook.ts | 2 - 24 files changed, 233 insertions(+), 67 deletions(-) create mode 100644 docs/src/content/docs/commands/claude-hook.mdx diff --git a/README.md b/README.md index be44f2b..aadfb31 100644 --- a/README.md +++ b/README.md @@ -263,6 +263,7 @@ Only the owner of `linear.apiKey` (or the ids in `linear.agentAllow`) can start | `worktree remove [branch]` | Remove one or more worktrees | | `worktree cleanup` | Remove stale worktrees that are safe to delete | | `worktree linear-listen` | Start a worktree for each Linear agent delegation | +| `worktree claude-hook` | Make Claude Code create and remove worktrees with this tool | For command help at any time: diff --git a/context/notes.md b/context/notes.md index 8d86b70..6668987 100644 --- a/context/notes.md +++ b/context/notes.md @@ -34,3 +34,14 @@ Non-blocking observations from the gates. Branch-local; `/feature-close` deletes - `removeCalls`' `args?.[0] === "prune"` can never match (dead, harmless). - The re-scan's realpath step is untested (test paths are already real); sessions with no `sessionId` count as "other" and refuse (fails safe); a failed session listing reads as no sessions, as in the gather. - On main: a gone directory under a symlinked prefix is compared as written, so the hook exits 1 instead of 0 (fails safe). + +## Phase 4 — Setup docs, and the command un-hidden + +- `claude-hook.mdx` Removal row, "With the hooks" cell, reads as if the hook always keeps both; it deletes them when nothing would be lost (line 70 says so). Suggested: "the worktree and its branch, only when nothing would be lost; otherwise both are kept (the refusals above) and nothing is discarded". +- Dox `retrieval.mrr` 0.716 → 0.682 from corpus growth (lookup-linear-issue 1→2, reworded-cleanup-merged-prs 1→2, fault-long-how-to 4→3); the new page's own wording was fixed so `refusal.quiet` stays 1. +- Claude Code column: "swept … once older than `cleanupPeriodDays`" is imprecise; clean subagent worktrees go at once, the sweep leaves ones holding work. +- "A directory that is already gone exits 0" holds only while git still lists the record; once pruned, the hook exits 1. +- The page's exit-code table and the `--help` text omit the dangling-record exit 2; nothing tests the `--help` content. +- `cleanup` would judge a fresh subagent worktree (no commits, no remote) stale at once unless its session is detected live; whether Claude locks hook-made worktrees is §9 Q3. +- Files beyond the plan's line, needed for the count: `og-cards.test.ts`, `og-art.test.ts`, `chat-handler.test.ts`, `docs/README.md`. `SKILL.md:624` heading still says "use these worktrees" (vocabulary only). +- The plan's §7 claim that `stack.md` miscounted command pages was wrong: 9 at HEAD was right, 10 now. diff --git a/context/stack.md b/context/stack.md index 766c938..01aaf9d 100644 --- a/context/stack.md +++ b/context/stack.md @@ -32,7 +32,7 @@ scripts/ version-sync script, run by `pnpm sync-version`; `release- .changeset/ Changesets config and pending release notes (`.changeset/.md`) skills/ the usage skill, `skills/worktree/SKILL.md`; hand-written, shipped inside the npm package (package.json `files`) and installable with `npx skills add`. Nothing on npm discovers it since TanStack Intent went (`skills add` reads GitHub); it stays in `files` so an `npm i -g` install has a copy matching its own version on disk docs/ Astro 7 + Starlight docs site, React 19 islands, Base UI; own package.json, `astro.config.mjs` -docs/src/content/docs/ Starlight pages (29 pages: `index.mdx` is the landing at `/worktree/`, `getting-started.mdx` is Getting Started at `/worktree/getting-started/`, plus `commands/` (9 command pages and an index), `guides/` (12 guides and an index), `configuration`, `project-configuration`, `faq` and `changelog`) +docs/src/content/docs/ Starlight pages (30 pages: `index.mdx` is the landing at `/worktree/`, `getting-started.mdx` is Getting Started at `/worktree/getting-started/`, plus `commands/` (10 command pages and an index), `guides/` (12 guides and an index), `configuration`, `project-configuration`, `faq` and `changelog`) docs/src/ chat client, site metadata, styles; the chat is the page `/dox` (`pages/dox.astro`, one React island, `chat/components/DoxPage.tsx`), reached by plain links only: the header's "Chat with Dox" crystal (`components/Header.astro`, repeated in the mobile menu by `components/MobileMenuFooter.astro`) and the landing's "Ask Dox" (`components/Hero.astro`); `components/DoxMark.astro` draws the crystal, and no page but `/dox` loads chat code; the header's right group ends with the settings gear (`components/SettingsControl.astro`, wired by `lib/settings-control.ts`: a native `[popover]` holding the "Dark theme" switch, whose rule is `lib/theme.ts`; it shows at every width, below 50rem as the only chip of the right group that does, and the mobile menu has no copy); sound is `lib/sound/` (GMT's engine, cut down: `settings.ts` is the reader's choice in the `dox:sound` key shared with GMT and northguild.dev, `cue.ts` is loaded on every page by `components/Head.astro`, and the engine is a chunk only its dynamic `import()` reaches, once a reader has unmuted, and on the landing alone it imports `lib/sound/leaves.ts`, the leaves' voices, driven by the last landing and the sampled landing places `hero/flight.ts` computes, only while sound is on, from the particles' own timings; no press makes a sound but the chat's Send and "Try again"); `components/Hero.astro` puts the landing's copy beside `HeroLeaves.astro` (the leaf-particle hero: a still SVG, a canvas and a small loader script; the effect itself, in `hero/` with OGL, is a chunk only the loader's dynamic `import()` reaches, so the landing alone ships hero script; its CSS is in the shared stylesheet); the share cards are made in the build: `pages/og/[...route].ts` writes `dist/og/site.png` and one PNG per page, `lib/og-cards.ts` decides the cards and their alt text, `lib/og-art.ts` draws one with CanvasKit (`lib/og-canvaskit.ts` loads it) over the committed `assets/og-art.png` in the Michroma TTF of `assets/og-fonts/`, `components/Head.astro` writes each page's share tags, and `lib/og-image-version.ts` is the integration that appends `?v=` to them after the build docs/src/styles/northguild/ the NorthGuild theme, vendored unedited from `northguild/northguild.dev` `packages/theme/` (each file's header names the commit); `docs/src/styles/theme.css` is this site's own `--gmt-*` → `--sl-*` mapping. To refresh, see `docs/README.md` (Theme) docs/wrangler.jsonc the docs site's Worker config (assets from `docs/.deploy`, the build staged under `worktree/` and `docs/deploy/_headers` at its root by `stage:deploy`); `docs/scripts/` holds `audit-dist.mjs`, `build-og-art.mjs` (draws the share cards' art into `docs/src/assets/og-art.png` by hand, never in the build), `theme-contrast.mjs` (measures the theme's contrast pairs), `build-legacy-pages.mjs` (writes the gitignored `docs/legacy/`), `deploy-smoke.mjs` and `web-vitals.mjs` (measures Core Web Vitals by hand, not a gate) diff --git a/context/verify.md b/context/verify.md index bafdc71..a168c86 100644 --- a/context/verify.md +++ b/context/verify.md @@ -101,19 +101,19 @@ pnpm docs:audit-dist ``` Runs after `pnpm docs:build` (Build above), because it reads `docs/dist/`; with no build it exits 1 saying it -cannot audit the directory (ENOENT). It asserts the SEO requirements of #235 over the built site: on each of the 29 pages a +cannot audit the directory (ENOENT). It asserts the SEO requirements of #235 over the built site: on each of the 30 pages a unique meta description of at most 155 characters, one canonical link in the form `https://northguild.dev/worktree//`, Open Graph and Twitter tags, JSON-LD of the right types, and a "Last updated" date equal to `git log --follow -1` for the page's source file (as a UTC date) — except the landing, which has no footer and so must carry no date; no page may carry an "Edit page" link into GitHub's editor (removed 2026-11-04; gmt's docs have none); no page may carry the project line the footer once had (licence, CLI version, maintainers); no page may show the northguild organisation's GitHub avatar (`github.com/northguild.png`), the second logo the footer once had, and no id may appear -twice on a page; across the site, a sitemap and an `llms.txt` (llmstxt.org format) each listing exactly those 29 +twice on a page; across the site, a sitemap and an `llms.txt` (llmstxt.org format) each listing exactly those 30 URLs, a `404.html` (with the site's search, a link to Getting Started at `/worktree/getting-started/`, and no canonical link or JSON-LD), a landing at the root (a heading, a "Get started" link to `/worktree/getting-started/`, one "Ask Dox" link to `/worktree/dox/` and no "Ask Dox" button, no second action and no section below the hero; the root alone may carry the site default description), and no `shuding/nextra` string. The date rule is only meaningful on full git history (CI uses `fetch-depth: 0`): on a shallow clone Starlight and the oracle both read the same truncated log. A page whose source file has no commit yet (a new or just-renamed one) fails the date rule with "no git history", so run the audit after committing it. It prints every failed rule, one line each, and exits 1 on any. To run it by hand: `pnpm docs:build && pnpm docs:audit-dist`, or point it at another build with `node docs/scripts/audit-dist.mjs `. It also checks accessible names on every page and the 404 (each button named, a name beside visible text containing it, each `