hookset 1.0.1 → 1.1.1
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 +2 -0
- package/claude/skills/verify/SKILL.md +38 -0
- package/claude/verify-before-stop.mjs +306 -0
- package/dist/cli.js +26 -1
- package/dist/context.js +126 -0
- package/dist/core.d.ts +17 -1
- package/dist/core.js +20 -0
- package/package.json +1 -1
- package/stations.json +7 -2
package/README.md
CHANGED
|
@@ -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
|
|
|
@@ -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,306 @@
|
|
|
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 { commands, globToRegExp } from "./guard-bash.mjs";
|
|
33
|
+
import { isTestCommand } from "./stop-after-3.mjs";
|
|
34
|
+
|
|
35
|
+
const DOCS = /\.(md|mdx|txt)$/i;
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The uncommitted paths `git status` lists, staged, unstaged and untracked, relative to the repo
|
|
39
|
+
* root. A rename lists both sides, so code renamed to a doc still counts; a copy only its new path.
|
|
40
|
+
*/
|
|
41
|
+
export function changedPaths(dir) {
|
|
42
|
+
const r = spawnSync(
|
|
43
|
+
"git",
|
|
44
|
+
["status", "--porcelain=v1", "-z", "--untracked-files=all"],
|
|
45
|
+
{ cwd: dir, encoding: "utf8" },
|
|
46
|
+
);
|
|
47
|
+
if (r.status !== 0) return [];
|
|
48
|
+
const parts = r.stdout.split("\0").filter(Boolean);
|
|
49
|
+
const paths = [];
|
|
50
|
+
for (let i = 0; i < parts.length; i++) {
|
|
51
|
+
const entry = parts[i];
|
|
52
|
+
paths.push(entry.slice(3));
|
|
53
|
+
// A rename or copy is followed by its old path. A rename removed it; a copy left it as it was.
|
|
54
|
+
if (entry[0] === "R" && parts[i + 1]) paths.push(parts[i + 1]);
|
|
55
|
+
if (entry[0] === "R" || entry[0] === "C") i++;
|
|
56
|
+
}
|
|
57
|
+
return paths;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** True when `path` is code this hook judges: not docs, not a glob the repo ignores. */
|
|
61
|
+
export function counts(path, ignore = []) {
|
|
62
|
+
const rel = path.replaceAll("\\", "/");
|
|
63
|
+
return !DOCS.test(rel) && !ignore.some((g) => globToRegExp(g).test(rel));
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** The work tree's root, so a hook whose cwd is a package still reads root-relative paths. */
|
|
67
|
+
function rootOf(dir) {
|
|
68
|
+
const r = spawnSync("git", ["rev-parse", "--show-toplevel"], {
|
|
69
|
+
cwd: dir,
|
|
70
|
+
encoding: "utf8",
|
|
71
|
+
});
|
|
72
|
+
return r.status === 0 && r.stdout.trim() ? r.stdout.trim() : dir;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** One hash over every uncommitted code path and its content, or null when there is none. */
|
|
76
|
+
export function fingerprint(cwd, ignore = []) {
|
|
77
|
+
const dir = rootOf(cwd);
|
|
78
|
+
const paths = changedPaths(dir)
|
|
79
|
+
.filter((p) => counts(p, ignore))
|
|
80
|
+
.sort();
|
|
81
|
+
if (paths.length === 0) return null;
|
|
82
|
+
const hash = createHash("sha256");
|
|
83
|
+
for (const p of paths) {
|
|
84
|
+
const file = join(dir, p);
|
|
85
|
+
hash.update(p).update("\0");
|
|
86
|
+
hash
|
|
87
|
+
.update(existsSync(file) ? readFileSync(file) : "<deleted>")
|
|
88
|
+
.update("\0");
|
|
89
|
+
}
|
|
90
|
+
return { hash: hash.digest("hex"), paths };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function stateFile(session) {
|
|
94
|
+
const dir = join(tmpdir(), "hookset-verify-before-stop");
|
|
95
|
+
mkdirSync(dir, { recursive: true });
|
|
96
|
+
return join(
|
|
97
|
+
dir,
|
|
98
|
+
`${String(session || "default").replace(/[^\w.-]/g, "_")}.json`,
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function passedHash(session) {
|
|
103
|
+
try {
|
|
104
|
+
return JSON.parse(readFileSync(stateFile(session), "utf8")).hash ?? null;
|
|
105
|
+
} catch {
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* True when the shell's exit status is the test run's own: the test is the last command and no
|
|
112
|
+
* `|`, `||`, `;` or `&` can hide its failure or run an edit after it. `cd pkg && npx vitest run`
|
|
113
|
+
* proves a pass; `npm test || true`, `npm test | tail` and `npm test && sed -i … a.ts` do not.
|
|
114
|
+
*/
|
|
115
|
+
export function provesPass(command) {
|
|
116
|
+
// `2>&1` merges streams; its `&` is not a background launch.
|
|
117
|
+
const merged = String(command).replace(/\d*>&\d+/g, " ");
|
|
118
|
+
const bare = merged
|
|
119
|
+
.replace(/'[^']*'|"(?:\\.|[^"\\])*"/g, '""')
|
|
120
|
+
.replaceAll("&&", " ");
|
|
121
|
+
if (/[|;&\n]/.test(bare)) return false;
|
|
122
|
+
const last = commands(merged).at(-1);
|
|
123
|
+
return Boolean(last) && isTestCommand(last.join(" "));
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* PostToolUse: a passing foreground test run (`{ command, failed, background }`) remembers what
|
|
128
|
+
* the code looked like. A background launch returns before its tests finish. Prints nothing.
|
|
129
|
+
*/
|
|
130
|
+
export function recordPass(
|
|
131
|
+
session,
|
|
132
|
+
dir,
|
|
133
|
+
{ command, failed, background = false },
|
|
134
|
+
ignore = [],
|
|
135
|
+
) {
|
|
136
|
+
if (failed || background || !provesPass(command)) return;
|
|
137
|
+
const fp = fingerprint(dir, ignore);
|
|
138
|
+
// A pass with nothing uncommitted proves the committed tree; forget any older fingerprint.
|
|
139
|
+
if (fp) writeFileSync(stateFile(session), JSON.stringify({ hash: fp.hash }));
|
|
140
|
+
else rmSync(stateFile(session), { force: true });
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Stop: the JSON that sends the turn back, or null to let it end. */
|
|
144
|
+
export function decideStop(session, dir, active, ignore = []) {
|
|
145
|
+
if (active) return null;
|
|
146
|
+
const fp = fingerprint(dir, ignore);
|
|
147
|
+
if (!fp || fp.hash === passedHash(session)) return null;
|
|
148
|
+
const shown =
|
|
149
|
+
fp.paths.slice(0, 5).join(", ") +
|
|
150
|
+
(fp.paths.length > 5 ? `, and ${fp.paths.length - 5} more` : "");
|
|
151
|
+
return {
|
|
152
|
+
decision: "block",
|
|
153
|
+
reason:
|
|
154
|
+
`[verify-before-stop] Code changed since the last passing test run (${shown}). ` +
|
|
155
|
+
"Run the tests that cover it, or the repo's verify skill, in the foreground as the last command with no pipe, `||`, `;` or `&` after it, and say what passed. " +
|
|
156
|
+
"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.",
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** The repo's `verifyIgnore` globs from .claude/hookset.json. Missing is none. */
|
|
161
|
+
function ignoreOf(dir) {
|
|
162
|
+
try {
|
|
163
|
+
const list = JSON.parse(
|
|
164
|
+
readFileSync(join(dir, ".claude", "hookset.json"), "utf8"),
|
|
165
|
+
).verifyIgnore;
|
|
166
|
+
return Array.isArray(list) ? list.map(String) : [];
|
|
167
|
+
} catch {
|
|
168
|
+
return [];
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function failedResponse(payload) {
|
|
173
|
+
if (payload.hook_event_name === "PostToolUseFailure") return true;
|
|
174
|
+
const r = payload.tool_response;
|
|
175
|
+
if (!r || typeof r !== "object") return false;
|
|
176
|
+
if (r.interrupted === true) return true;
|
|
177
|
+
const code = r.exitCode ?? r.exit_code ?? r.returnCode ?? r.code;
|
|
178
|
+
return typeof code === "number"
|
|
179
|
+
? code !== 0
|
|
180
|
+
: r.is_error === true || r.isError === true;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function selfTest() {
|
|
184
|
+
const bad = [];
|
|
185
|
+
const dir = join(tmpdir(), `hookset-vbs-${process.pid}`);
|
|
186
|
+
rmSync(dir, { recursive: true, force: true });
|
|
187
|
+
mkdirSync(dir, { recursive: true });
|
|
188
|
+
const env = Object.fromEntries(Object.entries(process.env).filter(([k]) => !k.startsWith("GIT_")));
|
|
189
|
+
const git = (...a) => spawnSync("git", a, { cwd: dir, encoding: "utf8", env });
|
|
190
|
+
git("init", "-q");
|
|
191
|
+
git(
|
|
192
|
+
"-c",
|
|
193
|
+
"user.email=t@t",
|
|
194
|
+
"-c",
|
|
195
|
+
"user.name=t",
|
|
196
|
+
"commit",
|
|
197
|
+
"-q",
|
|
198
|
+
"--allow-empty",
|
|
199
|
+
"-m",
|
|
200
|
+
"root",
|
|
201
|
+
);
|
|
202
|
+
const session = `self-test-${process.pid}`;
|
|
203
|
+
rmSync(stateFile(session), { force: true });
|
|
204
|
+
|
|
205
|
+
if (decideStop(session, dir, false))
|
|
206
|
+
bad.push("a clean tree should end the turn");
|
|
207
|
+
writeFileSync(join(dir, "notes.md"), "x");
|
|
208
|
+
if (decideStop(session, dir, false))
|
|
209
|
+
bad.push("a docs-only change should end the turn");
|
|
210
|
+
writeFileSync(join(dir, "a.ts"), "export const a = 1;\n");
|
|
211
|
+
if (decideStop(session, dir, false)?.decision !== "block")
|
|
212
|
+
bad.push("untested code should send the turn back");
|
|
213
|
+
if (decideStop(session, dir, true))
|
|
214
|
+
bad.push("the second stop of a turn should always pass");
|
|
215
|
+
if (decideStop(session, dir, false, ["*.ts"]))
|
|
216
|
+
bad.push("a verifyIgnore glob should not count");
|
|
217
|
+
recordPass(session, dir, { command: "npm run build", failed: false });
|
|
218
|
+
if (!decideStop(session, dir, false)) bad.push("a build is not a test run");
|
|
219
|
+
recordPass(session, dir, { command: "npx vitest run", failed: true });
|
|
220
|
+
if (!decideStop(session, dir, false))
|
|
221
|
+
bad.push("a failing test run is not a pass");
|
|
222
|
+
recordPass(session, dir, { command: "npx vitest run", failed: false });
|
|
223
|
+
if (decideStop(session, dir, false))
|
|
224
|
+
bad.push("a passing run over this code should end the turn");
|
|
225
|
+
writeFileSync(join(dir, "a.ts"), "export const a = 2;\n");
|
|
226
|
+
if (!decideStop(session, dir, false))
|
|
227
|
+
bad.push("an edit after the pass should send the turn back");
|
|
228
|
+
for (const command of [
|
|
229
|
+
"npm test || true",
|
|
230
|
+
"npx vitest run 2>&1 | tail -5",
|
|
231
|
+
"npm test; echo done",
|
|
232
|
+
"npm test && sed -i s/2/3/ a.ts",
|
|
233
|
+
]) {
|
|
234
|
+
recordPass(session, dir, { command, failed: false });
|
|
235
|
+
if (!decideStop(session, dir, false))
|
|
236
|
+
bad.push(`"${command}" cannot prove a pass`);
|
|
237
|
+
}
|
|
238
|
+
recordPass(session, dir, { command: "npm test", failed: false, background: true });
|
|
239
|
+
if (!decideStop(session, dir, false))
|
|
240
|
+
bad.push("a background launch is not a finished run");
|
|
241
|
+
mkdirSync(join(dir, "pkg"), { recursive: true });
|
|
242
|
+
writeFileSync(join(dir, "pkg", "b.ts"), "export const b = 1;\n");
|
|
243
|
+
recordPass(session, join(dir, "pkg"), {
|
|
244
|
+
command: "npx vitest run 2>&1",
|
|
245
|
+
failed: false,
|
|
246
|
+
});
|
|
247
|
+
if (decideStop(session, join(dir, "pkg"), false))
|
|
248
|
+
bad.push("a pass from a package directory should cover the same tree");
|
|
249
|
+
writeFileSync(join(dir, "pkg", "b.ts"), "export const b = 2;\n");
|
|
250
|
+
if (!decideStop(session, join(dir, "pkg"), false))
|
|
251
|
+
bad.push("an edit seen from a package directory should send the turn back");
|
|
252
|
+
git("add", "-A");
|
|
253
|
+
git("-c", "user.email=t@t", "-c", "user.name=t", "commit", "-q", "-m", "code");
|
|
254
|
+
git("mv", "a.ts", "a.md");
|
|
255
|
+
rmSync(stateFile(session), { force: true });
|
|
256
|
+
if (!decideStop(session, dir, false))
|
|
257
|
+
bad.push("renaming code to a doc removes code and should send the turn back");
|
|
258
|
+
|
|
259
|
+
rmSync(stateFile(session), { force: true });
|
|
260
|
+
rmSync(dir, { recursive: true, force: true });
|
|
261
|
+
process.stdout.write(
|
|
262
|
+
bad.length ? `${bad.join("\n")}\n${bad.length} failing\n` : "ok: 17 cases\n",
|
|
263
|
+
);
|
|
264
|
+
process.exit(bad.length ? 1 : 0);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
const isMain =
|
|
268
|
+
Boolean(process.argv[1]) &&
|
|
269
|
+
import.meta.url.endsWith(`/${process.argv[1].split(/[\\/]/).pop()}`);
|
|
270
|
+
if (isMain && process.argv.includes("--self-test")) selfTest();
|
|
271
|
+
else if (isMain) {
|
|
272
|
+
let raw = "";
|
|
273
|
+
process.stdin.on("data", (d) => (raw += d));
|
|
274
|
+
process.stdin.on("end", () => {
|
|
275
|
+
let payload;
|
|
276
|
+
try {
|
|
277
|
+
payload = JSON.parse(raw) ?? {};
|
|
278
|
+
} catch {
|
|
279
|
+
process.exit(0);
|
|
280
|
+
}
|
|
281
|
+
const dir = payload.cwd || process.env.CLAUDE_PROJECT_DIR || process.cwd();
|
|
282
|
+
const ignore = ignoreOf(process.env.CLAUDE_PROJECT_DIR || dir);
|
|
283
|
+
if (payload.hook_event_name === "Stop") {
|
|
284
|
+
const out = decideStop(
|
|
285
|
+
payload.session_id,
|
|
286
|
+
dir,
|
|
287
|
+
payload.stop_hook_active === true,
|
|
288
|
+
ignore,
|
|
289
|
+
);
|
|
290
|
+
if (out) process.stdout.write(JSON.stringify(out));
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
const command = payload.tool_input?.command;
|
|
294
|
+
if (typeof command === "string")
|
|
295
|
+
recordPass(
|
|
296
|
+
payload.session_id,
|
|
297
|
+
dir,
|
|
298
|
+
{
|
|
299
|
+
command,
|
|
300
|
+
failed: failedResponse(payload),
|
|
301
|
+
background: payload.tool_input?.run_in_background === true,
|
|
302
|
+
},
|
|
303
|
+
ignore,
|
|
304
|
+
);
|
|
305
|
+
});
|
|
306
|
+
}
|
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
|
});
|
package/dist/context.js
ADDED
|
@@ -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
|
-
/**
|
|
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
|
@@ -203,6 +203,23 @@ function checkClaude(repo, pkg, stations) {
|
|
|
203
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`' });
|
|
204
204
|
}
|
|
205
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
|
+
}
|
|
206
223
|
return problems;
|
|
207
224
|
}
|
|
208
225
|
export function expectedClaudeHooks(stations) {
|
|
@@ -248,6 +265,9 @@ export function initRepo(repo, pkg, options = {}) {
|
|
|
248
265
|
write(`.claude/hooks/${file}`, readText(join(pkg, 'claude', file)));
|
|
249
266
|
if (!existsSync(join(repo, '.claude', 'hookset.json')))
|
|
250
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)));
|
|
251
271
|
write('.claude/settings.json', mergeSettings(repo, stations));
|
|
252
272
|
}
|
|
253
273
|
return { changed: written.length > 0, written };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "hookset",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.1.1",
|
|
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": [
|
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
|
}
|