enhance(#3911): hooks declare their crash policy (#3960)

* enhance(#3911): give hooks an exit seam that needs no build

ADR-3889 Phase 7 foundation. The 19 shipped enforcement hooks hold 91 of the
epic's 128 terminators and cannot reach `terminateNow` today.

The obvious route — requiring `gsd-core/bin/lib/cli-exit.cjs`, as
gsd-agent-isolation-guard.js already does for two other modules — is rejected.
That precedent carries its own warning (#3582): those files are tsc output,
gitignored and absent on a raw plugin-marketplace or git-clone install, so the
hook must first call ensureRuntimeBuild() to self-heal. Making the module a
hook needs IN ORDER TO TERMINATE depend on a build inverts the dependency, and
its failure mode is precisely the fail-open this phase exists to remove: a
guard that cannot terminate cannot deny. `lint-hooks-runtime-build-seam`
already encodes that concern, and Design B would have had to add an
ensureRuntimeBuild() call to all 19 hooks to satisfy it.

So `hooks/lib/` becomes a third emit location for cli-exit and a fifth for the
registry, preserving the invariant `src/cli-exit.cts`'s own header states: it
imports nothing but node:fs and its sibling registry, and the generator
dual-emits that sibling alongside each copy so a relative require resolves next
to whichever copy loaded it. Shipping needed no change — build-hooks.js already
declares HOOKS_SUBDIRS_TO_COPY = ['lib'].

Proven, not asserted: the two files are copied into an otherwise-empty tmpdir
and a child process requires them and terminates — PASS exits 0, HOOK_DENY
exits 2 with the payload on both stdout and stderr. That test fails the moment
the hooks copy gains a require reaching outside hooks/lib/.

Also fixed inline: the registry's fifth target let any `--write` test overwrite
the real committed hooks/lib/exit-code-registry.js, because the test helper
derived only three of the other output paths. It now redirects all five, and a
regression test asserts every committed artifact is byte-identical after a
redirected write.

Install-tree goldens pick up the two new shipped paths across 11 runtimes —
insertions only, no removals. lint:ci was green while they were stale, so this
was found by regenerating rather than by a gate.

Verification runs on the remote runner.

Refs #3911

* enhance(#3911): declare a crash policy, and migrate the write guard

Adds `hooks/lib/hook-exit.js` — the hook-facing vocabulary over `terminateNow`,
hand-written because the cli-exit copy beside it is generated:

  allow(payload)          exit 0
  deny(payload, stderr?)  exit 2
  crash(onCrash, payload) whichever the hook DECLARED

`crash()` takes the policy as a required argument with no default, which is the
whole mechanism: fail-open by accident stops being expressible. A hook must
name ALLOW or DENY at the call site, and an unrecognized value terminates
INTERNAL rather than guessing. Fail-open stays legal; fail-open by omission
does not.

`gsd-write-guard.js` is the first hook migrated, all 12 sites, and it exposed a
gap in the seam. `terminateNow`'s doc comment justified its fd-2 write by
citing this hook's `emitBlock` — but modeled it as sending the same bytes to
both streams, when `emitBlock` actually sends full JSON to stdout and only the
bare `reason` string to stderr, because Kimi's hook bus feeds stderr verbatim
back to the model. Migrating as written would have turned a readable sentence
into a JSON blob for Kimi-backed agents.

#3911 requires both "all 19 hooks terminate through terminateNow" and "no
hook's effective default changes". Those are jointly satisfiable only by
teaching the seam to carry a distinct stderr payload, so `terminateNow` gains
an optional third argument: omitted, behavior is byte-for-byte what it was; a
string is written raw, which is exactly the Kimi case. The doc comment's
inaccurate claim about emitBlock is corrected in place.

Proven rather than asserted: the pre-migration file is reconstructed from HEAD
and driven with the same catastrophic-shrink payload as the migrated one —
exit code, stdout and stderr all byte-identical.

Verification runs on the remote runner.

Refs #3911

* enhance(#3911): all 19 hooks terminate through the seam

Migrates the remaining 18 enforcement hooks onto allow/deny/crash. An AST walk
now reports zero `process.exit(` call sites across every `hooks/*.js` — down
from the 91 the census measured.

Each hook with an outer catch declares its policy once, at module top, with the
reason that policy is right for that specific guard: a read guard that cannot
scan must not block the read; a statusline that renders every prompt must
degrade rather than crash; an injection scanner must not retroactively block a
result already returned. Those sentences are the deliverable — they are what
turns fail-open-by-accident into fail-open-on-purpose. No hook's effective
default changed.

Wiring exposed two defects, both fixed here rather than noted.

A SECOND stdout/stderr-splitting site turned up in `gsd-workflow-guard.js`'s
`emitForceAddBlock`, matching the pattern already known from the write guard —
full JSON to stdout, bare reason to stderr for the Kimi bus. It uses the
`stderrPayload` argument added in the previous commit, which is now carrying
its second real caller rather than one special case.

More seriously, `terminateNow` emitted both streams inside ONE try, so a
payload that failed to serialize aborted before the stderr write ever ran. The
two windsurf guards write nothing to stdout on a block and only a reason string
to stderr, so `deny(undefined, reason)` exited 2 with EMPTY stderr — a deny
that silently loses its reason, which is the exact "fails with success" class
this epic exists to close. The streams are now emitted independently, each with
its own guard, and `undefined` means "nothing to write for this stream" rather
than an error. Regression tests inject a throwing write on one fd and assert
the other still receives its payload; they fail against the single-try version.

Byte-identity was proven per hook, not assumed: each pre-change file is
reconstructed from HEAD and driven side by side with the migrated one across
its normal path, its deny path, malformed stdin and empty stdin — exit code,
stdout and stderr compared.

Verification runs on the remote runner.

Refs #3911

* enhance(#3911): harden the three shell hooks, and pin every hook's policy

`gsd-phase-boundary.sh`, `gsd-session-state.sh` and `gsd-validate-commit.sh`
gain `set -euo pipefail`.

The expected hazard did not materialize, and that is worth recording: every
intentionally-non-zero command in all three is already the condition of an
`if`/`elif`, which `set -e` never fires on, and none of them reads a
possibly-unset variable or pipes through a grep that may legitimately match
nothing. No `|| true` guards were needed. Each hook was still checked
command-by-command before the flags went in rather than after.

Twenty-one before/after cases across the three hooks — disabled and enabled,
planning and non-planning, missing STATE.md, malformed JSON, the Kimi payload
shape, quoted and unquoted `-m`, valid and over-long Conventional Commits —
all match on exit code, stdout and stderr.

The hardening is shown to actually fire, not merely added: with a stubbed
`node` that fails at the JSON-emit step, phase-boundary and session-state go
from silently exiting 0 with empty stdout to failing visibly with the error
surfaced. No such case could be constructed for `gsd-validate-commit.sh`,
whose every statement already sits inside an if-condition — recorded as
unproven rather than claimed.

`tests/hooks-crash-policy.test.cjs` adds the per-hook coverage the issue asks
for, table-driven over all 19 hooks rather than 76 hand-written cases: normal
allow, deny where a deny path exists, crash-honors-the-declared-policy, and an
unclosed-stdin case — the one `process.exitCode` structurally cannot serve. The
deny assertions encode each hook's ACTUAL stream split rather than a uniform
shape, since four of the six deliberately differ. A drift guard enumerates
`hooks/*.js` and fails if a terminating hook is ever added without a row.

Writing those tests surfaced two hooks that emit a block decision in their JSON
body and exit 0. Both were checked rather than assumed, and neither is a
fails-with-success: `gsd-read-injection-scanner.js` is PostToolUse, where the
tool has already run and exit 2 has no meaning, and `gsd-cursor-subagent-start.js`
follows Cursor's JSON-body protocol. They are deliberately left alone — a
mechanical sweep to `deny()` would have broken exactly these two.

Verification runs on the remote runner.

Refs #3911

* fix(#3838): the commit validator says when it could not validate

#3911 claims to subsume #3838. Measurement said otherwise, so this closes it
for real rather than by assertion.

`set -euo pipefail`, added earlier on this branch, does NOT fix #3838: bash
exempts a command used as an `if` condition from `set -e`, and all three of the
hook's swallow-and-pass sites are exactly that shape. Verified against the
hardened hook with a node shim that fails only the classifier call — a
non-conforming commit still exited 0 with empty stdout AND empty stderr,
indistinguishable from "your commit conforms". That is the defect verbatim.

All three sites named in #3838 now capture the real exit status instead of
consuming it as a condition, and each distinguishes its genuine negative from
"could not run":

- the classifier: 0 = is a git commit, 1 = genuinely not one, anything else =
  could not classify. Its `node -e` now wraps the require and the call in
  try/catch and exits 3 on a throw, so a broken require chain can never be
  mistaken for `isGitSubcommand` legitimately returning false — which is the
  arm that matters, since `token-scanner.cjs` is a gitignored build artifact
  and a fresh checkout lands there.
- the opt-in config read and the JSON command extraction get the same
  treatment.

On "could not run" the hook emits a diagnostic to stderr naming which check
failed and why, then exits 0. The issue confirms this is safe — it is a
PreToolUse hook, so stderr does not disturb the JSON protocol — and ranks it
the smallest sufficient fix. The gate still fails open, but it can no longer do
so silently, which is the whole complaint: a validator that disables itself
quietly costs more than one that is absent, because it is trusted.

Both controls are unchanged and pinned by tests: a conforming commit still
passes silently, a non-conforming one still exits 2 with its existing block
payload. The defect test asserts stderr is non-empty and names the failure; it
fails against the pre-fix hook.

Verification runs on the remote runner.

Refs #3911, #3838

* docs(#3911): document the hook crash-policy contract

Reference and Explanation via a new docs/features fragment (FEATURES.md is
generated from it), INVENTORY rows for the three new hooks/lib files, and an
ARCHITECTURE note on the hooks section.

How-To: docs/how-to/declare-a-hook-crash-policy.md, indexed from docs/README.md
— a hook author now has to choose and declare a crash policy, which is more
than one step and crosses into which harness protocol their hook speaks. It
covers allow/deny/crash, writing an ON_CRASH reason that is actually useful,
when a deny needs a distinct stderr payload, the two hooks whose harness reads
a JSON-body decision and must NOT use deny(), and what to do when a check
cannot run at all — with #3838 as the worked example.

Refs #3911

* test(#3911): prove the seam actually ships, and stop hand-rolling temp cleanup

Two review findings.

The acceptance criterion 'hooks/dist/** stays in parity via the build seam
(lint:hooks-runtime-build-seam)' was misstated and unmet: that lint checks
something else — that a hook requiring a compiled gsd-core/bin/lib module also
calls ensureRuntimeBuild(). Nothing exercised that the three new hooks/lib
files reach hooks/dist/lib at all. That gap is not theoretical: #770 is a
recorded ship-blocking bug where a new hook never shipped because a copy list
missed it. The suite now builds dist through the repo's own ensureBuiltHooks(),
byte-compares each shipped copy against its source, and spawns a child that
requires the SHIPPED dist copy and denies — which is what catches a copy that
exists but cannot resolve its sibling registry.

gsd-validate-commit.sh hand-duplicated mktemp/run/rm three times; one idempotent
trap on EXIT replaces them, guarded so cleanup cannot alter the exit status.
Behavior-neutral across five cases, with temp-file counts taken before and
after each run.

Refs #3911

* fix(#3911): stage transitive hook lib requires, not just one level

The remote run returned 7 failures across 3 real causes.

The important one is a PRODUCTION bug this phase exposed rather than caused.
`writeCursorHooksJson` scanned each hook script for `./lib/X` requires exactly
one level deep and never re-scanned the lib files it staged for their own
sibling requires. Nothing had a transitive lib dependency before, so the gap
was invisible. Adding hook-exit.js -> cli-exit.js -> exit-code-registry.js
made real Cursor installs ship a bundle that dies at require time with
MODULE_NOT_FOUND. It now walks to a fixed point, and a real installed Cursor
hook runs to completion.

The staging harness in shared-hooks-dir-resolution hand-copied its fixture, so
the injection scanner crashed at require time and its exit-1 was being read as
a policy decision. Migrated to copyScriptWithDeps, which walks the require
graph — the repo's recorded rule for this class, since adding another
copyFileSync keeps it alive for the next person.

The missing-lib-source test in cursor-hook-workspace-roots hardcoded which lib
file it expected to be named in the abort message; the same throw now fires for
a different file first. Its assertion is unchanged in substance — staging still
must abort rather than ship a broken hook — only the name is no longer pinned.

The last one was my own test asserting an uppercase reason code. Measured
against origin/next: the pre-change hook emits the same lowercase
'config_unreadable', so the test was wrong, not the migration. Corrected to the
real value rather than making the code match the test.

Verification runs on the remote runner.

Refs #3911

* chore(#3911): regenerate the cursor install-tree golden

The staging fix means a Cursor install now correctly carries the two
transitive lib files it was silently missing. Additive only — no path was
removed. The golden diff is the evidence the packaging defect was real.

Refs #3911

* chore(#3911): backfill the changeset PR number

Refs #3911

* fix(#3911): a git probe that timed out is not a negative

A macOS CI lane failed three deny cases at 2084ms, 2112ms and 2177ms — just
past the 2000ms budget these hooks give their git probes. The three that passed
took 72ms, 595ms and 651ms. Under shard contention `git rev-parse` overruns,
the hook reads the non-zero result as "not a git repo", and allows with exit 0
and empty stdout AND empty stderr. Under load, the guards silently stop
guarding. That is ADR-3889's thesis exactly, sitting inside the security hooks
this phase is about.

The repo had already recognized the class in one place — gsd-cursor-subagent-start.js
fail-closed-denies on `git_timed_out` (#3045) — but nowhere else.

`hooks/lib/git-probe.js` classifies a probe's outcome, distinguishing a real
non-zero exit from ETIMEDOUT, a signal kill, and a spawn failure, rather than
folding all four into `status !== 0`. Three guards route their eight git probes
through it.

The resolution is the same shape #3838 took, and the same one that issue
endorsed as smallest-sufficient: fail open, but loudly. **No exit code changes
on any path** — a developer on a loaded machine is still not blocked, which
keeps #3911's declaration-pass contract intact for exit codes. What changes is
that the hook now says on stderr which probe could not answer, instead of
presenting silence as a clean verdict.

Scope was checked across every hooks/*.js, not just the three that failed:
gsd-agent-isolation-guard spawns no git; gsd-statusline's two probes gate only
a cosmetic display segment, not an allow/deny decision, and are left alone.

The C2 deny assertion was a real-race test — it demanded exit 2 while a slow
git legitimately yields 0. It now requires the hook to either deny, or allow
with a diagnostic naming the probe that could not run; a silent allow still
fails, so the assertion is not vacuous. A deterministic regression stubs git on
PATH to sleep past the budget rather than waiting for load to reproduce it.

Verification runs on the remote runner.

Refs #3911

* test(#3911): a PATH shim cannot intercept the hooks' git spawn on Windows

The deterministic timeout regression stubbed git on PATH and asserted the
guard reports rather than silently allows. It passes on Linux and macOS and
failed on Windows in 83ms and 176ms — the stub was never invoked at all.

Mechanism: the hooks call spawnSync('git', args) with no shell:true, so on
Windows CreateProcess resolves git.exe only and never a PATH .cmd shim. The
git.cmd branch could not have worked and is removed rather than left implying
a Windows path that does. Adding shell:true to the hooks to serve a test would
change product behavior and widen an injection surface, so the case is skipped
on win32 only, with the mechanism written into the skip reason so a future
reader does not 'fix' it that way.

Linux and macOS keep the coverage, and macOS is where the underlying fail-open
was actually caught.

Refs #3911

---------

Co-authored-by: sim <sim@local>
This commit is contained in:
Tom Boucher
2026-08-27 22:21:10 -04:00
committed by GitHub
parent 52b11ee811
commit 2ea5efc151
60 changed files with 3156 additions and 259 deletions

View File

@@ -1,12 +1,18 @@
#!/usr/bin/env node
/**
* gen-exit-code-registry.cjs — generates FOUR byte-identical/derived
* gen-exit-code-registry.cjs — generates FIVE byte-identical/derived
* artifacts from the declaration at gsd-core/bin/shared/exit-codes.json:
* - gsd-core/bin/lib/exit-code-registry.cjs (tsc-adjacent build tree)
* - scripts/lib/exit-code-registry.cjs (committed, for scripts/
* consumers that must work on an unbuilt clone — same reason
* scripts/lib/cli-exit.cjs exists alongside gsd-core/bin/lib/cli-exit.cjs;
* see scripts/gen-scripts-cli-exit.cjs).
* - hooks/lib/exit-code-registry.js (committed, for hooks/
* consumers that must work on a raw, unbuilt clone — same reason as the
* scripts/ copy above; see scripts/gen-hooks-cli-exit.cjs, which emits
* hooks/lib/cli-exit.js's sibling `require('./exit-code-registry.js')`.
* `.js`, not `.cjs`, to match the hooks/lib/*.js convention — ADR-3889
* Phase 7, #3911).
* - src/exit-code-registry.d.cts (the ambient type declaration
* tsc uses to typecheck src/cli-exit.cts's `require('./exit-code-registry.cjs')`
* against the shape the .cjs artifacts above actually export — generated
@@ -24,22 +30,24 @@
* the review finding that the .d.cts was hand-maintained with no gate by
* generating it here too; Phase 4 (#3908) added the shell fragment so the
* three bash scanners can source symbolic names instead of hardcoding
* integers.
* integers; Phase 7 (#3911) added the hooks/lib/ copy so a shipped hook can
* terminate through `terminateNow` without depending on any build artifact.
*
* The two .cjs artifacts are byte-identical: serializeRegistry() only encodes
* the DECLARATION path (for the banner comment), never the output path, so
* one generated string is written to both locations unchanged. The .d.cts
* and .sh artifacts are separate, smaller derivations but are generated and
* --check-gated exactly the same way.
* The three .cjs/.js artifacts (primary, scripts, hooks) are byte-identical:
* serializeRegistry() only encodes the DECLARATION path (for the banner
* comment), never the output path, so one generated string is written to all
* three locations unchanged. The .d.cts and .sh artifacts are separate,
* smaller derivations but are generated and --check-gated exactly the same
* way.
*
* Nothing in this script emits a registered exit code itself; wiring
* consumers onto the registry is separate work.
*
* Usage:
* node scripts/gen-exit-code-registry.cjs # same as --write
* node scripts/gen-exit-code-registry.cjs --write # write all four artifacts
* node scripts/gen-exit-code-registry.cjs --write # write all five artifacts
* node scripts/gen-exit-code-registry.cjs --check # exit 1 if ANY committed artifact is stale
* node scripts/gen-exit-code-registry.cjs --declaration <path> --out <path> --scripts-out <path> --dts-out <path> --sh-out <path> # override for tests
* node scripts/gen-exit-code-registry.cjs --declaration <path> --out <path> --scripts-out <path> --hooks-out <path> --dts-out <path> --sh-out <path> # override for tests
* node scripts/gen-exit-code-registry.cjs --json # emit ONE JSON report on stdout instead of human prose
*/
@@ -52,6 +60,7 @@ const REPO_ROOT = path.resolve(__dirname, '..');
const DEFAULT_DECLARATION_PATH = path.join(REPO_ROOT, 'gsd-core', 'bin', 'shared', 'exit-codes.json');
const DEFAULT_OUTPUT_PATH = path.join(REPO_ROOT, 'gsd-core', 'bin', 'lib', 'exit-code-registry.cjs');
const DEFAULT_SCRIPTS_OUTPUT_PATH = path.join(REPO_ROOT, 'scripts', 'lib', 'exit-code-registry.cjs');
const DEFAULT_HOOKS_OUTPUT_PATH = path.join(REPO_ROOT, 'hooks', 'lib', 'exit-code-registry.js');
const DEFAULT_DTS_OUTPUT_PATH = path.join(REPO_ROOT, 'src', 'exit-code-registry.d.cts');
const DEFAULT_SH_OUTPUT_PATH = path.join(REPO_ROOT, 'gsd-core', 'bin', 'shared', 'exit-codes.sh');
@@ -89,13 +98,14 @@ const REASON = Object.freeze({
});
const USAGE_MESSAGE = [
'Usage: node scripts/gen-exit-code-registry.cjs [--write|--check] [--declaration <path>] [--out <path>] [--scripts-out <path>] [--dts-out <path>] [--sh-out <path>] [--json]',
'Usage: node scripts/gen-exit-code-registry.cjs [--write|--check] [--declaration <path>] [--out <path>] [--scripts-out <path>] [--hooks-out <path>] [--dts-out <path>] [--sh-out <path>] [--json]',
' (no flag) same as --write',
' --write write all four generated registry artifacts',
' --write write all five generated registry artifacts',
' --check exit 1 if ANY committed artifact is stale',
' --declaration override the declaration path (default: gsd-core/bin/shared/exit-codes.json)',
' --out override the primary output artifact path (default: gsd-core/bin/lib/exit-code-registry.cjs)',
' --scripts-out override the secondary output artifact path (default: scripts/lib/exit-code-registry.cjs)',
' --hooks-out override the hooks output artifact path (default: hooks/lib/exit-code-registry.js)',
' --dts-out override the ambient type declaration path (default: src/exit-code-registry.d.cts)',
' --sh-out override the shell-sourceable fragment path (default: gsd-core/bin/shared/exit-codes.sh)',
' --json emit ONE JSON report ({ok, reason, context, detail?}) on stdout instead of human-readable prose',
@@ -318,10 +328,11 @@ function serializeRegistry(entries, declarationPath) {
'// GENERATED FILE — DO NOT EDIT BY HAND.',
`// Source of truth: ${relDeclaration}. Regenerate with:`,
'// node scripts/gen-exit-code-registry.cjs --write',
'// This exact content is emitted to TWO locations — gsd-core/bin/lib/exit-code-registry.cjs',
'// and scripts/lib/exit-code-registry.cjs (the latter committed so scripts/',
'// consumers work on an unbuilt clone) — both byte-compared by',
'// `npm run lint:generated-sync` (#3905 ADR-3889 Phase 1; #3906 Phase 2 added the second copy).',
'// This exact content is emitted to THREE locations — gsd-core/bin/lib/exit-code-registry.cjs,',
'// scripts/lib/exit-code-registry.cjs, and hooks/lib/exit-code-registry.js (the latter two',
'// committed so scripts/ and hooks/ consumers work on an unbuilt clone) — all byte-compared by',
'// `npm run lint:generated-sync` (#3905 ADR-3889 Phase 1; #3906 Phase 2 added the second copy;',
'// #3911 ADR-3889 Phase 7 added the hooks/lib/ copy).',
'//',
'// exitCodeFor(name) / nameForExitCode(code) are pure and total over this',
'// closed table — each throws for anything not registered here.',
@@ -531,16 +542,16 @@ function emitOk(reason, humanMessage, json) {
console.log(humanMessage);
}
function doWrite(declarationPath, outPath, scriptsOutPath, dtsPath, shPath, json) {
function doWrite(declarationPath, outPath, scriptsOutPath, hooksOutPath, dtsPath, shPath, json) {
const result = buildRegistryContent(declarationPath);
if (!result.ok) {
emitFail(result, json);
return 1;
}
// The two .cjs artifacts are byte-identical copies of the same generated
// content (serializeRegistry never encodes the output path), so the same
// string is written to both locations unchanged.
for (const target of [outPath, scriptsOutPath]) {
// The three .cjs/.js artifacts are byte-identical copies of the same
// generated content (serializeRegistry never encodes the output path), so
// the same string is written to all three locations unchanged.
for (const target of [outPath, scriptsOutPath, hooksOutPath]) {
fs.mkdirSync(path.dirname(target), { recursive: true });
fs.writeFileSync(target, result.content, 'utf8');
}
@@ -553,6 +564,7 @@ function doWrite(declarationPath, outPath, scriptsOutPath, dtsPath, shPath, json
emitOk(
REASON.OK,
`ok gen-exit-code-registry: wrote ${outPath}\nok gen-exit-code-registry: wrote ${scriptsOutPath}\n`
+ `ok gen-exit-code-registry: wrote ${hooksOutPath}\n`
+ `ok gen-exit-code-registry: wrote ${dtsPath}\nok gen-exit-code-registry: wrote ${shPath}`,
json,
);
@@ -589,12 +601,12 @@ function checkOneArtifact(artifactLabel, artifactPath, content) {
}
/**
* --check verifies ALL FOUR committed artifacts against the same freshly
* --check verifies ALL FIVE committed artifacts against the same freshly
* generated content and fails naming which one drifted (or is missing) if
* any does. Checked in a fixed order (primary, secondary, dts, sh) so a
* single-artifact failure is always reported deterministically.
* any does. Checked in a fixed order (primary, secondary, hooks, dts, sh) so
* a single-artifact failure is always reported deterministically.
*/
function doCheck(declarationPath, outPath, scriptsOutPath, dtsPath, shPath, json) {
function doCheck(declarationPath, outPath, scriptsOutPath, hooksOutPath, dtsPath, shPath, json) {
const result = buildRegistryContent(declarationPath);
if (!result.ok) {
emitFail(result, json);
@@ -606,6 +618,7 @@ function doCheck(declarationPath, outPath, scriptsOutPath, dtsPath, shPath, json
const artifacts = [
['primary', outPath, result.content],
['secondary', scriptsOutPath, result.content],
['hooks', hooksOutPath, result.content],
['dts', dtsPath, dtsContent],
['sh', shPath, shContent],
];
@@ -621,6 +634,7 @@ function doCheck(declarationPath, outPath, scriptsOutPath, dtsPath, shPath, json
REASON.OK,
`ok gen-exit-code-registry: ${outPath} matches ${declarationPath}\n`
+ `ok gen-exit-code-registry: ${scriptsOutPath} matches ${declarationPath}\n`
+ `ok gen-exit-code-registry: ${hooksOutPath} matches ${declarationPath}\n`
+ `ok gen-exit-code-registry: ${dtsPath} matches ${declarationPath}\n`
+ `ok gen-exit-code-registry: ${shPath} matches ${declarationPath}`,
json,
@@ -629,13 +643,14 @@ function doCheck(declarationPath, outPath, scriptsOutPath, dtsPath, shPath, json
}
/**
* @returns {{mode:'write'|'check', declarationPath:?string, outPath:?string, scriptsOutPath:?string, dtsPath:?string, shPath:?string, json:boolean}}
* @returns {{mode:'write'|'check', declarationPath:?string, outPath:?string, scriptsOutPath:?string, hooksOutPath:?string, dtsPath:?string, shPath:?string, json:boolean}}
*/
function parseArgs(argv) {
let mode = null;
let declarationPath = null;
let outPath = null;
let scriptsOutPath = null;
let hooksOutPath = null;
let dtsPath = null;
let shPath = null;
let json = false;
@@ -667,6 +682,12 @@ function parseArgs(argv) {
scriptsOutPath = value;
} else if (arg.startsWith('--scripts-out=')) {
scriptsOutPath = arg.slice('--scripts-out='.length);
} else if (arg === '--hooks-out') {
const value = argv[++i];
if (value === undefined) throw new Error('--hooks-out requires a value');
hooksOutPath = value;
} else if (arg.startsWith('--hooks-out=')) {
hooksOutPath = arg.slice('--hooks-out='.length);
} else if (arg === '--dts-out') {
const value = argv[++i];
if (value === undefined) throw new Error('--dts-out requires a value');
@@ -684,7 +705,7 @@ function parseArgs(argv) {
}
}
return { mode: mode || 'write', declarationPath, outPath, scriptsOutPath, dtsPath, shPath, json };
return { mode: mode || 'write', declarationPath, outPath, scriptsOutPath, hooksOutPath, dtsPath, shPath, json };
}
function main() {
@@ -705,12 +726,13 @@ function main() {
const declarationPath = args.declarationPath || DEFAULT_DECLARATION_PATH;
const outPath = args.outPath || DEFAULT_OUTPUT_PATH;
const scriptsOutPath = args.scriptsOutPath || DEFAULT_SCRIPTS_OUTPUT_PATH;
const hooksOutPath = args.hooksOutPath || DEFAULT_HOOKS_OUTPUT_PATH;
const dtsPath = args.dtsPath || DEFAULT_DTS_OUTPUT_PATH;
const shPath = args.shPath || DEFAULT_SH_OUTPUT_PATH;
return args.mode === 'check'
? doCheck(declarationPath, outPath, scriptsOutPath, dtsPath, shPath, args.json)
: doWrite(declarationPath, outPath, scriptsOutPath, dtsPath, shPath, args.json);
? doCheck(declarationPath, outPath, scriptsOutPath, hooksOutPath, dtsPath, shPath, args.json)
: doWrite(declarationPath, outPath, scriptsOutPath, hooksOutPath, dtsPath, shPath, args.json);
}
if (require.main === module) process.exitCode = main();
@@ -721,6 +743,7 @@ module.exports = {
DEFAULT_DECLARATION_PATH,
DEFAULT_OUTPUT_PATH,
DEFAULT_SCRIPTS_OUTPUT_PATH,
DEFAULT_HOOKS_OUTPUT_PATH,
DEFAULT_DTS_OUTPUT_PATH,
DEFAULT_SH_OUTPUT_PATH,
ENTRY_FIELD_TYPES,

View File

@@ -0,0 +1,207 @@
#!/usr/bin/env node
/**
* gen-hooks-cli-exit.cjs — generates hooks/lib/cli-exit.js from a fresh
* compile of src/cli-exit.cts.
*
* ADR-3889 Phase 7 (#3911): shipped hooks must be able to terminate through
* `terminateNow` WITHOUT depending on any build artifact. hooks/ runs
* straight from a raw, unbuilt clone (a hook is required by name via
* `require('./lib/cli-exit.js')` relative to the hook's own __dirname), so
* the generated file is compiled to a THROWAWAY outDir rather than read from
* gsd-core/bin/lib/ — reading the tracked build output would let a stale
* build produce a false green. This mirrors scripts/gen-scripts-cli-exit.cjs
* exactly (same compile-to-temp strategy, same banner/check/write shape);
* kept as a SIBLING script rather than folded into that one because
* gen-scripts-cli-exit.cjs is hard-coded to a single output path/extension
* (`scripts/lib/cli-exit.cjs`) throughout its BANNER prose and REASON
* messaging — parameterizing it for a second, differently-extensioned
* target (`.js`, not `.cjs`, to match the hooks/lib/*.js convention) would
* tangle a script that is otherwise simple and single-purpose.
*
* Usage:
* node scripts/gen-hooks-cli-exit.cjs # same as --write
* node scripts/gen-hooks-cli-exit.cjs --write # write hooks/lib/cli-exit.js
* node scripts/gen-hooks-cli-exit.cjs --check # exit 1 if committed file is stale
*/
'use strict';
const { execFileSync } = require('node:child_process');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const REPO_ROOT = path.resolve(__dirname, '..');
const OUTPUT_PATH = path.join(REPO_ROOT, 'hooks', 'lib', 'cli-exit.js');
const COMPILE_TIMEOUT_MS = 60_000;
/** Frozen reason codes so tests assert on structure, not prose. */
const REASON = Object.freeze({
OK: 'ok_generated_sync',
DRIFTED: 'fail_generated_drifted',
BUILD_FAILED: 'fail_build_failed',
MISSING_EMIT: 'fail_missing_emit',
USAGE: 'fail_usage',
});
const USAGE_MESSAGE = [
'Usage: node scripts/gen-hooks-cli-exit.cjs [--write|--check]',
' (no flag) same as --write',
' --write write hooks/lib/cli-exit.js',
' --check exit 1 if the committed file is stale',
].join('\n');
const BANNER = [
'// GENERATED FILE — DO NOT EDIT BY HAND.',
'// Source of truth: src/cli-exit.cts. Regenerate with:',
'// node scripts/gen-hooks-cli-exit.cjs --write',
'// Byte-compared by `npm run lint:generated-sync` (#3911, ADR-3889 Phase 7).',
'//',
'// Why this copy exists: hooks/ runs straight from a raw, unbuilt clone — a',
'// shipped hook must be able to `require(\'./lib/cli-exit.js\')` relative to',
'// its own __dirname and terminate through `terminateNow` without depending',
'// on any build artifact. gsd-core/bin/lib/cli-exit.cjs is gitignored tsc',
'// output and doubles as the build sentinel, so it cannot be required from',
'// here. `.js`, not `.cjs`, to match the hooks/lib/*.js convention. Hence one',
'// source, three emitted locations (gsd-core/bin/lib, scripts/lib, hooks/lib).',
'',
'',
].join('\n');
/** Compile the whole project to a throwaway outDir so the work tree is untouched. */
function compileToTemp() {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-hooks-cli-exit-'));
try {
execFileSync(
process.execPath,
[
path.join(REPO_ROOT, 'node_modules', 'typescript', 'bin', 'tsc'),
'-p', path.join(REPO_ROOT, 'tsconfig.build.json'),
'--outDir', tmp,
// A throwaway outDir must not reuse the in-tree incremental state, or
// tsc skips emit for files it believes are already current.
'--incremental', 'false',
'--tsBuildInfoFile', 'null',
],
{ cwd: REPO_ROOT, encoding: 'utf8', stdio: 'pipe', timeout: COMPILE_TIMEOUT_MS },
);
return { ok: true, dir: tmp };
} catch (err) {
fs.rmSync(tmp, { recursive: true, force: true });
const detail = [err.stdout, err.stderr].filter(Boolean).join('\n').trim();
return { ok: false, detail };
}
}
/**
* Compile src/cli-exit.cts to a throwaway outDir and return the expected
* generated content (banner + compiled bytes, with the sibling registry
* require rewritten to the `.js` extension hooks/lib/ uses), or a failure
* descriptor.
*
* @returns {{ ok: true, content: string } | { ok: false, reason: string, detail?: string }}
*/
function buildExpectedContent() {
const build = compileToTemp();
if (!build.ok) {
return { ok: false, reason: REASON.BUILD_FAILED, detail: build.detail };
}
try {
const emitted = path.join(build.dir, 'cli-exit.cjs');
if (!fs.existsSync(emitted)) {
return { ok: false, reason: REASON.MISSING_EMIT, detail: `no emit produced at ${emitted} from src/cli-exit.cts` };
}
const compiled = fs.readFileSync(emitted, 'utf8');
// hooks/lib/ ships `.js`, not `.cjs` (matching the hooks/lib/*.js
// convention — see the module header), so the sibling registry require
// tsc emits for src/cli-exit.cts's `require('./exit-code-registry.cjs')`
// must be rewritten to resolve the `.js` copy scripts/gen-exit-code-
// registry.cjs emits alongside this file, not the `.cjs` one. A literal,
// anchored replace (never a regex) so this can only ever touch the exact
// string tsc is known to emit for that one import.
const REGISTRY_REQUIRE_CJS = 'require("./exit-code-registry.cjs")';
const REGISTRY_REQUIRE_JS = 'require("./exit-code-registry.js")';
if (!compiled.includes(REGISTRY_REQUIRE_CJS)) {
return {
ok: false,
reason: REASON.MISSING_EMIT,
detail: `expected compiled output to contain ${REGISTRY_REQUIRE_CJS} (the sibling registry require) — tsc's emit shape may have changed`,
};
}
const rewritten = compiled.split(REGISTRY_REQUIRE_CJS).join(REGISTRY_REQUIRE_JS);
return { ok: true, content: BANNER + rewritten };
} finally {
fs.rmSync(build.dir, { recursive: true, force: true });
}
}
function doWrite() {
const result = buildExpectedContent();
if (!result.ok) {
console.error(`FAIL gen-hooks-cli-exit: ${result.reason}`);
if (result.detail) console.error(result.detail);
return 1;
}
fs.mkdirSync(path.dirname(OUTPUT_PATH), { recursive: true });
fs.writeFileSync(OUTPUT_PATH, result.content, 'utf8');
console.log(`ok gen-hooks-cli-exit: wrote ${path.relative(REPO_ROOT, OUTPUT_PATH)}`);
return 0;
}
function doCheck() {
const result = buildExpectedContent();
if (!result.ok) {
console.error(`FAIL gen-hooks-cli-exit: ${result.reason}`);
if (result.detail) console.error(result.detail);
return 1;
}
if (!fs.existsSync(OUTPUT_PATH)) {
console.error(`FAIL gen-hooks-cli-exit: ${REASON.MISSING_EMIT}`);
console.error(` ${path.relative(REPO_ROOT, OUTPUT_PATH)} does not exist. Run:`);
console.error(' node scripts/gen-hooks-cli-exit.cjs --write');
return 1;
}
const committed = fs.readFileSync(OUTPUT_PATH, 'utf8');
if (committed !== result.content) {
console.error(`FAIL gen-hooks-cli-exit: ${REASON.DRIFTED}`);
console.error(
` ${path.relative(REPO_ROOT, OUTPUT_PATH)} (${committed.length} bytes) != ` +
`compile of src/cli-exit.cts (${result.content.length} bytes)`,
);
console.error('');
console.error('Regenerate with:');
console.error(' node scripts/gen-hooks-cli-exit.cjs --write');
return 1;
}
console.log(`ok gen-hooks-cli-exit: ${path.relative(REPO_ROOT, OUTPUT_PATH)} matches src/cli-exit.cts`);
return 0;
}
function main() {
const flag = process.argv[2];
const extra = process.argv[3];
if (flag !== undefined && flag !== '--write' && flag !== '--check') {
console.error(`FAIL gen-hooks-cli-exit: ${REASON.USAGE}`);
console.error(` unrecognized argument: ${flag}`);
console.error(USAGE_MESSAGE);
return 1;
}
if (extra !== undefined) {
console.error(`FAIL gen-hooks-cli-exit: ${REASON.USAGE}`);
console.error(` unexpected extra argument: ${extra}`);
console.error(USAGE_MESSAGE);
return 1;
}
if (flag === '--check') return doCheck();
return doWrite();
}
if (require.main === module) process.exitCode = main();
module.exports = { REASON, buildExpectedContent, OUTPUT_PATH, BANNER };

View File

@@ -300,9 +300,21 @@ function runMain(main) {
* it.
*
* @param outcome - declared outcome name, projected via projectOutcome.
* @param payload - JSON-serializable value written to fd 1 (and, on a deny,
* fd 2 too — Kimi's native hook bus feeds stderr, not stdout, back to the
* model on exit 2, per hooks/gsd-write-guard.js's emitBlock).
* @param payload - JSON-serializable value written to fd 1 (and, on a deny
* for which no `stderrPayload` is given, fd 2 too — this is the
* backward-compatible default every existing caller relies on).
* @param stderrPayload - optional, deny-only. When omitted (the default),
* fd 2 gets the SAME serialized `payload` fd 1 got — unchanged behavior.
* When provided, fd 2 gets THIS instead: a string is written raw
* (verbatim, not JSON-stringified), anything else is JSON-stringified
* like `payload`. This exists because `hooks/gsd-write-guard.js`'s
* emitBlock does NOT write the same bytes to both streams today — it
* writes the full JSON `output` to stdout but only the plain-text
* `output.reason` STRING to stderr, because Kimi's native hook bus reads
* stderr verbatim back to the model on exit 2. Migrating that call site
* onto terminateNow requires a way to say "fd 2 gets this different,
* plain-text value" — `stderrPayload` is that seam. Ignored entirely for
* a non-deny outcome: stderr is a deny-only channel.
*
* PAYLOAD-SIZE CONSTRAINT FOR CALLERS (measured for #3906, relevant to P7/
* #3911 wiring 19 enforcement hooks onto this function): the write-until-
@@ -325,7 +337,7 @@ function runMain(main) {
* arrives whole" test, which hit exactly this constructing its own fixture
* before being rewritten to build the payload inside the child instead.
*/
function terminateNow(outcome, payload) {
function terminateNow(outcome, payload, stderrPayload) {
// terminateNow is total by construction: its callers are enforcement hooks
// (P7/#3911, 19 of them) whose OWN outer catch may fail open (some end in
// `process.exit(0)`). If resolving the contract version, projecting the
@@ -353,6 +365,17 @@ function terminateNow(outcome, payload) {
// outcome the fail-closed branches this function serves exist to prevent.
// The decision to terminate with `projected` stands regardless of whether
// the payload could be delivered.
//
// The two streams are emitted in TWO SEPARATE try/catch blocks, not one
// shared block (the pre-#3911 defect): fd 1 and fd 2 (deny-only) are
// independent channels with independent failure modes, and a shared try
// meant a serialization failure on fd 1 (e.g. `payload` throwing on
// JSON.stringify) aborted the block before fd 2 ever ran — silently
// dropping a deny's reason. `deny(undefined, 'some reason')` used to exit
// 2 with EMPTY stderr because of exactly this. Each block independently
// treats an `undefined` value for ITS OWN stream as "nothing to write"
// and skips the write cleanly, rather than serializing `undefined` (which
// is not valid JSON text) and throwing into the catch.
try {
// fs.writeSync, never process.stdout.write: pipe writes via
// process.stdout/stderr are async on Windows, and process.exit() below
@@ -361,20 +384,36 @@ function terminateNow(outcome, payload) {
// payload larger than the destination pipe's buffer — where a single
// write() syscall can legitimately return fewer bytes written than
// requested — still arrives whole rather than truncated.
const buf = Buffer.from(JSON.stringify(payload), 'utf8');
let offset = 0;
while (offset < buf.length) {
offset += node_fs_1.default.writeSync(1, buf, offset, buf.length - offset);
}
if (projected === HOOK_DENY_CODE) {
let stderrOffset = 0;
while (stderrOffset < buf.length) {
stderrOffset += node_fs_1.default.writeSync(2, buf, stderrOffset, buf.length - stderrOffset);
if (payload !== undefined) {
const buf = Buffer.from(JSON.stringify(payload), 'utf8');
let offset = 0;
while (offset < buf.length) {
offset += node_fs_1.default.writeSync(1, buf, offset, buf.length - offset);
}
}
}
catch {
// Emission failed; the exit code decision still stands (see above).
// fd 1 emission failed; the exit code decision still stands (see
// above), and fd 2 below is unaffected — it has its own try/catch.
}
if (projected === HOOK_DENY_CODE) {
try {
// Backward-compatible default: when no `stderrPayload` is given, fd 2
// gets the SAME value fd 1 got (still subject to fd 2's own
// undefined-skips-the-write and string-vs-JSON rules below).
const resolvedStderr = stderrPayload === undefined ? payload : stderrPayload;
if (resolvedStderr !== undefined) {
const stderrBuf = Buffer.from(typeof resolvedStderr === 'string' ? resolvedStderr : JSON.stringify(resolvedStderr), 'utf8');
let stderrOffset = 0;
while (stderrOffset < stderrBuf.length) {
stderrOffset += node_fs_1.default.writeSync(2, stderrBuf, stderrOffset, stderrBuf.length - stderrOffset);
}
}
}
catch {
// fd 2 emission failed; independent of fd 1 above, and the exit code
// decision still stands regardless.
}
}
// n/no-process-exit is not registered for src/**/*.cts (see the ADR-3889
// reference note in the module header) and both compiled .cjs copies of

View File

@@ -3,10 +3,11 @@
// GENERATED FILE — DO NOT EDIT BY HAND.
// Source of truth: gsd-core/bin/shared/exit-codes.json. Regenerate with:
// node scripts/gen-exit-code-registry.cjs --write
// This exact content is emitted to TWO locations — gsd-core/bin/lib/exit-code-registry.cjs
// and scripts/lib/exit-code-registry.cjs (the latter committed so scripts/
// consumers work on an unbuilt clone) — both byte-compared by
// `npm run lint:generated-sync` (#3905 ADR-3889 Phase 1; #3906 Phase 2 added the second copy).
// This exact content is emitted to THREE locations — gsd-core/bin/lib/exit-code-registry.cjs,
// scripts/lib/exit-code-registry.cjs, and hooks/lib/exit-code-registry.js (the latter two
// committed so scripts/ and hooks/ consumers work on an unbuilt clone) — all byte-compared by
// `npm run lint:generated-sync` (#3905 ADR-3889 Phase 1; #3906 Phase 2 added the second copy;
// #3911 ADR-3889 Phase 7 added the hooks/lib/ copy).
//
// exitCodeFor(name) / nameForExitCode(code) are pure and total over this
// closed table — each throws for anything not registered here.