hookset 0.0.0-stage → 0.2.2
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/LICENSE +21 -0
- package/README.md +203 -2
- package/claude/guard-bash.mjs +435 -0
- package/claude/stop-after-3.mjs +158 -0
- package/dist/bin.js +4 -0
- package/dist/cli.js +54 -0
- package/dist/core.d.ts +86 -0
- package/dist/core.js +299 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/runtime.js +1 -0
- package/package.json +73 -4
- package/presets/lefthook/commit-msg.yml +8 -0
- package/presets/lefthook/pre-commit.yml +7 -0
- package/presets/lefthook/pre-push.yml +22 -0
- package/stations.json +27 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ofri Peretz
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,204 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<a href="https://github.com/ofri-peretz/burgee/tree/main/packages/hookset" target="blank">
|
|
3
|
+
<picture>
|
|
4
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ofri-peretz/burgee/main/brand-assets/hookset-lockup.svg" />
|
|
5
|
+
<img src="https://raw.githubusercontent.com/ofri-peretz/burgee/main/brand-assets/hookset-lockup-light.svg" alt="hookset" width="360" />
|
|
6
|
+
</picture>
|
|
7
|
+
</a>
|
|
8
|
+
</p>
|
|
2
9
|
|
|
3
|
-
|
|
10
|
+
<p align="center">
|
|
11
|
+
Every repo, the same hooks: the verification stations as lefthook presets and a Claude Code hook pack, pinned by tag.
|
|
12
|
+
</p>
|
|
13
|
+
|
|
14
|
+
<p align="center">
|
|
15
|
+
<a href="https://www.npmjs.com/package/hookset"><img src="https://img.shields.io/npm/v/hookset?style=flat-square&color=0a6b47" alt="hookset on npm: the latest version" /></a>
|
|
16
|
+
<a href="https://www.npmjs.com/package/hookset"><img src="https://img.shields.io/npm/dm/hookset?style=flat-square" alt="hookset downloads per month on npm" /></a>
|
|
17
|
+
<a href="https://github.com/ofri-peretz/burgee/actions/workflows/quality.yml?query=branch%3Amain"><img src="https://img.shields.io/github/actions/workflow/status/ofri-peretz/burgee/quality.yml?branch=main&style=flat-square&label=Quality%20Gate" alt="Quality Gate: the CI status of main" /></a>
|
|
18
|
+
<a href="https://app.codecov.io/gh/ofri-peretz/burgee/components"><img src="https://img.shields.io/codecov/c/github/ofri-peretz/burgee/main?component=hookset&style=flat-square" alt="hookset line coverage: its Codecov component" /></a>
|
|
19
|
+
<a href="https://scorecard.dev/viewer/?uri=github.com/ofri-peretz/burgee"><img src="https://img.shields.io/ossf-scorecard/github.com/ofri-peretz/burgee?style=flat-square&label=OpenSSF%20Scorecard" alt="OpenSSF Scorecard for the repository" /></a>
|
|
20
|
+
<a href="https://www.npmjs.com/package/hookset?activeTab=code"><img src="https://img.shields.io/npm/unpacked-size/hookset?style=flat-square" alt="Unpacked size of the latest hookset release on npm" /></a>
|
|
21
|
+
<a href="https://github.com/ofri-peretz/burgee/blob/main/packages/hookset/package.json"><img src="https://img.shields.io/badge/dependencies-1%20in%20family%2C%200%20outside-0a6b47?style=flat-square" alt="One dependency, all in the burgee family (burgee), none outside it" /></a>
|
|
22
|
+
<a href="https://github.com/ofri-peretz/burgee/blob/main/packages/hookset/package.json"><img src="https://img.shields.io/badge/types-included-blue?style=flat-square" alt="TypeScript types included for every entry point" /></a>
|
|
23
|
+
<a href="https://github.com/ofri-peretz/burgee/blob/main/packages/hookset/package.json"><img src="https://img.shields.io/badge/Node.js-22.13%2B-green?style=flat-square" alt="Node.js 22.13+" /></a>
|
|
24
|
+
<a href="https://github.com/ofri-peretz/burgee/blob/main/packages/hookset/LICENSE"><img src="https://img.shields.io/badge/License-MIT-blue?style=flat-square" alt="License: MIT" /></a>
|
|
25
|
+
<a href="https://www.npmjs.com/package/hookset#provenance"><img src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fregistry.npmjs.org%2Fhookset%2Flatest&query=%24.dist.attestations.provenance~&label=npm&style=flat-square&color=0a6b47" alt="npm provenance of the latest release, read live from its registry attestation" /></a>
|
|
26
|
+
</p>
|
|
27
|
+
|
|
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>
|
|
31
|
+
</p>
|
|
32
|
+
|
|
33
|
+
**hookset** puts the same verification stations in every repository: lefthook presets for
|
|
34
|
+
`commit-msg`, `pre-commit` and `pre-push`, pulled through lefthook `remotes` at a pinned
|
|
35
|
+
`hookset@<version>` tag, and a Claude Code hook pack that denies a skipped hook, a moved
|
|
36
|
+
`core.hooksPath` and a hand-rolled CI polling loop. Each preset step calls the repository's own
|
|
37
|
+
script by a declared name, so the preset is the same everywhere and the repository decides what
|
|
38
|
+
runs. `hookset init` writes the smallest `lefthook.yml` that pulls them; `hookset check` fails a
|
|
39
|
+
repository whose hooks miss a station, pin no version, repeat a preset step or drift from the pack.
|
|
40
|
+
|
|
41
|
+
It covers the install half of **husky**: where husky keeps a hook script in each repository,
|
|
42
|
+
hookset keeps one pinned set for all of them and checks each repository against it. Every command
|
|
43
|
+
prints burgee's `--json` envelope, each problem with its `fix:` line, for a pipe or an agent.
|
|
44
|
+
|
|
45
|
+
## Install
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
npm install hookset
|
|
49
|
+
pnpm add hookset
|
|
50
|
+
yarn add hookset
|
|
51
|
+
bun add hookset
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Install it as a dev dependency (`-D`) beside lefthook. It needs git.
|
|
55
|
+
|
|
56
|
+
## Quick start
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
npm install hookset
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
```js
|
|
63
|
+
import { parseRemotes } from "hookset";
|
|
64
|
+
|
|
65
|
+
// The remote `hookset init` writes into lefthook.yml, pinned to a release tag.
|
|
66
|
+
const lefthook = `remotes:
|
|
67
|
+
- git_url: https://github.com/ofri-peretz/burgee
|
|
68
|
+
ref: hookset@0.2.1
|
|
69
|
+
configs:
|
|
70
|
+
- packages/hookset/presets/lefthook/pre-push.yml
|
|
71
|
+
`;
|
|
72
|
+
for (const remote of parseRemotes(lefthook)) console.log(`${remote.ref ?? "no ref"}: ${remote.configs.join(", ")}`);
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
```text
|
|
76
|
+
hookset@0.2.1: packages/hookset/presets/lefthook/pre-push.yml
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
`hookset check` reads the same remotes and fails when one is pinned to a branch rather than a tag.
|
|
80
|
+
|
|
81
|
+
## What it checks
|
|
82
|
+
|
|
83
|
+
```sh
|
|
84
|
+
hookset init # the smallest lefthook.yml that pulls the presets, pinned to this version
|
|
85
|
+
hookset init --claude # and the Claude Code hook pack under .claude/hooks/
|
|
86
|
+
hookset check # the CI gate: exit 1 on any error, warnings listed
|
|
87
|
+
hookset check --json # the problems as data, one fix line each
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
| Command | Exit 1 when |
|
|
91
|
+
| :-- | :-- |
|
|
92
|
+
| `init` | a `lefthook.yml` written by hand is already there and `--force` is not given |
|
|
93
|
+
| `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 |
|
|
94
|
+
|
|
95
|
+
## Migrating
|
|
96
|
+
|
|
97
|
+
The switch is one command, `npx hookset init`, and husky's folder comes out:
|
|
98
|
+
|
|
99
|
+
```diff
|
|
100
|
+
// package.json
|
|
101
|
+
"scripts": {
|
|
102
|
+
- "prepare": "husky",
|
|
103
|
+
+ "prepare": "lefthook install",
|
|
104
|
+
}
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
`npx hookset init` writes `lefthook.yml`; move each `.husky/<hook>` script into the
|
|
108
|
+
`hook:staged` or `hook:verify` script its station calls, then delete `.husky/`.
|
|
109
|
+
|
|
110
|
+
## Compatibility
|
|
111
|
+
|
|
112
|
+
Not graded: hookset reads and writes a repository's hook configuration, and no suite is graded
|
|
113
|
+
against it. It runs anywhere git and lefthook do.
|
|
114
|
+
|
|
115
|
+
## Benchmarks
|
|
116
|
+
|
|
117
|
+
Every number here is produced by `npm run bench` and published at [burgee.interlace.tools/docs/benchmarks](https://burgee.interlace.tools/docs/benchmarks).
|
|
118
|
+
|
|
119
|
+
No suite is graded against this package yet, so there is no compatibility number to quote.
|
|
120
|
+
|
|
121
|
+
## For agents
|
|
122
|
+
|
|
123
|
+
- **`hookset check --json`** and **`init --json`** print burgee's `--json` envelope, every
|
|
124
|
+
problem with a message that ends in `fix:`.
|
|
125
|
+
- **`--json`, `--schema` and an MCP server** come from one declaration on burgee:
|
|
126
|
+
`hookset --mcp` serves its commands as tools.
|
|
127
|
+
- **The Claude Code hook pack** is what an agent meets first: a denied `--no-verify` names the
|
|
128
|
+
hook to fix instead.
|
|
129
|
+
- **The docs are machine-readable** at
|
|
130
|
+
[burgee.interlace.tools/llms.txt](https://burgee.interlace.tools/llms.txt).
|
|
131
|
+
|
|
132
|
+
## API
|
|
133
|
+
|
|
134
|
+
| Import | What it gives you |
|
|
135
|
+
| :-- | :-- |
|
|
136
|
+
| `hookset` | `parseRemotes()`, `checkRepo()`, `checkText()`, `initRepo()`, `lefthookTemplate()`, `loadStations()` and `program` |
|
|
137
|
+
|
|
138
|
+
The `hookset` bin is that API, declared once on burgee.
|
|
139
|
+
|
|
140
|
+
## Requirements
|
|
141
|
+
|
|
142
|
+
Node 22.13 or later, git and lefthook.
|
|
143
|
+
|
|
144
|
+
## Where it sits
|
|
145
|
+
|
|
146
|
+
It hosts no plugin key of its own.
|
|
147
|
+
|
|
148
|
+
Nothing in this family builds on it yet, and it builds on `burgee`.
|
|
149
|
+
|
|
150
|
+
## The family
|
|
151
|
+
|
|
152
|
+
18 packages, one repository, one release pipeline. Each installs and works on its own, and each owns
|
|
153
|
+
one job. Seven of them — `bellpull`, `closeout`, `linegauge`, `paratext`, `roundel`, `seniority`,
|
|
154
|
+
`truefit` — depend on nothing; the others depend only on packages in this table, and every
|
|
155
|
+
dependency points one way, down the [layers](https://burgee.interlace.tools/docs/concepts/family).
|
|
156
|
+
|
|
157
|
+
No package declares a dependency from outside the family; `react` and `react-reconciler` are
|
|
158
|
+
optional peers of `controlroom`, which npm does not install; `vitest` is an optional peer of
|
|
159
|
+
`oxmutate`, which npm does not install; `eslint` is an optional peer of `truepass`, which npm does
|
|
160
|
+
not install.
|
|
161
|
+
[`package-shape-lock`](https://github.com/ofri-peretz/burgee/blob/main/scripts/package-shape-lock.test.ts)
|
|
162
|
+
holds that for every manifest, and
|
|
163
|
+
[`independence-install-lock`](https://github.com/ofri-peretz/burgee/blob/main/scripts/independence-install-lock.test.ts)
|
|
164
|
+
installs each package alone and finds nothing but the family packages it declares.
|
|
165
|
+
|
|
166
|
+
Releases are published by one workflow through npm trusted publishing: no npm token is used, and
|
|
167
|
+
each release carries SLSA provenance, which `npm view <package> dist.attestations` shows.
|
|
168
|
+
[`trusted-publishing-lock`](https://github.com/ofri-peretz/burgee/blob/main/scripts/trusted-publishing-lock.test.ts)
|
|
169
|
+
keeps both true.
|
|
170
|
+
|
|
171
|
+
| Package | What it is | Migrates from |
|
|
172
|
+
| :-- | :-- | :-- |
|
|
173
|
+
| [burgee](https://burgee.interlace.tools/docs/packages/burgee) | The CLI framework: one declaration, every surface | commander, yargs and meow |
|
|
174
|
+
| [roundel](https://roundel.interlace.tools/docs) | Colour: one output policy, semantic tokens, a theme | chalk, colorette, kleur, picocolors, supports-color and yoctocolors |
|
|
175
|
+
| [flagstaff](https://flagstaff.interlace.tools/docs) | The frame loop: spinners, progress, boxes and tables | ora, log-update, boxen and cli-table3 |
|
|
176
|
+
| [caique](https://caique.interlace.tools/docs) | Prompts that are flags first, and never hang | @inquirer/core |
|
|
177
|
+
| [linegauge](https://linegauge.interlace.tools/docs) | Measuring, wrapping, truncating and slicing styled text | string-width, wrap-ansi, strip-ansi, slice-ansi, cli-truncate and widest-line |
|
|
178
|
+
| [paratext](https://paratext.interlace.tools/docs) | Hyperlinks, images, title, clipboard and notifications | ansi-escapes, terminal-link and term-img |
|
|
179
|
+
| [seniority](https://seniority.interlace.tools/docs) | Configuration precedence and discovery, with provenance | cosmiconfig, lilconfig, dotenv and rc |
|
|
180
|
+
| [closeout](https://closeout.interlace.tools/docs) | Exit handlers, terminal restore and a bounded shutdown | signal-exit, exit-hook, restore-cursor, cli-cursor and onetime |
|
|
181
|
+
| [bellpull](https://bellpull.interlace.tools/docs) | Subprocesses, and which executable actually ran | cross-spawn and which |
|
|
182
|
+
| [controlroom](https://controlroom.interlace.tools/docs) | Keyboard-driven terminal screens, inline or full-screen | ink |
|
|
183
|
+
| [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 |
|
|
189
|
+
| **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 |
|
|
191
|
+
|
|
192
|
+
Every migration guide, and the family-wide [compatibility](https://burgee.interlace.tools/docs/compatibility)
|
|
193
|
+
and [benchmarks](https://burgee.interlace.tools/docs/benchmarks) pages, are on
|
|
194
|
+
[burgee.interlace.tools](https://burgee.interlace.tools/docs/packages).
|
|
195
|
+
|
|
196
|
+
## Contributing
|
|
197
|
+
|
|
198
|
+
Issues and pull requests are welcome at [ofri-peretz/burgee](https://github.com/ofri-peretz/burgee/issues); read
|
|
199
|
+
[CONTRIBUTING.md](https://github.com/ofri-peretz/burgee/blob/main/CONTRIBUTING.md) first. Report a vulnerability privately, as
|
|
200
|
+
[SECURITY.md](https://github.com/ofri-peretz/burgee/blob/main/SECURITY.md) describes — never in a public issue.
|
|
201
|
+
|
|
202
|
+
## Licence
|
|
203
|
+
|
|
204
|
+
MIT © Ofri Peretz — see [LICENSE](https://github.com/ofri-peretz/burgee/blob/main/packages/hookset/LICENSE).
|
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// guard-bash — Claude Code PreToolUse hook for Bash, Edit and Write. Canonical copy:
|
|
3
|
+
// burgee packages/hookset/claude/. `hookset init --claude` vendors it into a repo's
|
|
4
|
+
// .claude/hooks/, byte-identical, and `hookset check` fails when the copy drifts.
|
|
5
|
+
//
|
|
6
|
+
// It replaces prose that every CLAUDE.md used to repeat. A rule an agent can break
|
|
7
|
+
// with one command is a check, not a sentence: the denial below is the documentation.
|
|
8
|
+
//
|
|
9
|
+
// 1. Skipping git hooks (--no-verify, `git commit -n`, LEFTHOOK=0/HUSKY=0) — the hooks are the gate.
|
|
10
|
+
// 2. Pointing git at other hooks (`git config core.hooksPath`, `git -c core.hooksPath=`).
|
|
11
|
+
// 3. Hand-rolled CI polling (`until/while … gh … sleep`) — the harness kills those loops
|
|
12
|
+
// and the turn ends knowing nothing. `gh pr checks <PR> --watch` blocks correctly.
|
|
13
|
+
// 4. Asks (never denies) before a publish: `npm publish`, `changeset publish`, and the
|
|
14
|
+
// commands the repo lists under `ask` in .claude/hookset.json (deploys, releases).
|
|
15
|
+
// 5. Denies Edit/Write on a path matching a glob the repo lists under `frozen` there.
|
|
16
|
+
// 6. Denies `git commit` / `git push` run in the foreground under the default 2-minute
|
|
17
|
+
// timeout: their hooks are the repo's gate and take minutes. The denial names the fix
|
|
18
|
+
// (timeout 600000 or run_in_background), so no CLAUDE.md has to say "not a hang".
|
|
19
|
+
//
|
|
20
|
+
// Matching is done on tokens, not regexes over the raw command: quoted strings and
|
|
21
|
+
// heredoc bodies are data (commit messages, PR bodies), and no pattern here can backtrack.
|
|
22
|
+
// Reads the PreToolUse payload on stdin. Prints a deny or ask decision, or nothing (no opinion).
|
|
23
|
+
// `node guard-bash.mjs --self-test` runs the cases at the bottom.
|
|
24
|
+
|
|
25
|
+
import { posix } from "node:path";
|
|
26
|
+
|
|
27
|
+
const SEPARATORS = new Set([";", "&", "|", "\n", "(", ")"]);
|
|
28
|
+
|
|
29
|
+
/** Drop heredoc bodies: everything after a `<<WORD` line until the line that is WORD. */
|
|
30
|
+
function dropHeredocs(cmd) {
|
|
31
|
+
const out = [];
|
|
32
|
+
let end = null;
|
|
33
|
+
for (const line of cmd.split("\n")) {
|
|
34
|
+
if (end !== null) {
|
|
35
|
+
if (line.trim() === end) end = null;
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
out.push(line);
|
|
39
|
+
const at = line.indexOf("<<");
|
|
40
|
+
// `<<<` is a herestring, not a heredoc: it has no body to skip.
|
|
41
|
+
if (at !== -1 && line[at + 2] !== "<") {
|
|
42
|
+
const word = line
|
|
43
|
+
.slice(at + 2)
|
|
44
|
+
.replace(/^-/, "")
|
|
45
|
+
.trim()
|
|
46
|
+
.split(" ")[0]
|
|
47
|
+
.replaceAll("'", "")
|
|
48
|
+
.replaceAll('"', "");
|
|
49
|
+
if (word) end = word;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return out.join("\n");
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Index just past the quote that closes the one at `start`. */
|
|
56
|
+
function skipQuoted(src, start) {
|
|
57
|
+
const quote = src[start];
|
|
58
|
+
let i = start + 1;
|
|
59
|
+
while (i < src.length && src[i] !== quote)
|
|
60
|
+
i += src[i] === "\\" && quote === '"' ? 2 : 1;
|
|
61
|
+
return i + 1;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const VALUE_FLAG = /^(-[a-zA-Z]*[mF]|--message|--file|--trailer)$/;
|
|
65
|
+
|
|
66
|
+
/** True when words[k] is a flag that takes the next word as its value, and was not itself one. */
|
|
67
|
+
function takesValue(words, k) {
|
|
68
|
+
return k >= 0 && VALUE_FLAG.test(words[k]) && !takesValue(words, k - 1);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Split into commands of whitespace-separated words. Quoted text becomes an empty word, except a
|
|
73
|
+
* quoted single word ("--no-verify", "core.hooksPath=x"), which the shell passes on as that word.
|
|
74
|
+
*/
|
|
75
|
+
export function commands(cmd) {
|
|
76
|
+
const src = dropHeredocs(cmd ?? "").replace(/\\\n/g, " ");
|
|
77
|
+
const result = [];
|
|
78
|
+
let words = [];
|
|
79
|
+
let word = "";
|
|
80
|
+
const flushWord = () => {
|
|
81
|
+
if (word !== "") words.push(word);
|
|
82
|
+
word = "";
|
|
83
|
+
};
|
|
84
|
+
const flushCommand = () => {
|
|
85
|
+
flushWord();
|
|
86
|
+
if (words.length) result.push(words);
|
|
87
|
+
words = [];
|
|
88
|
+
};
|
|
89
|
+
let i = 0;
|
|
90
|
+
while (i < src.length) {
|
|
91
|
+
const ch = src[i];
|
|
92
|
+
if (ch === "'" || ch === '"') {
|
|
93
|
+
const end = skipQuoted(src, i);
|
|
94
|
+
const inner = src.slice(i + 1, end - 1);
|
|
95
|
+
// A quoted single word reaches the program as that word, unless it is a message or file value.
|
|
96
|
+
const isValue = word === "" && takesValue(words, words.length - 1);
|
|
97
|
+
word += !isValue && /^\S+$/.test(inner) ? inner : '""';
|
|
98
|
+
i = end;
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
if (SEPARATORS.has(ch)) flushCommand();
|
|
102
|
+
else if (ch === " " || ch === "\t") flushWord();
|
|
103
|
+
else word += ch;
|
|
104
|
+
i++;
|
|
105
|
+
}
|
|
106
|
+
flushCommand();
|
|
107
|
+
return result;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const GIT_OPTS_WITH_VALUE = new Set([
|
|
111
|
+
"-C",
|
|
112
|
+
"-c",
|
|
113
|
+
"--git-dir",
|
|
114
|
+
"--work-tree",
|
|
115
|
+
"--namespace",
|
|
116
|
+
]);
|
|
117
|
+
|
|
118
|
+
/** Index of git's subcommand in `words` (past `git -C dir`, `git -c k=v`), or -1. */
|
|
119
|
+
function gitSub(words) {
|
|
120
|
+
const g = words.indexOf("git");
|
|
121
|
+
if (g === -1) return -1;
|
|
122
|
+
let s = g + 1;
|
|
123
|
+
while (words[s]?.startsWith("-"))
|
|
124
|
+
s += GIT_OPTS_WITH_VALUE.has(words[s]) ? 2 : 1;
|
|
125
|
+
return s;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function skipsHooks(words) {
|
|
129
|
+
const s = gitSub(words);
|
|
130
|
+
if (s === -1) return false;
|
|
131
|
+
const env = words.slice(0, words.indexOf("git"));
|
|
132
|
+
const sub = words[s];
|
|
133
|
+
const args = words.slice(s + 1);
|
|
134
|
+
if (args.includes("--no-verify")) return true;
|
|
135
|
+
if (
|
|
136
|
+
sub === "commit" &&
|
|
137
|
+
args.some((a) => /^-[a-zA-Z]+$/.test(a) && a.includes("n"))
|
|
138
|
+
)
|
|
139
|
+
return true;
|
|
140
|
+
const offEnv = env.some((w) => /^(LEFTHOOK|HUSKY)=(0|false)$/.test(w));
|
|
141
|
+
return offEnv && (sub === "commit" || sub === "push");
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** `git config [--global|--local] core.hooksPath x` or `git -c core.hooksPath=x …`. */
|
|
145
|
+
function movesHooks(words) {
|
|
146
|
+
const g = words.indexOf("git");
|
|
147
|
+
if (g === -1) return false;
|
|
148
|
+
const rest = words.slice(g + 1);
|
|
149
|
+
for (let i = 0; i < rest.length; i++)
|
|
150
|
+
if (rest[i] === "-c" && /^core\.hookspath=/i.test(rest[i + 1] ?? "")) return true;
|
|
151
|
+
const c = rest.indexOf("config");
|
|
152
|
+
return c !== -1 && rest.slice(c + 1).some((w) => /^core\.hookspath$/i.test(w)) && !rest.includes("--get") && !rest.includes("--unset");
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** True when `words` holds `phrase` (a space-separated word list) as a contiguous run. */
|
|
156
|
+
function hasPhrase(words, phrase) {
|
|
157
|
+
const want = phrase.split(" ").filter(Boolean);
|
|
158
|
+
if (!want.length) return false;
|
|
159
|
+
for (let i = 0; i + want.length <= words.length; i++)
|
|
160
|
+
if (want.every((w, j) => words[i + j] === w)) return true;
|
|
161
|
+
return false;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export const PUBLISH = ["npm publish", "pnpm publish", "yarn npm publish", "changeset publish"];
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* True when `words` runs `npm` or `pnpm` with `publish` as its subcommand after global options:
|
|
168
|
+
* `npm --access=public publish`, `npm --registry https://r publish`. An option without `=`
|
|
169
|
+
* may take the next word as its value, so that word is skipped unless it is `publish` itself.
|
|
170
|
+
*/
|
|
171
|
+
function publishesAfterOptions(words) {
|
|
172
|
+
for (let i = 0; i < words.length; i++) {
|
|
173
|
+
if (words[i] !== "npm" && words[i] !== "pnpm") continue;
|
|
174
|
+
let j = i + 1;
|
|
175
|
+
while (j < words.length && words[j].startsWith("-")) {
|
|
176
|
+
// Any option without `=` may take the next word as its value (`--registry url`, `-F pkg`).
|
|
177
|
+
const valued = !words[j].includes("=");
|
|
178
|
+
j++;
|
|
179
|
+
if (valued && j < words.length && !words[j].startsWith("-") && words[j] !== "publish") j++;
|
|
180
|
+
}
|
|
181
|
+
if (words[j] === "publish") return `${words[i]} publish`;
|
|
182
|
+
}
|
|
183
|
+
return null;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const RULES = [
|
|
187
|
+
{
|
|
188
|
+
id: "no-verify",
|
|
189
|
+
test: (cmds) => cmds.some(skipsHooks),
|
|
190
|
+
reason:
|
|
191
|
+
"Git hooks are this repo's gate: never skip them (--no-verify, commit -n, LEFTHOOK=0). " +
|
|
192
|
+
"If a hook fails, fix what it reports. If it is slow, wait: commit/push hooks can take 3–4 minutes, " +
|
|
193
|
+
"and a killed push may still have landed (check `git log origin/<branch> -1` before retrying).",
|
|
194
|
+
},
|
|
195
|
+
{
|
|
196
|
+
id: "hooks-path",
|
|
197
|
+
test: (cmds) => cmds.some(movesHooks),
|
|
198
|
+
reason:
|
|
199
|
+
"Do not point git at other hooks (core.hooksPath): lefthook installed this repo's hooks and they are the gate. " +
|
|
200
|
+
"If a hook is wrong, fix lefthook.yml or the hookset preset in a PR.",
|
|
201
|
+
},
|
|
202
|
+
{
|
|
203
|
+
id: "ci-poll-loop",
|
|
204
|
+
test: (cmds) => {
|
|
205
|
+
const all = cmds.flat();
|
|
206
|
+
return (
|
|
207
|
+
(all.includes("until") || all.includes("while")) &&
|
|
208
|
+
all.includes("gh") &&
|
|
209
|
+
all.includes("sleep")
|
|
210
|
+
);
|
|
211
|
+
},
|
|
212
|
+
reason:
|
|
213
|
+
"Do not hand-roll CI polling loops: the harness timeout kills them and the turn ends knowing nothing. " +
|
|
214
|
+
"Use `gh pr checks <PR> --watch` (or `gh run watch <run-id>`; in interlace, `pr-blockers watch`). " +
|
|
215
|
+
"`--watch` returning means nothing is pending, not that everything passed: check the results after.",
|
|
216
|
+
},
|
|
217
|
+
];
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* The verdict for one Bash command: `{ decision: "deny" | "ask", id, reason }`, or null.
|
|
221
|
+
* `ask` holds extra phrases the repo wants a person to approve (from .claude/hookset.json).
|
|
222
|
+
*/
|
|
223
|
+
export function decide(command, ask = []) {
|
|
224
|
+
const cmds = commands(command);
|
|
225
|
+
for (const r of RULES)
|
|
226
|
+
if (r.test(cmds)) return { decision: "deny", id: r.id, reason: r.reason };
|
|
227
|
+
const phrase =
|
|
228
|
+
PUBLISH.find((p) => cmds.some((w) => hasPhrase(w, p))) ??
|
|
229
|
+
cmds.map(publishesAfterOptions).find(Boolean);
|
|
230
|
+
if (phrase)
|
|
231
|
+
return {
|
|
232
|
+
decision: "ask",
|
|
233
|
+
id: "publish",
|
|
234
|
+
reason: `\`${phrase}\` publishes or deploys outside this repo, and that cannot be undone. A person approves it; CI release workflows are the usual route.`,
|
|
235
|
+
};
|
|
236
|
+
const listed = ask.find((p) => cmds.some((w) => hasPhrase(w, p)));
|
|
237
|
+
if (listed)
|
|
238
|
+
return {
|
|
239
|
+
decision: "ask",
|
|
240
|
+
id: "repo-ask",
|
|
241
|
+
reason: `This repo lists \`${listed}\` in .claude/hookset.json as a step a person approves: it overwrites or ships something that is hard to take back.`,
|
|
242
|
+
};
|
|
243
|
+
return null;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** Below this a foreground Bash call is killed while a commit or push hook is still running. */
|
|
247
|
+
export const HOOKED_MIN_TIMEOUT_MS = 300_000;
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* The verdict for a `git commit` or `git push` given the Bash call's `timeout` and
|
|
251
|
+
* `run_in_background`, or null. Their hooks run the repo's gate for minutes; the default
|
|
252
|
+
* 2-minute timeout kills them mid-gate and the agent retries a push that may have landed.
|
|
253
|
+
*/
|
|
254
|
+
export function decideHooked(command, { timeout, run_in_background } = {}) {
|
|
255
|
+
if (run_in_background === true || (Number(timeout) || 0) >= HOOKED_MIN_TIMEOUT_MS) return null;
|
|
256
|
+
const hooked = commands(command).find((w) => {
|
|
257
|
+
const s = gitSub(w);
|
|
258
|
+
// `git commit --dry-run` runs no hooks; `git push --dry-run` still runs pre-push.
|
|
259
|
+
return s !== -1 && (w[s] === "commit" ? !w.includes("--dry-run") : w[s] === "push") && !w.includes("--help");
|
|
260
|
+
});
|
|
261
|
+
if (!hooked) return null;
|
|
262
|
+
const sub = hooked[gitSub(hooked)];
|
|
263
|
+
return {
|
|
264
|
+
decision: "deny",
|
|
265
|
+
id: "hooked-timeout",
|
|
266
|
+
reason:
|
|
267
|
+
`\`git ${sub}\` runs this repo's ${sub === "push" ? "pre-push" : "commit"} hooks, which take minutes: not a hang. ` +
|
|
268
|
+
"Run it again with `timeout: 600000` (or `run_in_background: true`) and wait for it. " +
|
|
269
|
+
"If an earlier push was killed, check `git log origin/<branch> -1` first: it may have landed.",
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** `*` within a segment, `**` across segments, `?` one character. Paths use forward slashes. */
|
|
274
|
+
export function globToRegExp(glob) {
|
|
275
|
+
let re = "";
|
|
276
|
+
for (let i = 0; i < glob.length; i++) {
|
|
277
|
+
const ch = glob[i];
|
|
278
|
+
if (ch === "*" && glob[i + 1] === "*") {
|
|
279
|
+
re += glob[i + 2] === "/" ? "(?:.*/)?" : ".*";
|
|
280
|
+
i += glob[i + 2] === "/" ? 2 : 1;
|
|
281
|
+
} else if (ch === "*") re += "[^/]*";
|
|
282
|
+
else if (ch === "?") re += "[^/]";
|
|
283
|
+
else re += /[.+^${}()|[\]\\]/.test(ch) ? `\\${ch}` : ch;
|
|
284
|
+
}
|
|
285
|
+
return new RegExp(`^${re}$`);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** The verdict for an Edit/Write on `file` (relative to the repo), or null. */
|
|
289
|
+
export function decideEdit(file, frozen = []) {
|
|
290
|
+
// posix.normalize folds `a/../b` and `./a`, so a dotted path cannot step around a frozen glob.
|
|
291
|
+
const rel = posix.normalize(String(file ?? "").replaceAll("\\", "/")).replace(/^\.\//, "");
|
|
292
|
+
const hit = frozen.find((g) => globToRegExp(g).test(rel));
|
|
293
|
+
return hit
|
|
294
|
+
? {
|
|
295
|
+
decision: "deny",
|
|
296
|
+
id: "frozen",
|
|
297
|
+
reason: `${rel} matches the frozen glob \`${hit}\` in .claude/hookset.json. It changes only by a decision: record one, then edit the list in its own PR.`,
|
|
298
|
+
}
|
|
299
|
+
: null;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
export const CASES = {
|
|
303
|
+
deny: [
|
|
304
|
+
"git commit --no-verify -m x",
|
|
305
|
+
"git push --no-verify origin x",
|
|
306
|
+
'git commit -nm "x"',
|
|
307
|
+
"git commit -n -m x",
|
|
308
|
+
"LEFTHOOK=0 git push",
|
|
309
|
+
"cd repo && git commit --no-verify",
|
|
310
|
+
'git commit "--no-verify" -m x',
|
|
311
|
+
"git -C . commit -n -m x",
|
|
312
|
+
"LEFTHOOK=0 git -c core.x=1 push",
|
|
313
|
+
"git config core.hooksPath /dev/null",
|
|
314
|
+
"git -c core.hooksPath=/tmp/none push",
|
|
315
|
+
'git -c "core.hooksPath=/dev/null" push',
|
|
316
|
+
'git commit -m -F "--no-verify"',
|
|
317
|
+
"HUSKY=false git commit -m x",
|
|
318
|
+
"read -r b <<< 'x'\ngit commit --no-verify -m y",
|
|
319
|
+
"git commit \\\n --no-verify -m x",
|
|
320
|
+
"until gh pr view 5 --json state | grep MERGED; do sleep 30; done",
|
|
321
|
+
"while true; do gh run list; sleep 10; done",
|
|
322
|
+
"until gh workflow view ci; do sleep 5; done",
|
|
323
|
+
],
|
|
324
|
+
allow: [
|
|
325
|
+
'git commit -m "docs: explain why --no-verify is banned"',
|
|
326
|
+
'git commit -m "--no-verify"',
|
|
327
|
+
'git commit -am "--no-verify"',
|
|
328
|
+
"git commit -F - <<'EOF'\nnever use --no-verify\nEOF",
|
|
329
|
+
"git commit -F - <<'EOF'\nuntil gh pr checks; do sleep 1; done\nEOF\ngit push",
|
|
330
|
+
"gh pr checks 12 --watch",
|
|
331
|
+
"git -C . log -n 3",
|
|
332
|
+
'git commit -am "x"',
|
|
333
|
+
"sleep 5",
|
|
334
|
+
"LEFTHOOK=0 npm ci",
|
|
335
|
+
"git log -n 3",
|
|
336
|
+
"git config --get core.hooksPath",
|
|
337
|
+
'echo "npm publish" > notes.txt',
|
|
338
|
+
],
|
|
339
|
+
ask: [
|
|
340
|
+
"npm publish --access public",
|
|
341
|
+
"cd pkg && npx changeset publish",
|
|
342
|
+
"pnpm publish",
|
|
343
|
+
"npm --access=public publish",
|
|
344
|
+
"npm --registry https://registry.npmjs.org publish",
|
|
345
|
+
"pnpm --filter pkg publish",
|
|
346
|
+
"pnpm -F pkg publish",
|
|
347
|
+
"npm -g publish",
|
|
348
|
+
],
|
|
349
|
+
// decideHooked: [command, Bash input, denied?]
|
|
350
|
+
hooked: [
|
|
351
|
+
["git push origin main", {}, true],
|
|
352
|
+
["git -C repo commit -m x", { timeout: 120000 }, true],
|
|
353
|
+
["cd a && git push", { timeout: 299999 }, true],
|
|
354
|
+
["git push", { timeout: 600000 }, false],
|
|
355
|
+
["git commit -m x", { run_in_background: true }, false],
|
|
356
|
+
["git push --dry-run", {}, true],
|
|
357
|
+
["git commit --dry-run -m x", {}, false],
|
|
358
|
+
["git log -n 3", {}, false],
|
|
359
|
+
["git commit -F - <<'EOF'\nx\nEOF", { timeout: 300000 }, false],
|
|
360
|
+
["echo 'git push'", {}, false],
|
|
361
|
+
],
|
|
362
|
+
};
|
|
363
|
+
|
|
364
|
+
function selfTest() {
|
|
365
|
+
const bad = [
|
|
366
|
+
...CASES.deny.filter((c) => decide(c)?.decision !== "deny").map((c) => `should deny: ${c}`),
|
|
367
|
+
...CASES.allow.filter((c) => decide(c)).map((c) => `should allow: ${c}`),
|
|
368
|
+
...CASES.ask.filter((c) => decide(c)?.decision !== "ask").map((c) => `should ask: ${c}`),
|
|
369
|
+
...CASES.hooked
|
|
370
|
+
.filter(([c, input, denied]) => Boolean(decideHooked(c, input)) !== denied)
|
|
371
|
+
.map(([c, input, denied]) => `should ${denied ? "deny" : "allow"} ${JSON.stringify(input)}: ${c}`),
|
|
372
|
+
];
|
|
373
|
+
process.stdout.write(
|
|
374
|
+
bad.length
|
|
375
|
+
? `${bad.join("\n")}\n${bad.length} failing\n`
|
|
376
|
+
: `ok: ${CASES.deny.length} denied, ${CASES.allow.length} allowed, ${CASES.ask.length} asked, ${CASES.hooked.length} timed\n`,
|
|
377
|
+
);
|
|
378
|
+
process.exit(bad.length ? 1 : 0);
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** The repo's `.claude/hookset.json`: `{ "ask": [phrases], "frozen": [globs] }`. Missing is empty. */
|
|
382
|
+
async function repoConfig() {
|
|
383
|
+
const { readFile } = await import("node:fs/promises");
|
|
384
|
+
const dir = process.env.CLAUDE_PROJECT_DIR || process.cwd();
|
|
385
|
+
try {
|
|
386
|
+
const c = JSON.parse(await readFile(`${dir}/.claude/hookset.json`, "utf8"));
|
|
387
|
+
return {
|
|
388
|
+
dir,
|
|
389
|
+
ask: Array.isArray(c.ask) ? c.ask.map(String) : [],
|
|
390
|
+
frozen: Array.isArray(c.frozen) ? c.frozen.map(String) : [],
|
|
391
|
+
};
|
|
392
|
+
} catch {
|
|
393
|
+
return { dir, ask: [], frozen: [] };
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
// Imported (stop-after-3 reads `commands` from guard-bash) is not run: only the entry file acts.
|
|
398
|
+
const isMain = Boolean(process.argv[1]) && import.meta.url.endsWith(`/${process.argv[1].split(/[\\/]/).pop()}`);
|
|
399
|
+
if (isMain && process.argv.includes("--self-test")) selfTest();
|
|
400
|
+
else if (isMain) {
|
|
401
|
+
let raw = "";
|
|
402
|
+
process.stdin.on("data", (d) => (raw += d));
|
|
403
|
+
process.stdin.on("end", async () => {
|
|
404
|
+
let payload;
|
|
405
|
+
try {
|
|
406
|
+
payload = JSON.parse(raw) ?? {};
|
|
407
|
+
} catch {
|
|
408
|
+
process.exit(0);
|
|
409
|
+
}
|
|
410
|
+
const input = payload.tool_input ?? {};
|
|
411
|
+
const config = await repoConfig();
|
|
412
|
+
let hit = null;
|
|
413
|
+
if (typeof input.command === "string")
|
|
414
|
+
hit = decide(input.command, config.ask) ?? decideHooked(input.command, input);
|
|
415
|
+
else {
|
|
416
|
+
const file = input.file_path ?? input.notebook_path;
|
|
417
|
+
if (typeof file === "string") {
|
|
418
|
+
// Windows hands both paths over with backslashes: compare them with forward slashes.
|
|
419
|
+
const [f, d] = [file, config.dir].map((p) => posix.normalize(p.replaceAll("\\", "/")));
|
|
420
|
+
const rel = f.startsWith(`${d}/`) ? f.slice(d.length + 1) : f;
|
|
421
|
+
hit = decideEdit(rel, config.frozen);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
if (!hit) process.exit(0);
|
|
425
|
+
process.stdout.write(
|
|
426
|
+
JSON.stringify({
|
|
427
|
+
hookSpecificOutput: {
|
|
428
|
+
hookEventName: "PreToolUse",
|
|
429
|
+
permissionDecision: hit.decision,
|
|
430
|
+
permissionDecisionReason: `[guard-bash:${hit.id}] ${hit.reason}`,
|
|
431
|
+
},
|
|
432
|
+
}),
|
|
433
|
+
);
|
|
434
|
+
});
|
|
435
|
+
}
|