hookset 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -18,7 +18,7 @@
18
18
  <a href="https://app.codecov.io/gh/ofri-peretz/burgee/components"><img src="https://img.shields.io/codecov/c/github/ofri-peretz/burgee/main?component=hookset&style=flat-square" alt="hookset line coverage: its Codecov component" /></a>
19
19
  <a href="https://scorecard.dev/viewer/?uri=github.com/ofri-peretz/burgee"><img src="https://img.shields.io/ossf-scorecard/github.com/ofri-peretz/burgee?style=flat-square&label=OpenSSF%20Scorecard" alt="OpenSSF Scorecard for the repository" /></a>
20
20
  <a href="https://www.npmjs.com/package/hookset?activeTab=code"><img src="https://img.shields.io/npm/unpacked-size/hookset?style=flat-square" alt="Unpacked size of the latest hookset release on npm" /></a>
21
- <a href="https://github.com/ofri-peretz/burgee/blob/main/packages/hookset/package.json"><img src="https://img.shields.io/badge/dependencies-1%20in%20family%2C%200%20outside-0a6b47?style=flat-square" alt="One dependency, all in the burgee family (burgee), none outside it" /></a>
21
+ <a href="https://github.com/ofri-peretz/burgee/blob/main/packages/hookset/package.json"><img src="https://img.shields.io/badge/dependencies-2%20in%20family%2C%200%20outside-0a6b47?style=flat-square" alt="Two dependencies, all in the burgee family (bellpull, burgee), none outside it" /></a>
22
22
  <a href="https://github.com/ofri-peretz/burgee/blob/main/packages/hookset/package.json"><img src="https://img.shields.io/badge/types-included-blue?style=flat-square" alt="TypeScript types included for every entry point" /></a>
23
23
  <a href="https://github.com/ofri-peretz/burgee/blob/main/packages/hookset/package.json"><img src="https://img.shields.io/badge/Node.js-22.13%2B-green?style=flat-square" alt="Node.js 22.13+" /></a>
24
24
  <a href="https://github.com/ofri-peretz/burgee/blob/main/packages/hookset/LICENSE"><img src="https://img.shields.io/badge/License-MIT-blue?style=flat-square" alt="License: MIT" /></a>
@@ -86,6 +86,8 @@ hookset init --claude # and the Claude Code hook pack under .claude/hooks/
86
86
  hookset check # the CI gate: exit 1 on any error, warnings listed
87
87
  hookset check --json # the problems as data, one fix line each
88
88
  hookset context # exit 1 when what Claude loads every session outgrows the ceiling
89
+ hookset worktrees --size # every worktree agents left, its size, and why it stays or can go
90
+ hookset worktrees --prune # remove the clean ones whose commits are all on a remote, idle 3+ days
89
91
  ```
90
92
 
91
93
  | Command | Exit 1 when |
@@ -93,6 +95,7 @@ hookset context # exit 1 when what Claude loads every session outgrows t
93
95
  | `init` | a `lefthook.yml` written by hand is already there and `--force` is not given |
94
96
  | `check` | a station is missing, a remote pins no `hookset@<version>` tag, a preset step is repeated, or a vendored hook drifts from the pack |
95
97
  | `context` | CLAUDE.md, its `@`-imports and every skill, command and subagent description (less the skills marked `disable-model-invocation: true`) come to more tokens than `context.tokens` in `.claude/hookset.json`; `--update` lowers that ceiling and never raises it |
98
+ | `worktrees` | git refused to remove a worktree `--prune` chose. Only a worktree that is not the main or current one, not locked, has an empty `git status`, has every commit on a remote and is unchanged for `--older-than` days (default 3) is removed, with `git worktree remove` (never `--force`); branches are kept. `--include-local-commits` lets a commit that is only on this machine go too. `git worktree lock <path>` keeps any worktree out of every sweep |
96
99
 
97
100
  ## Migrating
98
101
 
@@ -147,7 +150,7 @@ Node 22.13 or later, git and lefthook.
147
150
 
148
151
  It hosts no plugin key of its own.
149
152
 
150
- Nothing in this family builds on it yet, and it builds on `burgee`.
153
+ Nothing in this family builds on it yet, and it builds on `bellpull` and `burgee`.
151
154
 
152
155
  ## The family
153
156
 
@@ -30,13 +30,18 @@ export function serverSpec(dir) {
30
30
  }
31
31
  }
32
32
 
33
- /** The npx arguments that bring the index up to date: build it on a fresh clone, catch it up otherwise. */
33
+ /**
34
+ * The npx arguments that bring the index up to date: build it on a fresh clone, catch it up otherwise.
35
+ * The path is "." because the index runs with `dir` as its cwd: on Windows npx runs through a shell,
36
+ * which would split a path with a space in it.
37
+ */
34
38
  export function indexArgs(dir, spec) {
35
39
  const indexed = existsSync(join(dir, ".codegraph", "codegraph.db"));
36
- return ["-y", spec, ...(indexed ? ["sync"] : ["init", "--yes"]), dir];
40
+ return ["-y", spec, ...(indexed ? ["sync"] : ["init", "--yes"]), "."];
37
41
  }
38
42
 
39
43
  function startIndex(dir, spec) {
44
+ // Telemetry off through the env var: `init` and `sync` reject `--no-telemetry`, which only `serve` takes.
40
45
  const env = { ...process.env, CODEGRAPH_TELEMETRY: "0" };
41
46
  const windows = process.platform === "win32";
42
47
  const child = spawn(windows ? "npx.cmd" : "npx", indexArgs(dir, spec), { cwd: dir, env, detached: true, stdio: "ignore", shell: windows });
@@ -61,10 +66,10 @@ function selfTest() {
61
66
  if (serverSpec(dir) !== want) bad.push(`spec of ${json}: want ${want}, got ${serverSpec(dir)}`);
62
67
  }
63
68
  const dir = mkdtempSync(join(tmpdir(), "codegraph-"));
64
- if (indexArgs(dir, "x@1").join(" ") !== `-y x@1 init --yes ${dir}`) bad.push("a fresh clone should init");
69
+ if (indexArgs(dir, "x@1").join(" ") !== "-y x@1 init --yes .") bad.push("a fresh clone should init");
65
70
  mkdirSync(join(dir, ".codegraph"));
66
71
  writeFileSync(join(dir, ".codegraph", "codegraph.db"), "");
67
- if (indexArgs(dir, "x@1").join(" ") !== `-y x@1 sync ${dir}`) bad.push("an indexed repo should sync");
72
+ if (indexArgs(dir, "x@1").join(" ") !== "-y x@1 sync .") bad.push("an indexed repo should sync");
68
73
  if (serverSpec(join(dir, "missing")) !== null) bad.push("no .mcp.json should be null");
69
74
  process.stdout.write(bad.length ? `${bad.join("\n")}\n${bad.length} failing\n` : `ok: ${Object.keys(CASES.specs).length + 3} cases\n`);
70
75
  process.exit(bad.length ? 1 : 0);
@@ -23,11 +23,18 @@
23
23
  // 7. Asks before a push that rewrites or deletes remote history: --force, --force-with-lease,
24
24
  // -f, +refspec, --delete, :refspec, --mirror, --prune.
25
25
  //
26
+ // 8. Denies a `git commit -m/-F` whose message the repo's commit-msg stations would reject
27
+ // (commitlint with the repo's own config, and the `Verified-by:` receipt where the repo has the
28
+ // provedone station), so the failure comes in seconds, before the pre-commit hook has run for minutes.
29
+ // No commitlint config or install, an interactive commit, or any internal error: no opinion.
30
+ //
26
31
  // Matching is done on tokens, not regexes over the raw command: quoted strings and
27
32
  // heredoc bodies are data (commit messages, PR bodies), and no pattern here can backtrack.
28
33
  // Reads the PreToolUse payload on stdin. Prints a deny or ask decision, or nothing (no opinion).
29
34
  // `node guard-bash.mjs --self-test` runs the cases at the bottom.
30
35
 
36
+ import { spawnSync } from "node:child_process";
37
+ import { existsSync, readFileSync } from "node:fs";
31
38
  import { posix } from "node:path";
32
39
 
33
40
  const SEPARATORS = new Set([";", "&", "|", "\n", "(", ")"]);
@@ -329,6 +336,174 @@ export function decideHooked(command, { timeout, run_in_background } = {}) {
329
336
  };
330
337
  }
331
338
 
339
+ /** Words of the commands in `src`, quotes resolved (`"a b"` is one word), each with whether the shell would expand it. */
340
+ function shellWords(src) {
341
+ const out = [];
342
+ let words = [];
343
+ let w = null;
344
+ const flushWord = () => {
345
+ if (w) words.push(w);
346
+ w = null;
347
+ };
348
+ const flush = () => {
349
+ flushWord();
350
+ if (words.length) out.push(words);
351
+ words = [];
352
+ };
353
+ const add = (text, dynamic) => {
354
+ w ??= { text: "", dynamic: false };
355
+ w.text += text;
356
+ w.dynamic ||= dynamic;
357
+ };
358
+ let i = 0;
359
+ while (i < src.length) {
360
+ const ch = src[i];
361
+ if (ch === "'") {
362
+ const end = src.indexOf("'", i + 1);
363
+ if (end === -1) return [];
364
+ add(src.slice(i + 1, end), false);
365
+ i = end + 1;
366
+ } else if (ch === '"') {
367
+ const end = skipQuoted(src, i) - 1;
368
+ const inner = src.slice(i + 1, end);
369
+ // `"$(cat <<'EOF' … EOF)"` is how a long message is passed: the body is the message.
370
+ const doc = /^\$\(cat <<-?\s*(['"]?)(\w+)\1\n([\s\S]*?)\n[ \t]*\2\s*\)$/.exec(inner);
371
+ if (doc) add(doc[3], false);
372
+ else add(inner.replace(/\\([\\"$`])/g, "$1"), /[$`]/.test(inner));
373
+ i = end + 1;
374
+ } else if (ch === "\\" && src[i + 1] !== undefined) {
375
+ add(src[i + 1], false);
376
+ i += 2;
377
+ } else if (SEPARATORS.has(ch)) {
378
+ flush();
379
+ i++;
380
+ } else if (ch === " " || ch === "\t") {
381
+ flushWord();
382
+ i++;
383
+ } else {
384
+ add(ch, ch === "$" || ch === "`");
385
+ i++;
386
+ }
387
+ }
388
+ flush();
389
+ return out;
390
+ }
391
+
392
+ /**
393
+ * The message a `git commit -m … / -F …` carries, or null when it is not a commit, has none on its
394
+ * command line (the editor opens), or cannot be known without running the shell. `read` returns a
395
+ * file's text (or null); `-F -` reads the command's own heredoc.
396
+ */
397
+ export function commitMessage(command, read = () => null) {
398
+ let src = String(command ?? "").replace(/\\\n/g, " ");
399
+ let stdin = null;
400
+ if (/(?:-F|--file)[ =]-(?:\s|$)/.test(src)) {
401
+ const heredoc = /<<-?\s*(['"]?)(\w+)\1[^\n]*\n([\s\S]*?)\n[ \t]*\2[ \t]*(?:\n|$)/.exec(src);
402
+ if (heredoc) {
403
+ stdin = heredoc[3];
404
+ src = src.replace(heredoc[0], "\n");
405
+ }
406
+ }
407
+ for (const w of shellWords(src)) {
408
+ const s = gitSub(w.map((x) => x.text));
409
+ if (s === -1 || w[s].text !== "commit") continue;
410
+ const args = w.slice(s + 1);
411
+ const parts = [];
412
+ for (let k = 0; k < args.length; k++) {
413
+ const a = args[k].text;
414
+ let value;
415
+ if (a === "--message" || a === "--file" || /^-[a-zA-Z]*[mF]$/.test(a)) {
416
+ const arg = args[++k];
417
+ if (!arg || arg.dynamic) return null;
418
+ value = arg.text;
419
+ if (/^-[a-zA-Z]*F$|^--file$/.test(a)) value = value === "-" ? stdin : read(value);
420
+ } else if (/^--(message|file)=/.test(a)) {
421
+ if (args[k].dynamic) return null;
422
+ value = a.startsWith("--file=") ? read(a.slice(7)) : a.slice(10);
423
+ } else if (/^-[a-zA-Z]*m./.test(a)) {
424
+ if (args[k].dynamic) return null;
425
+ value = a.slice(a.indexOf("m") + 1);
426
+ } else continue;
427
+ if (value === null || value === undefined) return null;
428
+ parts.push(value);
429
+ }
430
+ return parts.length ? parts.join("\n\n") : null;
431
+ }
432
+ return null;
433
+ }
434
+
435
+ const COMMITLINT_CONFIG = [
436
+ ...["", ".json", ".yaml", ".yml", ".js", ".cjs", ".mjs", ".ts", ".cts", ".mts"].map((e) => `.commitlintrc${e}`),
437
+ ...["js", "cjs", "mjs", "ts", "cts", "mts"].map((e) => `commitlint.config.${e}`),
438
+ ];
439
+
440
+ /** The `✖` lines commitlint prints for `message`: its rules (scope, type, footer width) come from the repo's own config; this only finds and runs it. */
441
+ function commitlintProblems(message, dir) {
442
+ const pkg = (() => {
443
+ try {
444
+ return JSON.parse(readFileSync(`${dir}/package.json`, "utf8"));
445
+ } catch {
446
+ return {};
447
+ }
448
+ })();
449
+ const cli = `${dir}/node_modules/@commitlint/cli/cli.js`;
450
+ if (!existsSync(cli) || !(pkg.commitlint || COMMITLINT_CONFIG.some((f) => existsSync(`${dir}/${f}`)))) return [];
451
+ const r = spawnSync(process.execPath, [cli], { cwd: dir, input: message, encoding: "utf8", timeout: 6000, env: { ...process.env, FORCE_COLOR: "0", NO_COLOR: "1" } });
452
+ if (r.status !== 1) return [];
453
+ // Lint failures are `✖ <message> [rule]` lines; a crash (bad config) prints none and has no opinion.
454
+ return `${r.stdout}\n${r.stderr}`.split("\n").map((l) => l.trim()).filter((l) => l.startsWith("✖") && /\[[a-z-]+\]$/.test(l));
455
+ }
456
+
457
+ /** The provedone receipt rule (burgee packages/provedone receipt.ts `verdict`), for repos that run its commit-msg station. */
458
+ function receiptProblem(message, dir) {
459
+ const has = (f) => {
460
+ try {
461
+ return readFileSync(`${dir}/${f}`, "utf8").includes("provedone");
462
+ } catch {
463
+ return false;
464
+ }
465
+ };
466
+ if (!has("package.json") && !has("lefthook.yml") && !has("lefthook.yaml")) return null;
467
+ const lines = message
468
+ .split("\n")
469
+ .filter((l) => !l.startsWith("#"))
470
+ .join("\n")
471
+ .replace(/\n[ \t]+/g, " ")
472
+ .split("\n");
473
+ if (/^Merge /.test(lines.join("\n"))) return null;
474
+ const values = lines.flatMap((l) => /^Verified-by:(.*)/i.exec(l)?.slice(1) ?? []).map((v) => v.trim());
475
+ const fix = "add a trailer `Verified-by: <command> -> exit 0` (or `Verified-by: none (<why no check applies>)`)";
476
+ if (!values.length) return `✖ no Verified-by: line: ${fix}`;
477
+ if (values.some((v) => /^none\b/i.test(v) && !/^none \(\s*\S[^)]*\)$/i.test(v))) return "✖ `Verified-by: none` gives no reason: write `Verified-by: none (<why it needs no check>)`";
478
+ if (values.some((v) => v === "")) return `✖ an empty Verified-by: line: ${fix}`;
479
+ return null;
480
+ }
481
+
482
+ /** The verdict for a `git commit` whose message the commit-msg stations would reject, or null. Never throws. */
483
+ export function decideCommitMessage(command, dir) {
484
+ try {
485
+ const message = commitMessage(command, (f) => {
486
+ try {
487
+ return readFileSync(posix.isAbsolute(f) ? f : `${dir}/${f}`, "utf8");
488
+ } catch {
489
+ return null;
490
+ }
491
+ });
492
+ if (message === null || message.trim() === "") return null;
493
+ const problems = [...commitlintProblems(message, dir), receiptProblem(message, dir)].filter(Boolean);
494
+ if (!problems.length) return null;
495
+ return {
496
+ decision: "deny",
497
+ id: "commit-message",
498
+ reason:
499
+ `The commit-msg hook would reject this message, but only after the pre-commit hook has spent minutes on the tests. Fix it now:\n${problems.join("\n")}` +
500
+ (problems.some((p) => p.includes("footer")) ? "\nFold a trailer longer than 100 characters onto a second line that starts with a space." : ""),
501
+ };
502
+ } catch {
503
+ return null;
504
+ }
505
+ }
506
+
332
507
  /** `*` within a segment, `**` across segments, `?` one character. Paths use forward slashes. */
333
508
  const GLOB_TOKEN = /\*\*\/|\*\*|\*|\?|[.+^${}()|[\]\\]/g;
334
509
  const GLOB_PART = { "**/": "(?:.*/)?", "**": ".*", "*": "[^/]*", "?": "[^/]" };
@@ -470,7 +645,49 @@ export const CASES = {
470
645
 
471
646
  const EDIT_CONFIG = { frozen: ["content/**/*.md"], generated: { "public/r/**": "npm run registry:build" } };
472
647
 
473
- function selfTest() {
648
+ // decideCommitMessage: [command, denied as a message problem containing, or null], run in a repo
649
+ // with a commitlint config (a stand-in CLI that applies the same three rules), the provedone station.
650
+ export const MESSAGES = [
651
+ ['git commit -m "feat(zzz): add x\n\nVerified-by: npm test -> exit 0"', "scope must be one of"],
652
+ ['git commit -m "feat(ci): add x"', "no Verified-by"],
653
+ ['git commit -m "feat(ci): add x" -m "Verified-by: none"', "gives no reason"],
654
+ [`git commit -m "feat(ci): add x" -m "Verified-by: ${"x".repeat(120)} -> exit 0"`, "100 characters"],
655
+ ['git commit -F - <<\'EOF\'\nfeat(zzz): x\n\nVerified-by: t -> exit 0\nEOF', "scope must be one of"],
656
+ ['git commit -m "$(cat <<\'EOF\'\nfeat(ci): x\n\nbody\nEOF\n)"', "no Verified-by"],
657
+ ['git commit -m "feat(ci): add x\n\nVerified-by: npm test -> exit 0"', null],
658
+ ['git commit -am "fix(ci): x" -m "Verified-by: none (docs only)"', null],
659
+ ['git commit -m "$(cat <<\'EOF\'\nfeat(ci): x\n\nVerified-by: npm test -> exit 0\nEOF\n)"', null],
660
+ ["git commit", null],
661
+ ["git commit --amend --no-edit", null],
662
+ ['git commit -m "$MSG"', null],
663
+ ['git log -m "feat(zzz): x"', null],
664
+ ];
665
+
666
+ const FAKE_COMMITLINT = `let s = "";
667
+ process.stdin.on("data", (d) => (s += d)).on("end", () => {
668
+ const out = [];
669
+ const scope = /^\\w+\\(([^)]*)\\)/.exec(s)?.[1];
670
+ if (scope && !["a", "ci"].includes(scope)) out.push("\\u2716 scope must be one of [a, ci] [scope-enum]");
671
+ if (s.split("\\n").slice(1).some((l) => l.length > 100)) out.push("\\u2716 footer's lines must not be longer than 100 characters [footer-max-line-length]");
672
+ console.log(out.join("\\n"));
673
+ process.exit(out.length ? 1 : 0);
674
+ });
675
+ `;
676
+
677
+ async function messageFixture() {
678
+ const { mkdtempSync, mkdirSync, writeFileSync } = await import("node:fs");
679
+ const { tmpdir } = await import("node:os");
680
+ const dir = mkdtempSync(`${tmpdir()}/guard-bash-`);
681
+ mkdirSync(`${dir}/node_modules/@commitlint/cli`, { recursive: true });
682
+ writeFileSync(`${dir}/node_modules/@commitlint/cli/cli.js`, FAKE_COMMITLINT);
683
+ writeFileSync(`${dir}/commitlint.config.mjs`, "export default {};\n");
684
+ writeFileSync(`${dir}/package.json`, JSON.stringify({ scripts: { "hook:provedone": "provedone gate --mode enforce" } }));
685
+ return dir;
686
+ }
687
+
688
+ async function selfTest() {
689
+ const repo = await messageFixture();
690
+ const bare = await messageFixture();
474
691
  const bad = [
475
692
  ...CASES.deny.filter((c) => decide(c)?.decision !== "deny").map((c) => `should deny: ${c}`),
476
693
  ...CASES.allow.filter((c) => decide(c)).map((c) => `should allow: ${c}`),
@@ -481,11 +698,22 @@ function selfTest() {
481
698
  ...CASES.edit
482
699
  .filter(([f, id]) => (decideEdit(f, EDIT_CONFIG.frozen, EDIT_CONFIG.generated)?.id ?? null) !== id)
483
700
  .map(([f, id]) => `should ${id ? `deny as ${id}` : "allow"}: edit ${f}`),
701
+ ...MESSAGES.flatMap(([c, want]) => {
702
+ const hit = decideCommitMessage(c, repo);
703
+ return (want === null ? hit === null : hit?.reason.includes(want)) ? [] : [`should ${want === null ? "allow" : `deny (${want})`}: ${c}`];
704
+ }),
484
705
  ];
706
+ // Without a commitlint config or the provedone station there is nothing to enforce.
707
+ const { rmSync } = await import("node:fs");
708
+ rmSync(`${bare}/commitlint.config.mjs`);
709
+ rmSync(`${bare}/package.json`);
710
+ if (decideCommitMessage('git commit -m "feat(zzz): x"', bare)) bad.push("should allow a commit in a repo with no commitlint config or provedone station");
711
+ rmSync(repo, { recursive: true, force: true });
712
+ rmSync(bare, { recursive: true, force: true });
485
713
  process.stdout.write(
486
714
  bad.length
487
715
  ? `${bad.join("\n")}\n${bad.length} failing\n`
488
- : `ok: ${CASES.deny.length} denied, ${CASES.allow.length} allowed, ${CASES.ask.length} asked, ${CASES.hooked.length} timed, ${CASES.edit.length} edits\n`,
716
+ : `ok: ${CASES.deny.length} denied, ${CASES.allow.length} allowed, ${CASES.ask.length} asked, ${CASES.hooked.length} timed, ${CASES.edit.length} edits, ${MESSAGES.length} messages\n`,
489
717
  );
490
718
  process.exit(bad.length ? 1 : 0);
491
719
  }
@@ -512,7 +740,7 @@ async function repoConfig() {
512
740
 
513
741
  // Imported (stop-after-3 reads `commands` from guard-bash) is not run: only the entry file acts.
514
742
  const isMain = Boolean(process.argv[1]) && import.meta.url.endsWith(`/${process.argv[1].split(/[\\/]/).pop()}`);
515
- if (isMain && process.argv.includes("--self-test")) selfTest();
743
+ if (isMain && process.argv.includes("--self-test")) await selfTest();
516
744
  else if (isMain) {
517
745
  let raw = "";
518
746
  process.stdin.on("data", (d) => (raw += d));
@@ -527,7 +755,7 @@ else if (isMain) {
527
755
  const config = await repoConfig();
528
756
  let hit = null;
529
757
  if (typeof input.command === "string")
530
- hit = decide(input.command, config.ask) ?? decideHooked(input.command, input);
758
+ hit = decide(input.command, config.ask) ?? decideCommitMessage(input.command, payload.cwd || config.dir) ?? decideHooked(input.command, input);
531
759
  else {
532
760
  const file = input.file_path ?? input.notebook_path;
533
761
  if (typeof file === "string") {
@@ -0,0 +1,111 @@
1
+ #!/usr/bin/env node
2
+ // worktree-sweep — Claude Code SessionStart hook. Canonical copy: burgee packages/hookset/claude/.
3
+ // `hookset init --claude` vendors it next to guard-bash.mjs.
4
+ //
5
+ // Claude Code's `--worktree`, isolated subagents and any agent that runs `git worktree add` leave
6
+ // a full checkout per task, and nothing removes one when the task ends. At most once a day per
7
+ // clone, this starts the repo's own `hookset worktrees --prune` in the background, so the session
8
+ // is not held for it. That command removes only worktrees that hold no work: not the main or
9
+ // current one, not locked, nothing uncommitted, every commit on a remote, and idle for the age
10
+ // given (default 3 days); `git worktree remove` without --force, branches kept.
11
+ //
12
+ // The person decides: HOOKSET_WORKTREES=0 turns it off, HOOKSET_WORKTREES_OLDER_THAN=<days>
13
+ // changes the age, and `git worktree lock <path>` keeps one worktree out of every sweep. It does
14
+ // nothing in a repo without hookset installed (node_modules/.bin/hookset). Each run's report is
15
+ // kept in the OS temp directory under hookset-worktree-sweep/.
16
+ // `node worktree-sweep.mjs --self-test` runs the cases at the bottom.
17
+
18
+ import { spawn } from "node:child_process";
19
+ import { createHash } from "node:crypto";
20
+ import { existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, writeFileSync } from "node:fs";
21
+ import { tmpdir } from "node:os";
22
+ import { join } from "node:path";
23
+
24
+ export const EVERY_MS = 24 * 60 * 60 * 1000;
25
+
26
+ /** The repo's own hookset bin, or null when hookset is not installed there. */
27
+ export function hooksetBin(dir) {
28
+ const bin = join(dir, "node_modules", ".bin", process.platform === "win32" ? "hookset.cmd" : "hookset");
29
+ return existsSync(bin) ? bin : null;
30
+ }
31
+
32
+ /** The arguments for the sweep: `--older-than` only when the person set a whole, non-negative number of days. */
33
+ export function sweepArgs(olderThan) {
34
+ const days = Number(olderThan);
35
+ const set = olderThan !== undefined && olderThan !== "" && Number.isFinite(days) && days >= 0;
36
+ return ["worktrees", "--prune", "--json", ...(set ? ["--older-than", String(days)] : [])];
37
+ }
38
+
39
+ /** Where this clone's last sweep is stamped and reported: named by a hash of the path, so no two clones share one. */
40
+ export function stampFile(dir, base = tmpdir()) {
41
+ const state = join(base, "hookset-worktree-sweep");
42
+ mkdirSync(state, { recursive: true });
43
+ return join(state, `${createHash("sha256").update(dir).digest("hex").slice(0, 16)}.json`);
44
+ }
45
+
46
+ /** Whether a sweep is due: no stamp yet, an unreadable one, or one older than EVERY_MS. */
47
+ export function due(stamp, now) {
48
+ try {
49
+ const at = Number(JSON.parse(readFileSync(stamp, "utf8")).at);
50
+ return !(now - at < EVERY_MS);
51
+ } catch {
52
+ return true;
53
+ }
54
+ }
55
+
56
+ function startSweep(dir, bin, args, stamp) {
57
+ writeFileSync(stamp, JSON.stringify({ at: Date.now(), args }));
58
+ const out = openSync(stamp.replace(/\.json$/, ".log"), "w");
59
+ const windows = process.platform === "win32";
60
+ // A .cmd runs only through a shell on Windows, which splits an unquoted path at its spaces.
61
+ const child = spawn(windows ? `"${bin}"` : bin, args, { cwd: dir, detached: true, stdio: ["ignore", out, out], shell: windows });
62
+ child.on("error", () => {});
63
+ child.unref();
64
+ }
65
+
66
+ function selfTest() {
67
+ const bad = [];
68
+ const check = (name, got, want) => {
69
+ if (JSON.stringify(got) !== JSON.stringify(want)) bad.push(`${name}: want ${JSON.stringify(want)}, got ${JSON.stringify(got)}`);
70
+ };
71
+ check("default args", sweepArgs(undefined), ["worktrees", "--prune", "--json"]);
72
+ check("empty age", sweepArgs(""), ["worktrees", "--prune", "--json"]);
73
+ check("an age", sweepArgs("7"), ["worktrees", "--prune", "--json", "--older-than", "7"]);
74
+ check("age zero", sweepArgs("0"), ["worktrees", "--prune", "--json", "--older-than", "0"]);
75
+ check("negative age", sweepArgs("-1"), ["worktrees", "--prune", "--json"]);
76
+ check("not a number", sweepArgs("soon"), ["worktrees", "--prune", "--json"]);
77
+ const base = mkdtempSync(join(tmpdir(), "worktree-sweep-"));
78
+ const stamp = stampFile("/repos/a b", base);
79
+ check("stamp path", stamp, join(base, "hookset-worktree-sweep", `${createHash("sha256").update("/repos/a b").digest("hex").slice(0, 16)}.json`));
80
+ check("paths that differ only in punctuation get their own stamps", stampFile("/repos/ab", base) === stampFile("/repos_ab", base), false);
81
+ check("due with no stamp", due(stamp, 1000), true);
82
+ writeFileSync(stamp, JSON.stringify({ at: 1000 }));
83
+ check("not due within a day", due(stamp, 1000 + EVERY_MS - 1), false);
84
+ check("due after a day", due(stamp, 1000 + EVERY_MS), true);
85
+ writeFileSync(stamp, "not json");
86
+ check("due on a bad stamp", due(stamp, 1000), true);
87
+ check("no bin", hooksetBin(base), null);
88
+ process.stdout.write(bad.length ? `${bad.join("\n")}\n${bad.length} failing\n` : "ok: 13 cases\n");
89
+ process.exit(bad.length ? 1 : 0);
90
+ }
91
+
92
+ const isMain = Boolean(process.argv[1]) && import.meta.url.endsWith(`/${process.argv[1].split(/[\\/]/).pop()}`);
93
+ if (isMain && process.argv.includes("--self-test")) selfTest();
94
+ else if (isMain) {
95
+ let raw = "";
96
+ process.stdin.on("data", (d) => (raw += d));
97
+ process.stdin.on("end", () => {
98
+ let payload;
99
+ try {
100
+ payload = JSON.parse(raw) ?? {};
101
+ } catch {
102
+ process.exit(0);
103
+ }
104
+ if (process.env.HOOKSET_WORKTREES === "0" || payload.hook_event_name !== "SessionStart") process.exit(0);
105
+ const dir = process.env.CLAUDE_PROJECT_DIR || payload.cwd || process.cwd();
106
+ const bin = hooksetBin(dir);
107
+ if (!bin) process.exit(0);
108
+ const stamp = stampFile(dir, process.env.HOOKSET_WORKTREE_SWEEP_DIR || tmpdir());
109
+ if (due(stamp, Date.now())) startSweep(dir, bin, sweepArgs(process.env.HOOKSET_WORKTREES_OLDER_THAN), stamp);
110
+ });
111
+ }
package/dist/cli.js CHANGED
@@ -1,7 +1,8 @@
1
- import { defineCommand, defineProgram, ExitCode } from 'burgee';
1
+ import { defineCommand, defineProgram, ExitCode, UsageError } from 'burgee';
2
2
  import { checkContext, contextText } from './context.js';
3
3
  import { checkRepo, checkText, initRepo, packageRoot, packageVersion } from './core.js';
4
4
  import { cwd } from './runtime.js';
5
+ import { DEFAULT_OLDER_THAN_DAYS, sweepWorktrees, worktreesText } from './worktrees.js';
5
6
  const TEXT = Symbol.for('burgee.text');
6
7
  const PKG = packageRoot();
7
8
  const repoOf = (options) => (typeof options['cwd'] === 'string' ? options['cwd'] : cwd());
@@ -71,9 +72,36 @@ const contextCommand = defineCommand({
71
72
  return data;
72
73
  },
73
74
  });
75
+ const worktreesCommand = defineCommand({
76
+ name: 'worktrees',
77
+ description: 'List the git worktrees agents left behind and, with --prune, remove the ones that hold no work',
78
+ effects: 'idempotent',
79
+ examples: [
80
+ { command: 'hookset worktrees --size', description: 'every linked worktree, its size, and why it stays or can go' },
81
+ { command: 'hookset worktrees --prune', description: 'remove clean worktrees whose commits are all on a remote and untouched for 3 days' },
82
+ { command: 'hookset worktrees --prune --older-than 0 --include-local-commits', description: 'a disk emergency: drop every clean worktree, even one with commits only here' },
83
+ ],
84
+ options: {
85
+ prune: { type: 'boolean', description: 'remove the removable worktrees (git worktree remove, never --force), then git worktree prune' },
86
+ olderThan: { type: 'number', default: DEFAULT_OLDER_THAN_DAYS, description: 'days without a change before a clean worktree can go' },
87
+ includeLocalCommits: { type: 'boolean', description: 'a commit on no remote no longer keeps its worktree (the branch is kept either way)' },
88
+ size: { type: 'boolean', description: 'add each worktree\'s size on disk (walks every file, node_modules included)' },
89
+ cwd: { type: 'string', description: 'any directory in the clone (default: the current directory)' },
90
+ },
91
+ run: async ({ options }) => {
92
+ const o = options;
93
+ const days = o['olderThan'];
94
+ if (days < 0)
95
+ throw new UsageError(`--older-than takes a number of days, not ${String(days)}`, 'pass --older-than 7');
96
+ const result = await sweepWorktrees(repoOf(o), { prune: o['prune'] === true, olderThanDays: days, keepLocalCommits: o['includeLocalCommits'] !== true, size: o['size'] === true });
97
+ const data = { ...result, changed: result.removed > 0, ...(result.ok ? {} : { exitCode: ExitCode.RUNTIME }) };
98
+ data[TEXT] = () => worktreesText(result);
99
+ return data;
100
+ },
101
+ });
74
102
  export const program = defineProgram({
75
103
  name: 'hookset',
76
104
  version: packageVersion(PKG),
77
105
  description: 'The verification stations as git and Claude hooks, the same in every repo',
78
- commands: [initCommand, checkCommand, contextCommand],
106
+ commands: [initCommand, checkCommand, contextCommand, worktreesCommand],
79
107
  });
@@ -0,0 +1,152 @@
1
+ import { existsSync, lstatSync, readdirSync, realpathSync, statSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { ambientRuntime, run } from 'bellpull';
4
+ const DAY_MS = 86_400_000;
5
+ const MB = 1_048_576;
6
+ const SHORT_SHA = 7;
7
+ const TENTHS = 10;
8
+ export const DEFAULT_OLDER_THAN_DAYS = 3;
9
+ export const SKIP_FOR_AGE = new Set(['.git', 'node_modules', '.turbo', '.next', 'dist', 'coverage']);
10
+ export const HOOK_GIT_VARS = new Set(['GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE']);
11
+ export const gitEnv = (env) => Object.fromEntries(Object.entries(env).filter(([key]) => !HOOK_GIT_VARS.has(key)));
12
+ export const runGit = async (cwd, args) => {
13
+ const runtime = ambientRuntime();
14
+ const r = await run('git', args, { cwd, env: gitEnv(runtime.env), runtime });
15
+ return { ok: r.ok, out: r.stdout, err: r.stderr.trim() };
16
+ };
17
+ export function parseWorktrees(porcelain) {
18
+ const out = [];
19
+ for (const block of porcelain.split('\n\n')) {
20
+ const lines = block.split('\n');
21
+ const field = (key) => lines.find((l) => l.startsWith(`${key} `))?.slice(key.length + 1);
22
+ const path = field('worktree');
23
+ if (path === undefined)
24
+ continue;
25
+ out.push({ path, head: field('HEAD') ?? '', branch: field('branch')?.replace('refs/heads/', ''), locked: lines.some((l) => l.split(' ')[0] === 'locked') });
26
+ }
27
+ return out;
28
+ }
29
+ export function newestUnder(dir) {
30
+ let newest = statSync(dir).mtimeMs;
31
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
32
+ if (SKIP_FOR_AGE.has(entry.name))
33
+ continue;
34
+ const full = join(dir, entry.name);
35
+ newest = Math.max(newest, entry.isDirectory() ? newestUnder(full) : lstatSync(full).mtimeMs);
36
+ }
37
+ return newest;
38
+ }
39
+ export function bytesUnder(dir) {
40
+ let bytes = 0;
41
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
42
+ const full = join(dir, entry.name);
43
+ bytes += entry.isDirectory() ? bytesUnder(full) : lstatSync(full).size;
44
+ }
45
+ return bytes;
46
+ }
47
+ export function samePath(a, b) {
48
+ try {
49
+ return realpathSync(a) === realpathSync(b);
50
+ }
51
+ catch {
52
+ return false;
53
+ }
54
+ }
55
+ export function keepReason(w, olderThanDays, keepLocalCommits) {
56
+ if (w.main)
57
+ return 'the main worktree';
58
+ if (w.current)
59
+ return 'this sweep runs in it';
60
+ if (w.missing)
61
+ return 'its directory is gone: `git worktree prune` drops it';
62
+ if (w.locked)
63
+ return 'locked';
64
+ if (w.dirty > 0)
65
+ return `${String(w.dirty)} uncommitted file(s)`;
66
+ if (keepLocalCommits && w.localCommits > 0)
67
+ return `${String(w.localCommits)} commit(s) on no remote`;
68
+ if (w.idleDays < olderThanDays)
69
+ return `changed ${(Math.floor(w.idleDays * TENTHS) / TENTHS).toFixed(1)} day(s) ago`;
70
+ return undefined;
71
+ }
72
+ const lineCount = (text) => text.split('\n').filter(Boolean).length;
73
+ async function inspect(l, main, o) {
74
+ const current = samePath(l.path, o.top);
75
+ const facts = { ...l, main, current, missing: !existsSync(l.path), dirty: 0, localCommits: 0, idleDays: 0 };
76
+ if (!facts.missing) {
77
+ facts.dirty = lineCount((await o.git(l.path, ['status', '--porcelain'])).out);
78
+ if (l.head !== '')
79
+ facts.localCommits = Number((await o.git(l.path, ['rev-list', '--count', 'HEAD', '--not', '--remotes'])).out) || 0;
80
+ if (!main && !current)
81
+ facts.idleDays = Math.max(0, (o.now - newestUnder(l.path)) / DAY_MS);
82
+ }
83
+ const sized = o.size && !facts.missing ? { bytes: bytesUnder(l.path) } : {};
84
+ return { ...facts, ...sized, keep: keepReason(facts, o.olderThanDays, o.keepLocalCommits), removed: false };
85
+ }
86
+ async function prune(repo, worktrees, git) {
87
+ for (const w of worktrees.filter((t) => t.keep === undefined)) {
88
+ const r = await git(repo, ['worktree', 'remove', w.path]);
89
+ w.removed = r.ok;
90
+ if (!r.ok)
91
+ w.error = r.err;
92
+ }
93
+ return (await git(repo, ['worktree', 'prune'])).ok;
94
+ }
95
+ export async function sweepWorktrees(repo, options = {}) {
96
+ const git = options.git ?? runGit;
97
+ const listed = await git(repo, ['worktree', 'list', '--porcelain']);
98
+ if (!listed.ok) {
99
+ return { repo, worktrees: [], removable: 0, removed: 0, pruned: false, ok: false, error: listed.err || 'git worktree list failed', fix: 'run it inside a git clone, or pass --cwd' };
100
+ }
101
+ const o = {
102
+ git,
103
+ top: (await git(repo, ['rev-parse', '--show-toplevel'])).out.trim(),
104
+ now: options.now ?? Date.now(),
105
+ size: options.size === true,
106
+ olderThanDays: options.olderThanDays ?? DEFAULT_OLDER_THAN_DAYS,
107
+ keepLocalCommits: options.keepLocalCommits ?? true,
108
+ };
109
+ const worktrees = await Promise.all(parseWorktrees(listed.out).map((l, index) => inspect(l, index === 0, o)));
110
+ const pruned = options.prune === true && (await prune(repo, worktrees, git));
111
+ const failed = worktrees.filter((w) => w.error !== undefined).map((w) => w.path);
112
+ const result = {
113
+ repo,
114
+ worktrees,
115
+ removable: worktrees.filter((w) => w.keep === undefined).length,
116
+ removed: worktrees.filter((w) => w.removed).length,
117
+ pruned,
118
+ ok: failed.length === 0,
119
+ };
120
+ if (failed.length > 0)
121
+ Object.assign(result, { error: `git refused to remove ${failed.join(', ')}`, fix: 'read the error on each; git keeps what it would lose' });
122
+ return result;
123
+ }
124
+ const mb = (bytes) => `${Math.round(bytes / MB).toString()} MB`;
125
+ function stateOf(w) {
126
+ if (w.removed)
127
+ return 'removed';
128
+ if (w.error !== undefined)
129
+ return `refused: ${w.error}`;
130
+ if (w.keep !== undefined)
131
+ return `kept: ${w.keep}`;
132
+ return 'removable';
133
+ }
134
+ function tailOf(result) {
135
+ if (result.pruned)
136
+ return `removed ${String(result.removed)} of ${String(result.removable)} removable`;
137
+ if (result.removable > 0)
138
+ return `${String(result.removable)} removable: run with --prune`;
139
+ return 'nothing to remove';
140
+ }
141
+ export function worktreesText(result) {
142
+ if (result.worktrees.length === 0 && result.error !== undefined)
143
+ return `hookset worktrees: ${result.error}`;
144
+ const sized = result.worktrees.filter((w) => w.bytes !== undefined);
145
+ const total = sized.length > 0 ? `, ${mb(sized.reduce((sum, w) => sum + w.bytes, 0))} in all` : '';
146
+ const head = `hookset worktrees: ${String(result.worktrees.filter((w) => !w.main).length)} linked worktree(s)${total}; ${tailOf(result)}`;
147
+ const lines = result.worktrees.map((w) => {
148
+ const size = w.bytes === undefined ? '' : ` ${mb(w.bytes)}`;
149
+ return ` ${w.path} [${w.branch ?? w.head.slice(0, SHORT_SHA)}]${size} ${stateOf(w)}`;
150
+ });
151
+ return [head, ...lines].join('\n');
152
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hookset",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "private": false,
5
5
  "description": "Git hooks presets for AI coding agents: lefthook presets pulled by a pinned tag, a Claude Code hook pack that denies skipped hooks, and `hookset init` and `check`. No dependency outside the burgee family. A husky migration path.",
6
6
  "keywords": [
@@ -57,7 +57,8 @@
57
57
  "lint": "cd ../.. && eslint packages/hookset/src --max-warnings 0"
58
58
  },
59
59
  "dependencies": {
60
- "burgee": "^2.2.2"
60
+ "bellpull": "^2.0.3",
61
+ "burgee": "^2.2.3"
61
62
  },
62
63
  "devDependencies": {
63
64
  "vitest": "^5.0.1"
package/stations.json CHANGED
@@ -18,14 +18,15 @@
18
18
  { "id": "triggerlist", "hook": "pre-push", "mode": "observe", "command": "hookset-triggerlist", "script": "hook:triggerlist", "detail": "protected paths changed only with their trigger" }
19
19
  ],
20
20
  "claude": {
21
- "files": ["guard-bash.mjs", "stop-after-3.mjs", "verify-before-stop.mjs", "codegraph.mjs"],
21
+ "files": ["guard-bash.mjs", "stop-after-3.mjs", "verify-before-stop.mjs", "codegraph.mjs", "worktree-sweep.mjs"],
22
22
  "hooks": [
23
23
  { "event": "PreToolUse", "matcher": "Bash", "file": "guard-bash.mjs" },
24
24
  { "event": "PreToolUse", "matcher": "Edit|Write|MultiEdit|NotebookEdit", "file": "guard-bash.mjs" },
25
25
  { "event": "PostToolUse", "matcher": "Bash", "file": "stop-after-3.mjs" },
26
26
  { "event": "PostToolUse", "matcher": "Bash", "file": "verify-before-stop.mjs" },
27
27
  { "event": "Stop", "matcher": "", "file": "verify-before-stop.mjs" },
28
- { "event": "SessionStart", "matcher": "", "file": "codegraph.mjs" }
28
+ { "event": "SessionStart", "matcher": "", "file": "codegraph.mjs" },
29
+ { "event": "SessionStart", "matcher": "", "file": "worktree-sweep.mjs" }
29
30
  ],
30
31
  "mcp": [
31
32
  {