hookset 0.0.1 → 1.0.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.
@@ -0,0 +1,158 @@
1
+ #!/usr/bin/env node
2
+ // stop-after-3 — Claude Code PostToolUse / PostToolUseFailure hook for Bash. Canonical copy:
3
+ // burgee packages/hookset/claude/. `hookset init --claude` vendors it next to guard-bash.mjs.
4
+ //
5
+ // "After three failed tries, stop and ask" was a sentence in CLAUDE.md, and a sentence is a
6
+ // suggestion. This counts failed test runs per session; a passing run resets the count, and the
7
+ // third failure in a row ends the turn (`continue: false`) with a message telling the agent to
8
+ // show the person what fails and ask how to proceed.
9
+ //
10
+ // A test run is a command whose words name a test runner (vitest, jest, `npm test`,
11
+ // `npm run test*`, `turbo run test`, `node --test`, `ci:local`, pytest, `cargo test`, `go test`).
12
+ // `node stop-after-3.mjs --self-test` runs the cases at the bottom.
13
+
14
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
15
+ import { tmpdir } from "node:os";
16
+ import { join } from "node:path";
17
+
18
+ import { commands } from "./guard-bash.mjs";
19
+
20
+ export const LIMIT = 3;
21
+
22
+ const RUNNERS = new Set(["vitest", "jest", "mocha", "pytest", "ava", "tap"]);
23
+ /** Words that hand the next word the job of being the command: `npx vitest`, `pnpm exec jest`. */
24
+ const LAUNCHERS = new Set(["npx", "bunx", "pnpx", "exec", "dlx", "--no", "--yes", "-y", "yarn", "--"]);
25
+
26
+ /** True when one command's words run a test suite. */
27
+ function runsTests(words) {
28
+ // The command word itself, past `VAR=value` assignments: `echo vitest` runs echo.
29
+ let start = 0;
30
+ while (/^\w+=/.test(words[start] ?? "")) start++;
31
+ for (let i = 0; i < words.length; i++) {
32
+ const w = words[i];
33
+ const next = words[i + 1] ?? "";
34
+ const head = i === start || LAUNCHERS.has(words[i - 1] ?? "");
35
+ // Every form counts only as the command itself: `echo npm test` runs echo.
36
+ if (!head) continue;
37
+ if (RUNNERS.has(w) || RUNNERS.has(w.split("/").pop())) return true;
38
+ if (/^(npm|pnpm|yarn|bun)$/.test(w) && (next === "test" || next === "t")) return true;
39
+ if (/^(npm|pnpm|yarn|bun)$/.test(w) && next === "run" && /^(test|ci:local)([:-].*)?$/.test(words[i + 2] ?? "")) return true;
40
+ if (w === "turbo" && next === "run" && words.slice(i + 2).some((x) => /^test([:-].*)?$/.test(x))) return true;
41
+ if (w === "node" && words.slice(i + 1).includes("--test")) return true;
42
+ if ((w === "cargo" || w === "go") && next === "test") return true;
43
+ if (w === "playwright" && next === "test") return true;
44
+ }
45
+ return false;
46
+ }
47
+
48
+ export function isTestCommand(command) {
49
+ return commands(command).some(runsTests);
50
+ }
51
+
52
+ function stateFile(session) {
53
+ const dir = join(tmpdir(), "hookset-stop-after-3");
54
+ mkdirSync(dir, { recursive: true });
55
+ return join(dir, `${String(session || "default").replace(/[^\w.-]/g, "_")}.json`);
56
+ }
57
+
58
+ function readCount(file) {
59
+ try {
60
+ return Number(JSON.parse(readFileSync(file, "utf8")).failures) || 0;
61
+ } catch {
62
+ return 0;
63
+ }
64
+ }
65
+
66
+ /**
67
+ * The hook's answer for one event: the JSON to print, or null. `failed` is true for a
68
+ * PostToolUseFailure event (or a PostToolUse whose response says it failed).
69
+ */
70
+ export function record(session, command, failed) {
71
+ if (!isTestCommand(command)) return null;
72
+ const file = stateFile(session);
73
+ if (!failed) {
74
+ rmSync(file, { force: true });
75
+ return null;
76
+ }
77
+ const failures = readCount(file) + 1;
78
+ if (failures < LIMIT) {
79
+ writeFileSync(file, JSON.stringify({ failures }));
80
+ return null;
81
+ }
82
+ rmSync(file, { force: true });
83
+ const reason =
84
+ `[stop-after-3] Tests have failed ${failures} times in a row this session. Stop here: ` +
85
+ "tell the person which tests fail, with the output, what you tried, and the options " +
86
+ "(keep trying on the failing tests only, change approach, or stop). Do not run them again until they answer.";
87
+ return { continue: false, stopReason: reason, systemMessage: reason };
88
+ }
89
+
90
+ /** True for a failed run, false for a pass, null for an interrupted run (it says nothing either way). */
91
+ function failedResponse(payload) {
92
+ if (payload.hook_event_name === "PostToolUseFailure") return true;
93
+ const r = payload.tool_response;
94
+ if (!r || typeof r !== "object") return false;
95
+ if (r.interrupted === true) return null;
96
+ const code = r.exitCode ?? r.exit_code ?? r.returnCode ?? r.code;
97
+ return typeof code === "number" ? code !== 0 : r.is_error === true || r.isError === true;
98
+ }
99
+
100
+ export const CASES = {
101
+ tests: [
102
+ "npx vitest run src/a.test.ts",
103
+ "npm test",
104
+ "npm run test -- --filter x",
105
+ "npm run ci:local",
106
+ "npx --no turbo run typecheck test build",
107
+ "node --test tests/",
108
+ "cd pkg && pnpm test",
109
+ "./node_modules/.bin/jest -t x",
110
+ "cargo test -p core",
111
+ ],
112
+ other: ["npm run build", "git commit -m 'fix tests'", "echo vitest", "echo npm test", "grep -r 'go test' docs", "npm run typecheck", "go build ./..."],
113
+ };
114
+
115
+ function selfTest() {
116
+ const session = `self-test-${process.pid}`;
117
+ const bad = [
118
+ ...CASES.tests.filter((c) => !isTestCommand(c)).map((c) => `should count: ${c}`),
119
+ ...CASES.other.filter((c) => isTestCommand(c)).map((c) => `should ignore: ${c}`),
120
+ ];
121
+ const seq = [record(session, "npm test", true), record(session, "npm test", true), record(session, "npm test", true)];
122
+ if (seq[0] || seq[1] || !seq[2] || seq[2].continue !== false) bad.push("third failure should stop the turn");
123
+ record(session, "npm test", true);
124
+ record(session, "npm test", false);
125
+ if (record(session, "npm test", true) || record(session, "npm test", true)) bad.push("a pass should reset the count");
126
+ record(session, "npm test", false);
127
+ // A passing command that only mentions a test run must not reset the count.
128
+ record(session, "npm test", true);
129
+ record(session, "npm test", true);
130
+ record(session, "echo npm test", false);
131
+ if (record(session, "npm test", true)?.continue !== false) bad.push("echo npm test should not reset the count");
132
+ record(session, "npm test", false);
133
+ process.stdout.write(bad.length ? `${bad.join("\n")}\n${bad.length} failing\n` : `ok: ${CASES.tests.length} counted, ${CASES.other.length} ignored, stop on ${LIMIT}\n`);
134
+ process.exit(bad.length ? 1 : 0);
135
+ }
136
+
137
+ // Imported (stop-after-3 reads `commands` from guard-bash) is not run: only the entry file acts.
138
+ const isMain = Boolean(process.argv[1]) && import.meta.url.endsWith(`/${process.argv[1].split(/[\\/]/).pop()}`);
139
+ if (isMain && process.argv.includes("--self-test")) selfTest();
140
+ else if (isMain) {
141
+ let raw = "";
142
+ process.stdin.on("data", (d) => (raw += d));
143
+ process.stdin.on("end", () => {
144
+ let payload;
145
+ try {
146
+ payload = JSON.parse(raw) ?? {};
147
+ } catch {
148
+ process.exit(0);
149
+ }
150
+ const command = payload.tool_input?.command;
151
+ if (typeof command !== "string") process.exit(0);
152
+ const failed = failedResponse(payload);
153
+ // An interrupted run neither fails nor passes: it leaves the count where it was.
154
+ if (failed === null) process.exit(0);
155
+ const out = record(payload.session_id, command, failed);
156
+ if (out) process.stdout.write(JSON.stringify(out));
157
+ });
158
+ }
package/dist/bin.js ADDED
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { run } from 'burgee';
3
+ import { program } from './cli.js';
4
+ await run(program);
package/dist/cli.js ADDED
@@ -0,0 +1,54 @@
1
+ import { defineCommand, defineProgram, ExitCode } from 'burgee';
2
+ import { checkRepo, checkText, initRepo, packageRoot, packageVersion } from './core.js';
3
+ import { cwd } from './runtime.js';
4
+ const TEXT = Symbol.for('burgee.text');
5
+ const PKG = packageRoot();
6
+ const repoOf = (options) => (typeof options['cwd'] === 'string' ? options['cwd'] : cwd());
7
+ const initCommand = defineCommand({
8
+ name: 'init',
9
+ description: 'Write the smallest lefthook.yml that pulls the hookset presets, pinned to this version',
10
+ effects: 'idempotent',
11
+ examples: [
12
+ { command: 'hookset init', description: 'a repo with no lefthook.yml: write one' },
13
+ { command: 'hookset init --force', description: 'a hand-written lefthook.yml: add the presets on top; `check` names the duplicates' },
14
+ { command: 'hookset init --claude', description: 'also vendor the Claude hook pack into .claude/ and wire it in settings.json' },
15
+ ],
16
+ options: {
17
+ force: { type: 'boolean', description: 'add the presets to a lefthook.yml hookset did not write' },
18
+ claude: { type: 'boolean', description: 'vendor guard-bash and stop-after-3 into .claude/hooks and wire them' },
19
+ cwd: { type: 'string', description: 'the repo to write in (default: the current directory)' },
20
+ },
21
+ run: ({ options }) => {
22
+ const o = options;
23
+ const result = initRepo(repoOf(o), PKG, { force: o['force'] === true, claude: o['claude'] === true });
24
+ const data = {
25
+ changed: result.changed,
26
+ written: result.written,
27
+ ...(result.refused === undefined ? {} : { exitCode: ExitCode.RUNTIME, error: result.refused, fix: 'pass --force, or add the remote by hand' }),
28
+ };
29
+ data[TEXT] = () => result.refused ?? (result.written.length ? `wrote ${result.written.join(', ')}` : 'already up to date');
30
+ return data;
31
+ },
32
+ });
33
+ const checkCommand = defineCommand({
34
+ name: 'check',
35
+ description: "Fail when a repo's hooks miss a station, pin no preset version, repeat a preset step, or drift from the Claude pack",
36
+ effects: 'read_only',
37
+ examples: [
38
+ { command: 'hookset check', description: 'the CI gate: exit 1 on any error, warnings listed' },
39
+ { command: 'hookset check --json', description: 'the problems as data, one fix line each' },
40
+ ],
41
+ options: { cwd: { type: 'string', description: 'the repo to check (default: the current directory)' } },
42
+ run: ({ options }) => {
43
+ const result = checkRepo(repoOf(options), PKG);
44
+ const data = { ...result, ...(result.ok ? {} : { exitCode: ExitCode.RUNTIME }) };
45
+ data[TEXT] = () => checkText(result);
46
+ return data;
47
+ },
48
+ });
49
+ export const program = defineProgram({
50
+ name: 'hookset',
51
+ version: packageVersion(PKG),
52
+ description: 'The verification stations as git and Claude hooks, the same in every repo',
53
+ commands: [initCommand, checkCommand],
54
+ });
package/dist/core.d.ts ADDED
@@ -0,0 +1,86 @@
1
+ export type Hook = 'commit-msg' | 'pre-commit' | 'pre-push';
2
+ export type Mode = 'enforce' | 'optional' | 'observe';
3
+ export interface Station {
4
+ id: string;
5
+ hook: Hook;
6
+ mode: Mode;
7
+ /** The command name the preset gives this station's step. */
8
+ command: string;
9
+ /** The repo script the step runs, when the repo decides what the station does. */
10
+ script?: string;
11
+ detail: string;
12
+ }
13
+ export interface ClaudeHook {
14
+ event: string;
15
+ matcher: string;
16
+ file: string;
17
+ }
18
+ export interface Stations {
19
+ remote: string;
20
+ tagPrefix: string;
21
+ presets: Record<Hook, string>;
22
+ stations: Station[];
23
+ claude: {
24
+ files: string[];
25
+ hooks: ClaudeHook[];
26
+ };
27
+ }
28
+ export interface Problem {
29
+ id: string;
30
+ severity: 'error' | 'warning';
31
+ message: string;
32
+ fix: string;
33
+ }
34
+ export interface Remote {
35
+ gitUrl: string;
36
+ ref: string | undefined;
37
+ configs: string[];
38
+ }
39
+ export interface Run {
40
+ hook: string;
41
+ command: string;
42
+ run: string;
43
+ }
44
+ /** The package root: the folder holding stations.json, presets/ and claude/. */
45
+ export declare function packageRoot(from?: string): string;
46
+ export declare function loadStations(pkg: string): Stations;
47
+ export declare function packageVersion(pkg: string): string;
48
+ /**
49
+ * The `remotes:` entries of a lefthook.yml. Read line by line: hookset writes this block itself,
50
+ * and a full YAML parser would be this package's only dependency. A remote starts at a list item
51
+ * whose first word is one of its keys; a configs entry is a list item that is a path.
52
+ */
53
+ export declare function parseRemotes(yaml: string): Remote[];
54
+ /** Every `run:` a lefthook.yml declares itself, outside `remotes:`, with its hook and command. */
55
+ export declare function localRuns(yaml: string): Run[];
56
+ /** True when a hand-written step repeats what a preset station already runs. */
57
+ export declare function duplicateOf(run: Run, stations: Station[]): Station | undefined;
58
+ export interface CheckResult {
59
+ ok: boolean;
60
+ /** The `hookset@…` tag the repo pins, when it pins one. */
61
+ pinned: string | undefined;
62
+ expected: string;
63
+ problems: Problem[];
64
+ }
65
+ /** Everything `hookset check` reports for the repo at `repo`, against the presets in `pkg`. */
66
+ 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). */
68
+ export declare function expectedClaudeHooks(stations: Stations): ClaudeHook[];
69
+ /** The lefthook.yml `hookset init` writes into a repo with none. */
70
+ export declare function lefthookTemplate(stations: Stations, ref: string): string;
71
+ export interface InitResult {
72
+ changed: boolean;
73
+ written: string[];
74
+ refused?: string;
75
+ }
76
+ /**
77
+ * Write or update the hookset wiring in `repo`. A lefthook.yml hookset did not write is refused
78
+ * unless `force`, which puts the remotes block on top and keeps every hand-written step (`check`
79
+ * then names the duplicates to delete). `claude` also vendors the Claude pack.
80
+ */
81
+ export declare function initRepo(repo: string, pkg: string, options?: {
82
+ force?: boolean;
83
+ claude?: boolean;
84
+ }): InitResult;
85
+ /** The text a person reads for a check result. */
86
+ export declare function checkText(result: CheckResult): string;
package/dist/core.js ADDED
@@ -0,0 +1,299 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ export function packageRoot(from = import.meta.url) {
5
+ return fileURLToPath(new URL('..', from));
6
+ }
7
+ const readText = (file) => readFileSync(file, 'utf8');
8
+ export function loadStations(pkg) {
9
+ return JSON.parse(readText(join(pkg, 'stations.json')));
10
+ }
11
+ export function packageVersion(pkg) {
12
+ return JSON.parse(readText(join(pkg, 'package.json'))).version;
13
+ }
14
+ const unquote = (text) => {
15
+ const bare = text.trim();
16
+ return bare.length > 1 && (bare[0] === '"' || bare[0] === "'") && bare.endsWith(bare[0]) ? bare.slice(1, -1) : bare;
17
+ };
18
+ const indentOf = (line) => line.length - line.trimStart().length;
19
+ function topBlock(lines, key) {
20
+ const from = lines.findIndex((l) => l.startsWith(`${key}:`));
21
+ if (from === -1)
22
+ return undefined;
23
+ const next = lines.findIndex((l, i) => i > from && /^[^\s#-]/.test(l));
24
+ return { from, to: next === -1 ? lines.length : next };
25
+ }
26
+ function keyValue(text) {
27
+ const m = /^([\w-]+):(.*)$/.exec(text);
28
+ return m ? [String(m[1]), String(m[2]).trim()] : undefined;
29
+ }
30
+ const listItem = (text) => (text.startsWith('- ') ? text.slice(2).trim() : undefined);
31
+ const stripComment = (line) => String(line.split(' #', 1)[0]).trim();
32
+ const REMOTE_KEYS = new Set(['git_url', 'ref', 'configs', 'refetch', 'refetch_frequency']);
33
+ export function parseRemotes(yaml) {
34
+ const lines = yaml.split(/\r?\n/);
35
+ const block = topBlock(lines, 'remotes');
36
+ if (!block)
37
+ return [];
38
+ const state = { remotes: [], inConfigs: false };
39
+ for (const raw of lines.slice(block.from + 1, block.to))
40
+ remoteLine(state, stripComment(raw));
41
+ return state.remotes;
42
+ }
43
+ function remoteLine(state, text) {
44
+ const item = listItem(text);
45
+ const pair = keyValue(item ?? text);
46
+ const isKey = pair !== undefined && (item === undefined || REMOTE_KEYS.has(pair[0]));
47
+ if (item !== undefined && isKey)
48
+ state.remotes.push({ gitUrl: '', ref: undefined, configs: [] });
49
+ const current = state.remotes.at(-1);
50
+ if (!current)
51
+ return;
52
+ if (isKey) {
53
+ state.inConfigs = pair[0] === 'configs';
54
+ assign(current, pair[0], pair[1]);
55
+ }
56
+ else if (item !== undefined && state.inConfigs)
57
+ current.configs.push(unquote(item));
58
+ }
59
+ function assign(remote, key, value) {
60
+ if (key === 'git_url')
61
+ remote.gitUrl = unquote(value);
62
+ else if (key === 'ref')
63
+ remote.ref = unquote(value);
64
+ else if (key === 'configs' && value.startsWith('['))
65
+ remote.configs.push(...value.slice(1, -1).split(',').map(unquote).filter(Boolean));
66
+ }
67
+ function blockBody(lines, at) {
68
+ const indent = indentOf(String(lines[at]));
69
+ const next = lines.findIndex((l, i) => i > at && l.trim() !== '' && indentOf(l) <= indent);
70
+ const end = (next === -1 ? lines.length : next) - 1;
71
+ return { text: lines.slice(at + 1, end + 1).map((l) => l.trim()).join('\n'), end };
72
+ }
73
+ const CONTAINERS = new Set(['commands', 'scripts', 'jobs']);
74
+ export function localRuns(yaml) {
75
+ const lines = yaml.split(/\r?\n/);
76
+ const runs = [];
77
+ const at = { hook: '', command: '' };
78
+ for (let i = 0; i < lines.length; i++) {
79
+ const pair = runLine(at, String(lines[i]));
80
+ if (pair?.[0] !== 'run')
81
+ continue;
82
+ let value = pair[1];
83
+ if (['|', '>', '|-', '>-'].includes(value)) {
84
+ const body = blockBody(lines, i);
85
+ value = body.text;
86
+ i = body.end;
87
+ }
88
+ runs.push({ hook: at.hook, command: at.command, run: unquote(value) });
89
+ }
90
+ return runs;
91
+ }
92
+ function runLine(at, line) {
93
+ if (!/^\s/.test(line)) {
94
+ at.hook = keyValue(line)?.[0] ?? at.hook;
95
+ return undefined;
96
+ }
97
+ if (at.hook === 'remotes')
98
+ return undefined;
99
+ const text = line.trim();
100
+ const pair = keyValue(listItem(text) ?? text);
101
+ if (pair && pair[1] === '' && !CONTAINERS.has(pair[0]))
102
+ at.command = pair[0];
103
+ return pair;
104
+ }
105
+ export function duplicateOf(run, stations) {
106
+ const words = run.run.split(/\s+/);
107
+ return stations.find((s) => {
108
+ if (s.id === 'commitlint')
109
+ return run.hook === 'commit-msg' && words.some((w) => w === 'commitlint' || w.endsWith('/commitlint')) && words.includes('--edit');
110
+ return words.includes(String(s.script));
111
+ });
112
+ }
113
+ const bareRemote = (url) => url.replace(/\/$/, '').replace(/\.git$/, '');
114
+ const sameRemote = (a, b) => bareRemote(a) === bareRemote(b);
115
+ function checkLefthook(repo, stations, expected, { error, warn }) {
116
+ const file = join(repo, 'lefthook.yml');
117
+ if (!existsSync(file)) {
118
+ error('no-lefthook', 'there is no lefthook.yml', 'run `hookset init`');
119
+ return undefined;
120
+ }
121
+ const yaml = readText(file);
122
+ for (const run of localRuns(yaml)) {
123
+ const dup = duplicateOf(run, stations.stations);
124
+ if (dup)
125
+ error('duplicate', `${run.hook} → ${run.command} repeats the ${dup.id} station the preset already runs`, `delete ${run.hook}.commands.${run.command} from lefthook.yml`);
126
+ }
127
+ const remote = parseRemotes(yaml).find((r) => sameRemote(r.gitUrl, stations.remote));
128
+ if (!remote) {
129
+ error('no-remote', `lefthook.yml does not pull the presets from ${stations.remote}`, 'run `hookset init --force`');
130
+ return undefined;
131
+ }
132
+ for (const [hook, preset] of Object.entries(stations.presets)) {
133
+ if (!remote.configs.includes(preset))
134
+ error('missing-preset', `the ${hook} preset is not pulled (${preset})`, `add \`- ${preset}\` under the remote's configs`);
135
+ }
136
+ const ref = remote.ref ?? '';
137
+ if (!ref.startsWith(stations.tagPrefix)) {
138
+ error('unpinned', `the presets remote is pinned to ${ref || 'the default branch'}, not a ${stations.tagPrefix}<version> tag`, `set \`ref: ${expected}\``);
139
+ return undefined;
140
+ }
141
+ if (ref !== expected)
142
+ warn('behind', `the presets are pinned to ${ref}; this hookset is ${expected}`, `set \`ref: ${expected}\` (\`hookset init\` does it)`);
143
+ return ref;
144
+ }
145
+ function checkScripts(repo, stations, { error, warn }) {
146
+ const manifest = join(repo, 'package.json');
147
+ if (!existsSync(manifest)) {
148
+ error('no-package', 'there is no package.json to declare the station scripts in', 'add a private package.json with lefthook as a devDependency');
149
+ return;
150
+ }
151
+ const scripts = new Map(Object.entries(JSON.parse(readText(manifest)).scripts ?? {}));
152
+ if (!(scripts.get('prepare') ?? '').includes('lefthook install'))
153
+ error('not-installed', 'nothing installs the hooks: package.json has no `prepare` running `lefthook install`', 'add `"prepare": "lefthook install || true"`');
154
+ for (const s of stations.stations) {
155
+ if (s.script === undefined || scripts.has(s.script))
156
+ continue;
157
+ if (s.mode === 'enforce')
158
+ error('missing-script', `the ${s.id} station runs \`npm run ${s.script}\`, and package.json does not declare it`, `add "${s.script}" to package.json scripts: ${s.detail}`);
159
+ else
160
+ warn('station-off', `the ${s.id} station is not declared yet (${s.mode})`, `add "${s.script}" to package.json scripts when the repo has it: ${s.detail}`);
161
+ }
162
+ }
163
+ export function checkRepo(repo, pkg) {
164
+ const stations = loadStations(pkg);
165
+ const expected = `${stations.tagPrefix}${packageVersion(pkg)}`;
166
+ const problems = [];
167
+ const error = (id, message, fix) => void problems.push({ id, severity: 'error', message, fix });
168
+ const warn = (id, message, fix) => void problems.push({ id, severity: 'warning', message, fix });
169
+ const pinned = checkLefthook(repo, stations, expected, { error, warn });
170
+ checkScripts(repo, stations, { error, warn });
171
+ const claudeDir = join(repo, '.claude');
172
+ if (existsSync(join(claudeDir, 'hookset.json')))
173
+ problems.push(...checkClaude(repo, pkg, stations));
174
+ else if (existsSync(claudeDir))
175
+ warn('claude-not-adopted', 'the repo has a .claude/ directory without the hookset Claude pack', 'run `hookset init --claude`');
176
+ return { ok: !problems.some((p) => p.severity === 'error'), pinned, expected, problems };
177
+ }
178
+ function settingsCommands(repo) {
179
+ const file = join(repo, '.claude', 'settings.json');
180
+ if (!existsSync(file))
181
+ return [];
182
+ const settings = JSON.parse(readText(file));
183
+ return Object.entries(settings.hooks ?? {}).flatMap(([event, groups]) => groups.flatMap((g) => (g.hooks ?? []).map((h) => ({ event, matcher: g.matcher ?? '', command: h.command ?? '' }))));
184
+ }
185
+ const hookCommand = (file) => `node "$CLAUDE_PROJECT_DIR/.claude/hooks/${file}"`;
186
+ function checkClaude(repo, pkg, stations) {
187
+ const problems = [];
188
+ for (const file of stations.claude.files) {
189
+ const vendored = join(repo, '.claude', 'hooks', file);
190
+ if (!existsSync(vendored))
191
+ problems.push({ id: 'claude-missing', severity: 'error', message: `.claude/hooks/${file} is missing`, fix: 'run `hookset init --claude`' });
192
+ else if (readText(vendored) !== readText(join(pkg, 'claude', file))) {
193
+ problems.push({ id: 'claude-drift', severity: 'error', message: `.claude/hooks/${file} differs from the hookset copy`, fix: 'run `hookset init --claude`; change the canonical copy in burgee, not the vendored one' });
194
+ }
195
+ }
196
+ const wired = settingsCommands(repo);
197
+ for (const h of expectedClaudeHooks(stations)) {
198
+ if (!wired.some((w) => w.event === h.event && w.matcher === h.matcher && w.command.includes(`.claude/hooks/${h.file}`))) {
199
+ 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
+ }
201
+ }
202
+ return problems;
203
+ }
204
+ export function expectedClaudeHooks(stations) {
205
+ return stations.claude.hooks.flatMap((h) => (h.event === 'PostToolUse' ? [h, { ...h, event: 'PostToolUseFailure' }] : [h]));
206
+ }
207
+ export function lefthookTemplate(stations, ref) {
208
+ return `# Git hooks. The stations come from the hookset presets (burgee packages/hookset), pinned by tag:
209
+ # bump \`ref\` to take a new preset version. \`hookset check\` (CI) fails on a missing station, an
210
+ # unpinned ref, or a step here that repeats one a preset runs.
211
+ ${remotesBlock(stations, ref)}
212
+ # Repo-specific steps go below, under the hook they belong to. The presets call the repo's own
213
+ # \`hook:staged\` and \`hook:verify\` scripts (package.json), so most repos need nothing here.
214
+ `;
215
+ }
216
+ function remotesBlock(stations, ref) {
217
+ return `remotes:
218
+ - git_url: ${stations.remote}
219
+ ref: ${ref}
220
+ configs:
221
+ ${Object.values(stations.presets)
222
+ .map((p) => ` - ${p}`)
223
+ .join('\n')}
224
+ `;
225
+ }
226
+ export function initRepo(repo, pkg, options = {}) {
227
+ const stations = loadStations(pkg);
228
+ const ref = `${stations.tagPrefix}${packageVersion(pkg)}`;
229
+ const written = [];
230
+ const write = (rel, text) => {
231
+ const file = join(repo, rel);
232
+ if (existsSync(file) && readText(file) === text)
233
+ return;
234
+ mkdirSync(join(file, '..'), { recursive: true });
235
+ writeFileSync(file, text);
236
+ written.push(rel);
237
+ };
238
+ const lefthook = nextLefthook(repo, stations, ref, options.force === true);
239
+ if ('refused' in lefthook)
240
+ return { changed: false, written, refused: lefthook.refused };
241
+ write('lefthook.yml', lefthook.text);
242
+ if (options.claude) {
243
+ for (const file of stations.claude.files)
244
+ write(`.claude/hooks/${file}`, readText(join(pkg, 'claude', file)));
245
+ if (!existsSync(join(repo, '.claude', 'hookset.json')))
246
+ write('.claude/hookset.json', `${JSON.stringify({ ask: [], frozen: [] }, undefined, 2)}\n`);
247
+ write('.claude/settings.json', mergeSettings(repo, stations));
248
+ }
249
+ return { changed: written.length > 0, written };
250
+ }
251
+ function nextLefthook(repo, stations, ref, force) {
252
+ const file = join(repo, 'lefthook.yml');
253
+ if (!existsSync(file))
254
+ return { text: lefthookTemplate(stations, ref) };
255
+ const yaml = readText(file);
256
+ if (parseRemotes(yaml).some((r) => sameRemote(r.gitUrl, stations.remote)))
257
+ return { text: repin(yaml, ref) };
258
+ if (yaml.split(/\r?\n/).some((l) => l.startsWith('remotes:')))
259
+ return { refused: 'lefthook.yml already has a remotes: block; add the hookset remote to it by hand' };
260
+ if (!force)
261
+ return { refused: 'lefthook.yml was written by hand; pass --force to add the presets on top of it' };
262
+ return { text: `${remotesBlock(stations, ref)}\n${yaml}` };
263
+ }
264
+ function repin(yaml, ref) {
265
+ const eol = yaml.includes('\r\n') ? '\r\n' : '\n';
266
+ 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)
271
+ return yaml;
272
+ lines.splice(at, 1, `${line.slice(0, line.indexOf('ref:'))}ref: ${ref}`);
273
+ return lines.join(eol);
274
+ }
275
+ function mergeSettings(repo, stations) {
276
+ const file = join(repo, '.claude', 'settings.json');
277
+ const settings = existsSync(file)
278
+ ? JSON.parse(readText(file))
279
+ : { $schema: 'https://json.schemastore.org/claude-code-settings.json' };
280
+ const events = new Map(Object.entries(settings.hooks ?? {}));
281
+ for (const h of expectedClaudeHooks(stations)) {
282
+ const groups = events.get(h.event) ?? [];
283
+ events.set(h.event, groups);
284
+ if (groups.some((g) => (g.matcher ?? '') === h.matcher && g.hooks.some((c) => c.command.includes(`.claude/hooks/${h.file}`))))
285
+ continue;
286
+ const group = groups.find((g) => (g.matcher ?? '') === h.matcher);
287
+ if (group)
288
+ group.hooks.push({ type: 'command', command: hookCommand(h.file) });
289
+ else
290
+ groups.push({ matcher: h.matcher, hooks: [{ type: 'command', command: hookCommand(h.file) }] });
291
+ }
292
+ settings.hooks = Object.fromEntries(events);
293
+ return `${JSON.stringify(settings, undefined, 2)}\n`;
294
+ }
295
+ export function checkText(result) {
296
+ 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)`;
298
+ return [head, ...lines].join('\n');
299
+ }
@@ -0,0 +1 @@
1
+ export * from './core.js';
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export * from './core.js';
@@ -0,0 +1 @@
1
+ export const cwd = () => process.cwd();