hookset 1.0.0 → 1.1.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
@@ -26,8 +26,8 @@
26
26
  </p>
27
27
 
28
28
  <p align="center">
29
- Docs: <a href="https://burgee.interlace.tools/docs/packages/hookset">https://burgee.interlace.tools/docs/packages/hookset</a><br />
30
- Migrating from: <a href="https://github.com/ofri-peretz/burgee/tree/main/packages/hookset#migrating">husky</a>
29
+ Docs: <a href="https://hookset.interlace.tools">https://hookset.interlace.tools</a><br />
30
+ Migrating from: <a href="https://hookset.interlace.tools/docs/coming-from/husky">husky</a>
31
31
  </p>
32
32
 
33
33
  **hookset** puts the same verification stations in every repository: lefthook presets for
@@ -85,12 +85,14 @@ hookset init # the smallest lefthook.yml that pulls the presets, pinn
85
85
  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
+ hookset context # exit 1 when what Claude loads every session outgrows the ceiling
88
89
  ```
89
90
 
90
91
  | Command | Exit 1 when |
91
92
  | :-- | :-- |
92
93
  | `init` | a `lefthook.yml` written by hand is already there and `--force` is not given |
93
94
  | `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
+ | `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 |
94
96
 
95
97
  ## Migrating
96
98
 
@@ -181,13 +183,13 @@ keeps both true.
181
183
  | [bellpull](https://bellpull.interlace.tools/docs) | Subprocesses, and which executable actually ran | cross-spawn and which |
182
184
  | [controlroom](https://controlroom.interlace.tools/docs) | Keyboard-driven terminal screens, inline or full-screen | ink |
183
185
  | [oxmutate](https://oxmutate.interlace.tools/docs) | Mutation testing on the oxc engine, inside your own Vitest | Stryker |
184
- | [truepass](https://burgee.interlace.tools/docs/packages/truepass) | Lint rules and a pre-push check that keep a test suite honest | @vitest/eslint-plugin |
185
- | [contractdiff](https://burgee.interlace.tools/docs/packages/contractdiff) | API contracts: breaking-change diff, lint, and code from the spec | openapi-typescript |
186
- | [truefit](https://burgee.interlace.tools/docs/packages/truefit) | Validation whose schemas are data, with no eval | zod |
187
- | [provedone](https://burgee.interlace.tools/docs/packages/provedone) | A receipt for how every change was verified, and a gate that reads it | @commitlint/cli |
188
- | [replz](https://burgee.interlace.tools/docs/packages/replz) | Recall of a reviewer and its checks, replayed on bugs that shipped | promptfoo |
186
+ | [truepass](https://truepass.interlace.tools/docs) | Lint rules and a pre-push check that keep a test suite honest | @vitest/eslint-plugin |
187
+ | [contractdiff](https://contractdiff.interlace.tools/docs) | API contracts: breaking-change diff, lint, and code from the spec | openapi-typescript |
188
+ | [truefit](https://truefit.interlace.tools/docs) | Validation whose schemas are data, with no eval | zod |
189
+ | [provedone](https://provedone.interlace.tools/docs) | A receipt for how every change was verified, and a gate that reads it | @commitlint/cli |
190
+ | [replz](https://replz.interlace.tools/docs) | Recall of a reviewer and its checks, replayed on bugs that shipped | promptfoo |
189
191
  | **hookset** (this package) | The same git and Claude Code hooks in every repository, pinned by tag | husky |
190
- | [triggerlist](https://burgee.interlace.tools/docs/packages/triggerlist) | The review checklist a diff selects, read from the base branch | danger |
192
+ | [triggerlist](https://triggerlist.interlace.tools/docs) | The review checklist a diff selects, read from the base branch | danger |
191
193
 
192
194
  Every migration guide, and the family-wide [compatibility](https://burgee.interlace.tools/docs/compatibility)
193
195
  and [benchmarks](https://burgee.interlace.tools/docs/benchmarks) pages, are on
@@ -165,7 +165,7 @@ const HOOK_FILE_TOOLS = new Set(["rm", "mv", "chmod", "unlink", "truncate", "ln"
165
165
  function removesHooks(words) {
166
166
  if (hasPhrase(words, "lefthook uninstall")) return true;
167
167
  const inHooks = (w) => /(^|\/)\.git\/hooks(\/|$)/.test(w.replace(/^>+/, ""));
168
- if (words.some((w, i) => inHooks(w) && (/^>/.test(w) || /^>+$/.test(words[i - 1] ?? "")))) return true;
168
+ if (words.some((w, i) => inHooks(w) && (w.startsWith(">") || /^>+$/.test(words[i - 1] ?? "")))) return true;
169
169
  const tool = words.findIndex((w) => HOOK_FILE_TOOLS.has(w.split("/").pop()));
170
170
  return tool !== -1 && words.slice(tool + 1).some(inHooks);
171
171
  }
@@ -330,18 +330,10 @@ export function decideHooked(command, { timeout, run_in_background } = {}) {
330
330
  }
331
331
 
332
332
  /** `*` within a segment, `**` across segments, `?` one character. Paths use forward slashes. */
333
+ const GLOB_TOKEN = /\*\*\/|\*\*|\*|\?|[.+^${}()|[\]\\]/g;
334
+ const GLOB_PART = { "**/": "(?:.*/)?", "**": ".*", "*": "[^/]*", "?": "[^/]" };
333
335
  export function globToRegExp(glob) {
334
- let re = "";
335
- for (let i = 0; i < glob.length; i++) {
336
- const ch = glob[i];
337
- if (ch === "*" && glob[i + 1] === "*") {
338
- re += glob[i + 2] === "/" ? "(?:.*/)?" : ".*";
339
- i += glob[i + 2] === "/" ? 2 : 1;
340
- } else if (ch === "*") re += "[^/]*";
341
- else if (ch === "?") re += "[^/]";
342
- else re += /[.+^${}()|[\]\\]/.test(ch) ? `\\${ch}` : ch;
343
- }
344
- return new RegExp(`^${re}$`);
336
+ return new RegExp(`^${glob.replace(GLOB_TOKEN, (token) => GLOB_PART[token] ?? `\\${token}`)}$`);
345
337
  }
346
338
 
347
339
  /** The verdict for an Edit/Write on `file` (relative to the repo), or null. */
@@ -453,7 +445,7 @@ export const CASES = {
453
445
  "git push -d origin x",
454
446
  "git push --mirror",
455
447
  ],
456
- // decideHooked: [command, Bash input, denied?]
448
+ // decideHooked cases: the command, its Bash input, and whether it is denied.
457
449
  hooked: [
458
450
  ["git push origin main", {}, true],
459
451
  ["git -C repo commit -m x", { timeout: 120000 }, true],
@@ -0,0 +1,38 @@
1
+ ---
2
+ name: verify
3
+ description: Boot this repo's app or CLI, drive the change the way a user would, and check what it shows. Use before every commit that changes behaviour, and as the smoke test after a fix.
4
+ ---
5
+
6
+ # Verify a change by running it
7
+
8
+ Tests say the parts work; this skill says the feature works. Run it before committing a change that
9
+ a user could notice, and paste what you saw (the command and its output, or the screenshot) into
10
+ the commit's `Verified-by:` receipt or the PR's "How this was checked".
11
+
12
+ TODO(verify): replace every TODO(verify) line with this repo's real steps, then delete this one.
13
+ `hookset check` fails while any TODO(verify) remains.
14
+
15
+ ## Boot
16
+
17
+ TODO(verify): the one command that builds and starts the thing a user runs (a dev server, the CLI
18
+ from its built bin, a local service), how to tell it is ready, and how long that takes.
19
+
20
+ ## Drive and inspect
21
+
22
+ TODO(verify): how to exercise it as a user: the browser tool and URL for a site, the CLI command
23
+ with real arguments, the request for a service. What to read back: the page text, the exit code
24
+ and output, the response body.
25
+
26
+ ## Feature map
27
+
28
+ The features a user sees, each with where to reach it and what "working" looks like. A change
29
+ re-runs the rows it touches; a release runs them all.
30
+
31
+ | Feature | Reach it by | Working means |
32
+ | ------------ | ------------ | ------------- |
33
+ | TODO(verify) | TODO(verify) | TODO(verify) |
34
+
35
+ ## When it fails
36
+
37
+ Fix the code, not this skill. If the skill itself is wrong (a step that no longer boots), fix the
38
+ skill in its own commit and say so. After three failed rounds, stop and show the person the output.
@@ -0,0 +1,235 @@
1
+ #!/usr/bin/env node
2
+ // verify-before-stop — Claude Code Stop hook, plus a PostToolUse hook for Bash that feeds it.
3
+ // Canonical copy: burgee packages/hookset/claude/. `hookset init --claude` vendors it next to
4
+ // guard-bash.mjs and stop-after-3.mjs.
5
+ //
6
+ // "Run the tests before you say you're done" was a sentence; the verification post says to make
7
+ // it a hook that runs when Claude finishes. A whole suite inside a Stop hook would hold every turn
8
+ // for minutes, so this hook asks for the run instead of making it:
9
+ //
10
+ // - PostToolUse (Bash): a test run that passes records a fingerprint of the uncommitted code.
11
+ // - Stop: when uncommitted code differs from the last passing run's fingerprint (or no run
12
+ // passed this session), the turn is sent back once with the reason. The second Stop of the
13
+ // same turn (`stop_hook_active`) always passes, so Claude can never be stuck here.
14
+ //
15
+ // Committed work is not judged here: the commit and push hooks are its gate. Docs do not count:
16
+ // `.md`, `.mdx` and `.txt` files, and any glob the repo lists under `verifyIgnore` in
17
+ // .claude/hookset.json. A test run is what stop-after-3 counts as one (vitest, `npm test`,
18
+ // `npm run ci:local`, …). `node verify-before-stop.mjs --self-test` runs the cases at the bottom.
19
+
20
+ import { spawnSync } from "node:child_process";
21
+ import { createHash } from "node:crypto";
22
+ import {
23
+ existsSync,
24
+ mkdirSync,
25
+ readFileSync,
26
+ rmSync,
27
+ writeFileSync,
28
+ } from "node:fs";
29
+ import { tmpdir } from "node:os";
30
+ import { join } from "node:path";
31
+
32
+ import { globToRegExp } from "./guard-bash.mjs";
33
+ import { isTestCommand } from "./stop-after-3.mjs";
34
+
35
+ const DOCS = /\.(md|mdx|txt)$/i;
36
+
37
+ /** The uncommitted paths `git status` lists, staged, unstaged and untracked, renames as their new path. */
38
+ export function changedPaths(dir) {
39
+ const r = spawnSync(
40
+ "git",
41
+ ["status", "--porcelain=v1", "-z", "--untracked-files=all"],
42
+ { cwd: dir, encoding: "utf8" },
43
+ );
44
+ if (r.status !== 0) return [];
45
+ const parts = r.stdout.split("\0").filter(Boolean);
46
+ const paths = [];
47
+ for (let i = 0; i < parts.length; i++) {
48
+ const entry = parts[i];
49
+ paths.push(entry.slice(3));
50
+ // A rename or copy is followed by its old path, which is not in the tree any more.
51
+ if (entry[0] === "R" || entry[0] === "C") i++;
52
+ }
53
+ return paths;
54
+ }
55
+
56
+ /** True when `path` is code this hook judges: not docs, not a glob the repo ignores. */
57
+ export function counts(path, ignore = []) {
58
+ const rel = path.replaceAll("\\", "/");
59
+ return !DOCS.test(rel) && !ignore.some((g) => globToRegExp(g).test(rel));
60
+ }
61
+
62
+ /** One hash over every uncommitted code path and its content, or null when there is none. */
63
+ export function fingerprint(dir, ignore = []) {
64
+ const paths = changedPaths(dir)
65
+ .filter((p) => counts(p, ignore))
66
+ .sort();
67
+ if (paths.length === 0) return null;
68
+ const hash = createHash("sha256");
69
+ for (const p of paths) {
70
+ const file = join(dir, p);
71
+ hash.update(p).update("\0");
72
+ hash
73
+ .update(existsSync(file) ? readFileSync(file) : "<deleted>")
74
+ .update("\0");
75
+ }
76
+ return { hash: hash.digest("hex"), paths };
77
+ }
78
+
79
+ function stateFile(session) {
80
+ const dir = join(tmpdir(), "hookset-verify-before-stop");
81
+ mkdirSync(dir, { recursive: true });
82
+ return join(
83
+ dir,
84
+ `${String(session || "default").replace(/[^\w.-]/g, "_")}.json`,
85
+ );
86
+ }
87
+
88
+ function passedHash(session) {
89
+ try {
90
+ return JSON.parse(readFileSync(stateFile(session), "utf8")).hash ?? null;
91
+ } catch {
92
+ return null;
93
+ }
94
+ }
95
+
96
+ /** PostToolUse: a passing test run remembers what the code looked like. Prints nothing. */
97
+ export function recordPass(session, dir, command, failed, ignore = []) {
98
+ if (failed || !isTestCommand(command)) return;
99
+ const fp = fingerprint(dir, ignore);
100
+ // A pass with nothing uncommitted proves the committed tree; forget any older fingerprint.
101
+ if (fp) writeFileSync(stateFile(session), JSON.stringify({ hash: fp.hash }));
102
+ else rmSync(stateFile(session), { force: true });
103
+ }
104
+
105
+ /** Stop: the JSON that sends the turn back, or null to let it end. */
106
+ export function decideStop(session, dir, active, ignore = []) {
107
+ if (active) return null;
108
+ const fp = fingerprint(dir, ignore);
109
+ if (!fp || fp.hash === passedHash(session)) return null;
110
+ const shown =
111
+ fp.paths.slice(0, 5).join(", ") +
112
+ (fp.paths.length > 5 ? `, and ${fp.paths.length - 5} more` : "");
113
+ return {
114
+ decision: "block",
115
+ reason:
116
+ `[verify-before-stop] Code changed since the last passing test run (${shown}). ` +
117
+ "Run the tests that cover it, or the repo's verify skill, and say what passed. " +
118
+ "If they cannot run yet (you need an answer first), say that in your reply and end the turn; this hook will not stop you twice.",
119
+ };
120
+ }
121
+
122
+ /** The repo's `verifyIgnore` globs from .claude/hookset.json. Missing is none. */
123
+ function ignoreOf(dir) {
124
+ try {
125
+ const list = JSON.parse(
126
+ readFileSync(join(dir, ".claude", "hookset.json"), "utf8"),
127
+ ).verifyIgnore;
128
+ return Array.isArray(list) ? list.map(String) : [];
129
+ } catch {
130
+ return [];
131
+ }
132
+ }
133
+
134
+ function failedResponse(payload) {
135
+ if (payload.hook_event_name === "PostToolUseFailure") return true;
136
+ const r = payload.tool_response;
137
+ if (!r || typeof r !== "object") return false;
138
+ if (r.interrupted === true) return true;
139
+ const code = r.exitCode ?? r.exit_code ?? r.returnCode ?? r.code;
140
+ return typeof code === "number"
141
+ ? code !== 0
142
+ : r.is_error === true || r.isError === true;
143
+ }
144
+
145
+ function selfTest() {
146
+ const bad = [];
147
+ const dir = join(tmpdir(), `hookset-vbs-${process.pid}`);
148
+ rmSync(dir, { recursive: true, force: true });
149
+ mkdirSync(dir, { recursive: true });
150
+ const env = Object.fromEntries(Object.entries(process.env).filter(([k]) => !k.startsWith("GIT_")));
151
+ const git = (...a) => spawnSync("git", a, { cwd: dir, encoding: "utf8", env });
152
+ git("init", "-q");
153
+ git(
154
+ "-c",
155
+ "user.email=t@t",
156
+ "-c",
157
+ "user.name=t",
158
+ "commit",
159
+ "-q",
160
+ "--allow-empty",
161
+ "-m",
162
+ "root",
163
+ );
164
+ const session = `self-test-${process.pid}`;
165
+ rmSync(stateFile(session), { force: true });
166
+
167
+ if (decideStop(session, dir, false))
168
+ bad.push("a clean tree should end the turn");
169
+ writeFileSync(join(dir, "notes.md"), "x");
170
+ if (decideStop(session, dir, false))
171
+ bad.push("a docs-only change should end the turn");
172
+ writeFileSync(join(dir, "a.ts"), "export const a = 1;\n");
173
+ if (decideStop(session, dir, false)?.decision !== "block")
174
+ bad.push("untested code should send the turn back");
175
+ if (decideStop(session, dir, true))
176
+ bad.push("the second stop of a turn should always pass");
177
+ if (decideStop(session, dir, false, ["*.ts"]))
178
+ bad.push("a verifyIgnore glob should not count");
179
+ recordPass(session, dir, "npm run build", false);
180
+ if (!decideStop(session, dir, false)) bad.push("a build is not a test run");
181
+ recordPass(session, dir, "npx vitest run", true);
182
+ if (!decideStop(session, dir, false))
183
+ bad.push("a failing test run is not a pass");
184
+ recordPass(session, dir, "npx vitest run", false);
185
+ if (decideStop(session, dir, false))
186
+ bad.push("a passing run over this code should end the turn");
187
+ writeFileSync(join(dir, "a.ts"), "export const a = 2;\n");
188
+ if (!decideStop(session, dir, false))
189
+ bad.push("an edit after the pass should send the turn back");
190
+
191
+ rmSync(stateFile(session), { force: true });
192
+ rmSync(dir, { recursive: true, force: true });
193
+ process.stdout.write(
194
+ bad.length ? `${bad.join("\n")}\n${bad.length} failing\n` : "ok: 9 cases\n",
195
+ );
196
+ process.exit(bad.length ? 1 : 0);
197
+ }
198
+
199
+ const isMain =
200
+ Boolean(process.argv[1]) &&
201
+ import.meta.url.endsWith(`/${process.argv[1].split(/[\\/]/).pop()}`);
202
+ if (isMain && process.argv.includes("--self-test")) selfTest();
203
+ else if (isMain) {
204
+ let raw = "";
205
+ process.stdin.on("data", (d) => (raw += d));
206
+ process.stdin.on("end", () => {
207
+ let payload;
208
+ try {
209
+ payload = JSON.parse(raw) ?? {};
210
+ } catch {
211
+ process.exit(0);
212
+ }
213
+ const dir = payload.cwd || process.env.CLAUDE_PROJECT_DIR || process.cwd();
214
+ const ignore = ignoreOf(process.env.CLAUDE_PROJECT_DIR || dir);
215
+ if (payload.hook_event_name === "Stop") {
216
+ const out = decideStop(
217
+ payload.session_id,
218
+ dir,
219
+ payload.stop_hook_active === true,
220
+ ignore,
221
+ );
222
+ if (out) process.stdout.write(JSON.stringify(out));
223
+ return;
224
+ }
225
+ const command = payload.tool_input?.command;
226
+ if (typeof command === "string")
227
+ recordPass(
228
+ payload.session_id,
229
+ dir,
230
+ command,
231
+ failedResponse(payload),
232
+ ignore,
233
+ );
234
+ });
235
+ }
package/dist/cli.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { defineCommand, defineProgram, ExitCode } from 'burgee';
2
+ import { checkContext, contextText } from './context.js';
2
3
  import { checkRepo, checkText, initRepo, packageRoot, packageVersion } from './core.js';
3
4
  import { cwd } from './runtime.js';
4
5
  const TEXT = Symbol.for('burgee.text');
@@ -46,9 +47,33 @@ const checkCommand = defineCommand({
46
47
  return data;
47
48
  },
48
49
  });
50
+ const contextCommand = defineCommand({
51
+ name: 'context',
52
+ description: "Fail when what Claude Code loads into every session outgrows the repo's token ceiling",
53
+ effects: 'idempotent',
54
+ examples: [
55
+ { command: 'hookset context', description: 'the CI gate: exit 1 over the ceiling in .claude/hookset.json' },
56
+ { command: 'hookset context --update', description: 'after a cut: lower the ceiling to the current size' },
57
+ ],
58
+ options: {
59
+ update: { type: 'boolean', description: 'lower the ceiling to the current size; never raises it' },
60
+ cwd: { type: 'string', description: 'the repo to measure (default: the current directory)' },
61
+ },
62
+ run: ({ options }) => {
63
+ const o = options;
64
+ const result = checkContext(repoOf(o), { update: o['update'] === true });
65
+ const data = {
66
+ ...result,
67
+ changed: result.updated,
68
+ ...(result.ok ? {} : { exitCode: ExitCode.RUNTIME, fix: result.fix }),
69
+ };
70
+ data[TEXT] = () => contextText(result);
71
+ return data;
72
+ },
73
+ });
49
74
  export const program = defineProgram({
50
75
  name: 'hookset',
51
76
  version: packageVersion(PKG),
52
77
  description: 'The verification stations as git and Claude hooks, the same in every repo',
53
- commands: [initCommand, checkCommand],
78
+ commands: [initCommand, checkCommand, contextCommand],
54
79
  });
@@ -0,0 +1,126 @@
1
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { join, posix } from 'node:path';
3
+ const CHARS_PER_TOKEN = 4;
4
+ const LARGEST_SHOWN = 5;
5
+ const FRONTMATTER = /^---\r?\n([\s\S]*?)\r?\n---/;
6
+ const USER_ONLY = /^disable-model-invocation:[ \t]*true[ \t]*$/m;
7
+ const LISTED_KEYS = [
8
+ ['name', /^name:[ \t]*(.*(?:\n[ \t].*)*)/m],
9
+ ['description', /^description:[ \t]*(.*(?:\n[ \t].*)*)/m],
10
+ ];
11
+ export const tokensOf = (chars) => Math.round(chars / CHARS_PER_TOKEN);
12
+ function memory(repo) {
13
+ const files = [];
14
+ let chars = 0;
15
+ const load = (file) => {
16
+ if (files.includes(file) || !existsSync(join(repo, file)))
17
+ return;
18
+ files.push(file);
19
+ const text = String(readFileSync(join(repo, file)));
20
+ chars += text.length;
21
+ for (const match of text.matchAll(/^@(\S+)/gm))
22
+ load(posix.normalize(posix.join(posix.dirname(file), match[1])));
23
+ };
24
+ load('CLAUDE.md');
25
+ return { chars, files };
26
+ }
27
+ function listed(repo) {
28
+ const out = [];
29
+ const walk = (dir, suffix) => {
30
+ if (!existsSync(join(repo, dir)))
31
+ return;
32
+ for (const entry of readdirSync(join(repo, dir), { withFileTypes: true })) {
33
+ const rel = `${dir}/${entry.name}`;
34
+ if (entry.isDirectory())
35
+ walk(rel, suffix);
36
+ else if (rel.endsWith(suffix))
37
+ out.push(rel);
38
+ }
39
+ };
40
+ walk('.claude/skills', '/SKILL.md');
41
+ walk('.claude/commands', '.md');
42
+ walk('.claude/agents', '.md');
43
+ return out.sort();
44
+ }
45
+ function entryOf(repo, file) {
46
+ const text = String(readFileSync(join(repo, file)));
47
+ const fm = FRONTMATTER.exec(text)?.[1] ?? '';
48
+ const userOnly = !file.startsWith('.claude/agents/') && USER_ONLY.test(fm);
49
+ let chars = 0;
50
+ if (!userOnly) {
51
+ for (const [key, pattern] of LISTED_KEYS) {
52
+ const value = pattern.exec(fm)?.[1];
53
+ if (value !== undefined)
54
+ chars += `${key}: ${value}`.length;
55
+ }
56
+ }
57
+ return { file, chars, userOnly };
58
+ }
59
+ export function measureContext(repo) {
60
+ const mem = memory(repo);
61
+ const entries = listed(repo).map((file) => entryOf(repo, file));
62
+ const chars = entries.reduce((sum, entry) => sum + entry.chars, mem.chars);
63
+ return {
64
+ tokens: tokensOf(chars),
65
+ memoryFiles: mem.files,
66
+ memoryChars: mem.chars,
67
+ entries,
68
+ };
69
+ }
70
+ function readConfig(repo) {
71
+ const path = join(repo, '.claude', 'hookset.json');
72
+ return existsSync(path) ? JSON.parse(String(readFileSync(path))) : {};
73
+ }
74
+ function ceilingOf(config) {
75
+ const tokens = config['context']?.tokens;
76
+ return typeof tokens === 'number' ? tokens : undefined;
77
+ }
78
+ export function checkContext(repo, options = {}) {
79
+ const measured = measureContext(repo);
80
+ const config = readConfig(repo);
81
+ const ceiling = ceilingOf(config);
82
+ const fail = (error, fix) => ({
83
+ ...measured,
84
+ ok: false,
85
+ ceiling,
86
+ updated: false,
87
+ error,
88
+ fix,
89
+ });
90
+ if (options.update === true) {
91
+ if (measured.tokens > (ceiling ?? Infinity)) {
92
+ return fail(`${measured.tokens} tokens is over the ceiling of ${ceiling}; --update only lowers it`, 'cut what was added, or raise context.tokens in .claude/hookset.json by decision');
93
+ }
94
+ const next = { ...config, context: { tokens: measured.tokens } };
95
+ mkdirSync(join(repo, '.claude'), { recursive: true });
96
+ writeFileSync(join(repo, '.claude', 'hookset.json'), `${JSON.stringify(next, undefined, 2)}\n`);
97
+ return { ...measured, ok: true, ceiling: measured.tokens, updated: true };
98
+ }
99
+ if (ceiling === undefined) {
100
+ return fail('no context ceiling in .claude/hookset.json', 'run `hookset context --update` to set it at the current size');
101
+ }
102
+ if (measured.tokens > ceiling) {
103
+ return fail(`always-loaded context is ${measured.tokens} tokens, over the ceiling of ${ceiling}`, 'shorten what you added, move a rule into a check, or mark a skill the model should never start itself `disable-model-invocation: true`');
104
+ }
105
+ return { ...measured, ok: true, ceiling, updated: false };
106
+ }
107
+ export function contextText(result) {
108
+ if (result.error !== undefined) {
109
+ const top = result.entries
110
+ .filter((e) => e.chars > 0)
111
+ .sort((a, b) => b.chars - a.chars)
112
+ .slice(0, LARGEST_SHOWN)
113
+ .map((e) => ` ${tokensOf(e.chars)} ${e.file}`);
114
+ return [
115
+ `✖ ${result.error}`,
116
+ ` CLAUDE.md and imports: ${tokensOf(result.memoryChars)} tokens (${result.memoryFiles.join(', ') || 'none'})`,
117
+ ...(top.length > 0 ? [' largest descriptions:', ...top] : []),
118
+ ` fix: ${result.fix}`,
119
+ ].join('\n');
120
+ }
121
+ if (result.updated)
122
+ return `ceiling set to ${result.tokens} tokens`;
123
+ const ceiling = result.ceiling;
124
+ const line = `✔ always-loaded context: ${result.tokens} tokens (ceiling ${ceiling})`;
125
+ return result.tokens < ceiling ? `${line}\n below the ceiling: run \`hookset context --update\` to lock in the cut` : line;
126
+ }
package/dist/core.d.ts CHANGED
@@ -15,6 +15,19 @@ export interface ClaudeHook {
15
15
  matcher: string;
16
16
  file: string;
17
17
  }
18
+ /** A skill every repo carries, such as `verify`: written from a template, then filled in by the repo. */
19
+ export interface ClaudeSkill {
20
+ id: string;
21
+ /** Where the repo keeps it, relative to the repo root. */
22
+ path: string;
23
+ /** The template `init --claude` writes, relative to the package root. */
24
+ template: string;
25
+ /** Text the filled-in skill still has to contain. */
26
+ requires: string[];
27
+ /** The marker the template puts on every line the repo has to replace. */
28
+ placeholder: string;
29
+ detail: string;
30
+ }
18
31
  export interface Stations {
19
32
  remote: string;
20
33
  tagPrefix: string;
@@ -23,6 +36,7 @@ export interface Stations {
23
36
  claude: {
24
37
  files: string[];
25
38
  hooks: ClaudeHook[];
39
+ skills: ClaudeSkill[];
26
40
  };
27
41
  }
28
42
  export interface Problem {
@@ -64,7 +78,9 @@ export interface CheckResult {
64
78
  }
65
79
  /** Everything `hookset check` reports for the repo at `repo`, against the presets in `pkg`. */
66
80
  export declare function checkRepo(repo: string, pkg: string): CheckResult;
67
- /** The pack's hooks, with stop-after-3 also on PostToolUseFailure (a failed Bash call lands there). */
81
+ /** A pack skill the repo must carry and fill in: present, still holding what it requires, no placeholder left. */
82
+ export declare function checkSkill(repo: string, skill: ClaudeSkill): Problem[];
83
+ /** The pack's hooks, each PostToolUse one also on PostToolUseFailure (a failed Bash call lands there). */
68
84
  export declare function expectedClaudeHooks(stations: Stations): ClaudeHook[];
69
85
  /** The lefthook.yml `hookset init` writes into a repo with none. */
70
86
  export declare function lefthookTemplate(stations: Stations, ref: string): string;
package/dist/core.js CHANGED
@@ -31,16 +31,18 @@ const listItem = (text) => (text.startsWith('- ') ? text.slice(2).trim() : undef
31
31
  const stripComment = (line) => String(line.split(' #', 1)[0]).trim();
32
32
  const REMOTE_KEYS = new Set(['git_url', 'ref', 'configs', 'refetch', 'refetch_frequency']);
33
33
  export function parseRemotes(yaml) {
34
- const lines = yaml.split(/\r?\n/);
34
+ return scanRemotes(yaml.split(/\r?\n/)).map(({ refAt: _, ...remote }) => remote);
35
+ }
36
+ function scanRemotes(lines) {
35
37
  const block = topBlock(lines, 'remotes');
36
38
  if (!block)
37
39
  return [];
38
40
  const state = { remotes: [], inConfigs: false };
39
- for (const raw of lines.slice(block.from + 1, block.to))
40
- remoteLine(state, stripComment(raw));
41
+ const from = block.from + 1;
42
+ lines.slice(from, block.to).forEach((raw, i) => remoteLine(state, stripComment(raw), from + i));
41
43
  return state.remotes;
42
44
  }
43
- function remoteLine(state, text) {
45
+ function remoteLine(state, text, at) {
44
46
  const item = listItem(text);
45
47
  const pair = keyValue(item ?? text);
46
48
  const isKey = pair !== undefined && (item === undefined || REMOTE_KEYS.has(pair[0]));
@@ -51,6 +53,8 @@ function remoteLine(state, text) {
51
53
  return;
52
54
  if (isKey) {
53
55
  state.inConfigs = pair[0] === 'configs';
56
+ if (pair[0] === 'ref')
57
+ current.refAt = at;
54
58
  assign(current, pair[0], pair[1]);
55
59
  }
56
60
  else if (item !== undefined && state.inConfigs)
@@ -199,6 +203,23 @@ function checkClaude(repo, pkg, stations) {
199
203
  problems.push({ id: 'claude-unwired', severity: 'error', message: `.claude/settings.json does not run ${h.file} on ${h.event} (${h.matcher})`, fix: 'run `hookset init --claude`' });
200
204
  }
201
205
  }
206
+ for (const skill of stations.claude.skills)
207
+ problems.push(...checkSkill(repo, skill));
208
+ return problems;
209
+ }
210
+ export function checkSkill(repo, skill) {
211
+ const file = join(repo, skill.path);
212
+ if (!existsSync(file))
213
+ return [{ id: `${skill.id}-skill-missing`, severity: 'error', message: `${skill.path} is missing: ${skill.detail}`, fix: `run \`hookset init --claude\`, then fill in every ${skill.placeholder} line` }];
214
+ const text = readText(file);
215
+ const problems = [];
216
+ const left = text.split(/\r?\n/).filter((l) => l.includes(skill.placeholder)).length;
217
+ if (left > 0)
218
+ problems.push({ id: `${skill.id}-skill-unfilled`, severity: 'error', message: `${skill.path} still has ${String(left)} ${skill.placeholder} line${left === 1 ? '' : 's'}`, fix: `replace each ${skill.placeholder} line with this repo's real steps` });
219
+ for (const need of skill.requires) {
220
+ if (!text.includes(need))
221
+ problems.push({ id: `${skill.id}-skill-incomplete`, severity: 'error', message: `${skill.path} has no \`${need}\``, fix: `put \`${need}\` back; the template shows where it goes` });
222
+ }
202
223
  return problems;
203
224
  }
204
225
  export function expectedClaudeHooks(stations) {
@@ -244,6 +265,9 @@ export function initRepo(repo, pkg, options = {}) {
244
265
  write(`.claude/hooks/${file}`, readText(join(pkg, 'claude', file)));
245
266
  if (!existsSync(join(repo, '.claude', 'hookset.json')))
246
267
  write('.claude/hookset.json', `${JSON.stringify({ ask: [], frozen: [] }, undefined, 2)}\n`);
268
+ for (const skill of stations.claude.skills)
269
+ if (!existsSync(join(repo, skill.path)))
270
+ write(skill.path, readText(join(pkg, skill.template)));
247
271
  write('.claude/settings.json', mergeSettings(repo, stations));
248
272
  }
249
273
  return { changed: written.length > 0, written };
@@ -254,21 +278,20 @@ function nextLefthook(repo, stations, ref, force) {
254
278
  return { text: lefthookTemplate(stations, ref) };
255
279
  const yaml = readText(file);
256
280
  if (parseRemotes(yaml).some((r) => sameRemote(r.gitUrl, stations.remote)))
257
- return { text: repin(yaml, ref) };
281
+ return { text: repin(yaml, ref, stations.remote) };
258
282
  if (yaml.split(/\r?\n/).some((l) => l.startsWith('remotes:')))
259
283
  return { refused: 'lefthook.yml already has a remotes: block; add the hookset remote to it by hand' };
260
284
  if (!force)
261
285
  return { refused: 'lefthook.yml was written by hand; pass --force to add the presets on top of it' };
262
286
  return { text: `${remotesBlock(stations, ref)}\n${yaml}` };
263
287
  }
264
- function repin(yaml, ref) {
288
+ function repin(yaml, ref, remote) {
265
289
  const eol = yaml.includes('\r\n') ? '\r\n' : '\n';
266
290
  const lines = yaml.split(/\r?\n/);
267
- const block = topBlock(lines, 'remotes');
268
- const at = lines.findIndex((l, i) => block !== undefined && i > block.from && i < block.to && keyValue(listItem(l.trim()) ?? l.trim())?.[0] === 'ref');
269
- const line = lines[at];
270
- if (line === undefined)
291
+ const at = scanRemotes(lines).find((r) => sameRemote(r.gitUrl, remote)).refAt;
292
+ if (at === undefined)
271
293
  return yaml;
294
+ const line = String(lines[at]);
272
295
  lines.splice(at, 1, `${line.slice(0, line.indexOf('ref:'))}ref: ${ref}`);
273
296
  return lines.join(eol);
274
297
  }
@@ -292,8 +315,18 @@ function mergeSettings(repo, stations) {
292
315
  settings.hooks = Object.fromEntries(events);
293
316
  return `${JSON.stringify(settings, undefined, 2)}\n`;
294
317
  }
318
+ function tally(problems) {
319
+ const counts = [];
320
+ for (const severity of ['error', 'warning']) {
321
+ const n = problems.filter((p) => p.severity === severity).length;
322
+ const plural = n === 1 ? '' : 's';
323
+ if (n > 0)
324
+ counts.push(`${String(n)} ${severity}${plural}`);
325
+ }
326
+ return counts.join(', ');
327
+ }
295
328
  export function checkText(result) {
296
329
  const lines = result.problems.map((p) => `${p.severity === 'error' ? '✗' : '!'} ${p.message}\n fix: ${p.fix}`);
297
- const head = result.ok ? `hookset: ok (${result.pinned ?? 'unpinned'})` : `hookset: ${String(result.problems.filter((p) => p.severity === 'error').length)} problem(s)`;
330
+ const head = result.ok ? `hookset: ok (${result.pinned ?? 'unpinned'})` : `hookset: ${tally(result.problems)}`;
298
331
  return [head, ...lines].join('\n');
299
332
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hookset",
3
- "version": "1.0.0",
3
+ "version": "1.1.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": [
@@ -15,7 +15,7 @@
15
15
  "cli"
16
16
  ],
17
17
  "license": "MIT",
18
- "homepage": "https://burgee.interlace.tools",
18
+ "homepage": "https://hookset.interlace.tools",
19
19
  "repository": {
20
20
  "type": "git",
21
21
  "url": "git+https://github.com/ofri-peretz/burgee.git",
@@ -54,10 +54,10 @@
54
54
  "typecheck": "tsc -p tsconfig.json --noEmit",
55
55
  "test": "vitest run",
56
56
  "coverage": "vitest run --coverage.enabled",
57
- "lint": "eslint src"
57
+ "lint": "cd ../.. && eslint packages/hookset/src --max-warnings 0"
58
58
  },
59
59
  "dependencies": {
60
- "burgee": "^2.1.3"
60
+ "burgee": "^2.2.2"
61
61
  },
62
62
  "devDependencies": {
63
63
  "vitest": "^5.0.1"
@@ -5,7 +5,7 @@ commit-msg:
5
5
  commands:
6
6
  hookset-commitlint:
7
7
  run: PATH="$PATH:/opt/homebrew/bin:/usr/local/bin" npx --no -- commitlint --edit {1}
8
- fail_text: "The message must be <type>(<scope>): <subject>, with a scope from commitlint.config. Fix it and commit again."
8
+ fail_text: "commitlint rejected the message. Each ✖ line above names the rule it broke (type, scope, length). Fix those and commit again."
9
9
  hookset-provedone:
10
10
  run: PATH="$PATH:/opt/homebrew/bin:/usr/local/bin" npm run --silent hook:provedone -- {1}
11
11
  fail_text: "No receipt. Add `Verified-by: <command> -> exit 0`, or `Verified-by: none (<why no check applies>)`, and commit again."
package/stations.json CHANGED
@@ -18,11 +18,16 @@
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"],
21
+ "files": ["guard-bash.mjs", "stop-after-3.mjs", "verify-before-stop.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
- { "event": "PostToolUse", "matcher": "Bash", "file": "stop-after-3.mjs" }
25
+ { "event": "PostToolUse", "matcher": "Bash", "file": "stop-after-3.mjs" },
26
+ { "event": "PostToolUse", "matcher": "Bash", "file": "verify-before-stop.mjs" },
27
+ { "event": "Stop", "matcher": "", "file": "verify-before-stop.mjs" }
28
+ ],
29
+ "skills": [
30
+ { "id": "verify", "path": ".claude/skills/verify/SKILL.md", "template": "claude/skills/verify/SKILL.md", "requires": ["name: verify", "## Feature map"], "placeholder": "TODO(verify)", "detail": "the skill that boots the app, drives the change and checks what it shows, with a feature map" }
26
31
  ]
27
32
  }
28
33
  }