@webpieces/ai-hook-rules 0.4.704 → 0.4.705

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,110 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HookBootFailure = exports.HookApp = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const inversify_1 = require("inversify");
6
+ const hook_core_1 = require("./hook-core");
7
+ const agent_response_1 = require("./agent-response");
8
+ const hook_ports_1 = require("./hook-ports");
9
+ const to_error_1 = require("../core/to-error");
10
+ // The reason text a crash surfaces to the agent. ONE literal, used by both fail-closed boundaries
11
+ // below and worded identically to `denyForCrash`'s so the audit trail reads the same whichever of them
12
+ // caught it.
13
+ const CRASH_PREFIX = '[ai-hooks] hook crashed unexpectedly — failing closed: ';
14
+ /**
15
+ * THE COMPOSITION ROOT'S APP — one PreToolUse invocation, end to end.
16
+ *
17
+ * Production is three lines in `guards-hook.ts` / `rules-hook.ts`:
18
+ *
19
+ * const container = new Container({ autobind: true });
20
+ * const app = container.get(HookApp);
21
+ * await app.run(new HookArgs('guards'));
22
+ *
23
+ * and a test is the SAME three lines with the ports rebound to doubles — canned stdin, a captured
24
+ * stdout, a recorded exit code. That is the whole difference, and it is the point: the test boundary
25
+ * is cut JUST ABOVE the injection point, so the seam a test drives is the seam production drives.
26
+ *
27
+ * What this replaces: `runMain(mode)`, which read stdin itself and reached `process.stdout.write` /
28
+ * `process.exit` from a dozen frames down. `runMain` is DELETED, not kept alongside — two spellings of
29
+ * one entry point is the shim shape this repo rejects outright (see CLAUDE.md, "NO webpieces surface
30
+ * is released backwards-compatible"). Nothing outside this file names it any more.
31
+ *
32
+ * The order of observable effects is unchanged from `runMain`: the invocation's audit line is flushed
33
+ * at the emit boundary inside the pipeline, the decision bytes are written next, and the process exits
34
+ * last through the injected exit port.
35
+ */
36
+ let HookApp = class HookApp {
37
+ stdin;
38
+ stdout;
39
+ processExit;
40
+ constructor(stdin, stdout, processExit) {
41
+ this.stdin = stdin;
42
+ this.stdout = stdout;
43
+ this.processExit = processExit;
44
+ }
45
+ async run(args) {
46
+ const outcome = await this.decide(args);
47
+ // An ALLOW writes NOTHING — a silent exit 0 is the allow in the PreToolUse protocol, and an
48
+ // empty write would still be a write on a pipe somebody is parsing. Guarded here rather than
49
+ // in the sink so the sink stays a dumb port.
50
+ if (outcome.stdout !== '')
51
+ this.stdout.write(outcome.stdout);
52
+ this.processExit.exit(outcome.exitCode);
53
+ }
54
+ /**
55
+ * THE FAIL-CLOSED BOUNDARY FOR THE READ ITSELF, and the reason this is a separate method.
56
+ *
57
+ * `runMain` had the stdin read INSIDE the try whose catch produced a deny, so a failure there was
58
+ * still a structured block. Moving the read behind a port would have quietly narrowed that: a
59
+ * rejected read (or anything else thrown before the pipeline starts) would escape `run`, land as an
60
+ * unhandled rejection, and exit non-zero — which PreToolUse reads as a NON-BLOCKING error and lets
61
+ * the tool call THROUGH. That is the exact inversion of "a broken hook never silently lets an edit
62
+ * through", and no golden could catch it, because the goldens substitute this very port.
63
+ *
64
+ * So the try is restored one level out, around the read AND the pipeline, and it emits the same
65
+ * bytes `denyForCrash` emits for a null event.
66
+ */
67
+ async decide(args) {
68
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
69
+ try {
70
+ const raw = await this.stdin.read();
71
+ return (0, hook_core_1.runPipeline)(raw, args.mode);
72
+ }
73
+ catch (err) {
74
+ const error = (0, to_error_1.toError)(err);
75
+ return (0, agent_response_1.denyOutcome)(null, `${CRASH_PREFIX}${error.message}`, 'hook-crash');
76
+ }
77
+ }
78
+ };
79
+ exports.HookApp = HookApp;
80
+ exports.HookApp = HookApp = tslib_1.__decorate([
81
+ (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
82
+ tslib_1.__metadata("design:paramtypes", [hook_ports_1.HookStdinSource, hook_ports_1.HookStdoutSink, hook_ports_1.HookProcessExit])
83
+ ], HookApp);
84
+ /**
85
+ * THE LAST-RESORT FAIL-CLOSED BOUNDARY: the composition root itself could not run.
86
+ *
87
+ * `new Container(...)` and `container.get(HookApp)` happen BEFORE any HookApp exists to catch for
88
+ * them, so an unresolvable binding (a missing decorator, a stripped `design:paramtypes`) would exit
89
+ * non-zero with a stack on stderr — and a non-zero exit is a non-blocking error, so every guarded tool
90
+ * call would sail through unjudged for as long as the defect lasted. Low probability; total
91
+ * consequence. One shared class rather than a copy in each bin, so the two can never drift.
92
+ *
93
+ * It writes through `process` directly, and that is correct rather than a leak: by construction there
94
+ * is no container here to have handed it a port, and this is the same designated terminal boundary the
95
+ * ports themselves wrap.
96
+ */
97
+ class HookBootFailure {
98
+ // webpieces-disable no-any-unknown -- a rejection value is `unknown` by construction; toError() below is the one place that narrowing belongs
99
+ report(err) {
100
+ const error = (0, to_error_1.toError)(err);
101
+ // `null` event ⇒ no `systemMessage`. Deliberate: we never parsed a payload, so we do not know
102
+ // whether this was a Bash call, and inventing the Bash-shaped deny would be a guess.
103
+ // webpieces-disable no-process-exit-outside-main -- the hook's exit code IS the Claude Code PreToolUse protocol (exit 0 + JSON = a block); this is the last-resort terminal boundary, reached only when no container could be built to inject a port.
104
+ process.stdout.write((0, agent_response_1.denyJson)(null, `${CRASH_PREFIX}${error.message}`) + '\n');
105
+ // webpieces-disable no-process-exit-outside-main -- same terminal boundary; exiting 0 is what makes this a BLOCK rather than a non-blocking error that lets the tool call through.
106
+ process.exit(0);
107
+ }
108
+ }
109
+ exports.HookBootFailure = HookBootFailure;
110
+ //# sourceMappingURL=hook-app.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hook-app.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/adapters/hook-app.ts"],"names":[],"mappings":";;;;AAAA,yCAA2D;AAE3D,2CAA0C;AAC1C,qDAAyD;AAEzD,6CAAgF;AAChF,+CAA2C;AAE3C,kGAAkG;AAClG,uGAAuG;AACvG,aAAa;AACb,MAAM,YAAY,GAAG,yDAAyD,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C,SAAS,CAAC;6CAMlB,4BAAe,EAAU,2BAAc,EAAe,4BAAe;GAL/E,OAAO,CA2CnB;AAED;;;;;;;;;;;;GAYG;AACH,MAAa,eAAe;IACxB,8IAA8I;IAC9I,MAAM,CAAC,GAAY;QACf,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,8FAA8F;QAC9F,qFAAqF;QACrF,sPAAsP;QACtP,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,IAAA,yBAAQ,EAAC,IAAI,EAAE,GAAG,YAAY,GAAG,KAAK,CAAC,OAAO,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC;QAC/E,mLAAmL;QACnL,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;CACJ;AAXD,0CAWC","sourcesContent":["import { injectable, bindingScopeValues } from 'inversify';\n\nimport { runPipeline } from './hook-core';\nimport { denyJson, denyOutcome } from './agent-response';\nimport { HookArgs, HookOutcome } from './hook-outcome';\nimport { HookStdinSource, HookStdoutSink, HookProcessExit } from './hook-ports';\nimport { toError } from '../core/to-error';\n\n// The reason text a crash surfaces to the agent. ONE literal, used by both fail-closed boundaries\n// below and worded identically to `denyForCrash`'s so the audit trail reads the same whichever of them\n// caught it.\nconst CRASH_PREFIX = '[ai-hooks] hook crashed unexpectedly — failing closed: ';\n\n/**\n * THE COMPOSITION ROOT'S APP — one PreToolUse invocation, end to end.\n *\n * Production is three lines in `guards-hook.ts` / `rules-hook.ts`:\n *\n * const container = new Container({ autobind: true });\n * const app = container.get(HookApp);\n * await app.run(new HookArgs('guards'));\n *\n * and a test is the SAME three lines with the ports rebound to doubles — canned stdin, a captured\n * stdout, a recorded exit code. That is the whole difference, and it is the point: the test boundary\n * is cut JUST ABOVE the injection point, so the seam a test drives is the seam production drives.\n *\n * What this replaces: `runMain(mode)`, which read stdin itself and reached `process.stdout.write` /\n * `process.exit` from a dozen frames down. `runMain` is DELETED, not kept alongside — two spellings of\n * one entry point is the shim shape this repo rejects outright (see CLAUDE.md, \"NO webpieces surface\n * is released backwards-compatible\"). Nothing outside this file names it any more.\n *\n * The order of observable effects is unchanged from `runMain`: the invocation's audit line is flushed\n * at the emit boundary inside the pipeline, the decision bytes are written next, and the process exits\n * last through the injected exit port.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class HookApp {\n private readonly stdin: HookStdinSource;\n private readonly stdout: HookStdoutSink;\n private readonly processExit: HookProcessExit;\n\n constructor(stdin: HookStdinSource, stdout: HookStdoutSink, processExit: HookProcessExit) {\n this.stdin = stdin;\n this.stdout = stdout;\n this.processExit = processExit;\n }\n\n async run(args: HookArgs): Promise<void> {\n const outcome = await this.decide(args);\n // An ALLOW writes NOTHING — a silent exit 0 is the allow in the PreToolUse protocol, and an\n // empty write would still be a write on a pipe somebody is parsing. Guarded here rather than\n // in the sink so the sink stays a dumb port.\n if (outcome.stdout !== '') this.stdout.write(outcome.stdout);\n this.processExit.exit(outcome.exitCode);\n }\n\n /**\n * THE FAIL-CLOSED BOUNDARY FOR THE READ ITSELF, and the reason this is a separate method.\n *\n * `runMain` had the stdin read INSIDE the try whose catch produced a deny, so a failure there was\n * still a structured block. Moving the read behind a port would have quietly narrowed that: a\n * rejected read (or anything else thrown before the pipeline starts) would escape `run`, land as an\n * unhandled rejection, and exit non-zero — which PreToolUse reads as a NON-BLOCKING error and lets\n * the tool call THROUGH. That is the exact inversion of \"a broken hook never silently lets an edit\n * through\", and no golden could catch it, because the goldens substitute this very port.\n *\n * So the try is restored one level out, around the read AND the pipeline, and it emits the same\n * bytes `denyForCrash` emits for a null event.\n */\n private async decide(args: HookArgs): Promise<HookOutcome> {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const raw = await this.stdin.read();\n return runPipeline(raw, args.mode);\n } catch (err: unknown) {\n const error = toError(err);\n return denyOutcome(null, `${CRASH_PREFIX}${error.message}`, 'hook-crash');\n }\n }\n}\n\n/**\n * THE LAST-RESORT FAIL-CLOSED BOUNDARY: the composition root itself could not run.\n *\n * `new Container(...)` and `container.get(HookApp)` happen BEFORE any HookApp exists to catch for\n * them, so an unresolvable binding (a missing decorator, a stripped `design:paramtypes`) would exit\n * non-zero with a stack on stderr — and a non-zero exit is a non-blocking error, so every guarded tool\n * call would sail through unjudged for as long as the defect lasted. Low probability; total\n * consequence. One shared class rather than a copy in each bin, so the two can never drift.\n *\n * It writes through `process` directly, and that is correct rather than a leak: by construction there\n * is no container here to have handed it a port, and this is the same designated terminal boundary the\n * ports themselves wrap.\n */\nexport class HookBootFailure {\n // webpieces-disable no-any-unknown -- a rejection value is `unknown` by construction; toError() below is the one place that narrowing belongs\n report(err: unknown): void {\n const error = toError(err);\n // `null` event ⇒ no `systemMessage`. Deliberate: we never parsed a payload, so we do not know\n // whether this was a Bash call, and inventing the Bash-shaped deny would be a guess.\n // webpieces-disable no-process-exit-outside-main -- the hook's exit code IS the Claude Code PreToolUse protocol (exit 0 + JSON = a block); this is the last-resort terminal boundary, reached only when no container could be built to inject a port.\n process.stdout.write(denyJson(null, `${CRASH_PREFIX}${error.message}`) + '\\n');\n // webpieces-disable no-process-exit-outside-main -- same terminal boundary; exiting 0 is what makes this a BLOCK rather than a non-blocking error that lets the tool call through.\n process.exit(0);\n }\n}\n"]}
@@ -1,12 +1,21 @@
1
1
  import { HookMode } from '../core/types';
2
+ import { HookOutcome } from './hook-outcome';
2
3
  export type { HookMode };
3
4
  export type ShimStaleDecision = 'allow-cure' | 'pass' | 'deny';
4
5
  export declare function shimStaleRecoveryDecision(toolName: string, command: string, filePath: string): ShimStaleDecision;
5
6
  /**
6
- * Shared entry point for every PreToolUse adapter. `mode` selects which tool kinds to validate;
7
- * payloads outside the mode's scope pass through (emitAllow). Blocks by emitting a PreToolUse
8
- * `permissionDecision:"deny"` JSON on stdout (exit 0) — see agent-response.ts. Fails CLOSED on any
9
- * unexpected crash (emits a deny) so a broken hook never silently lets an edit through, and the reason
10
- * surfaces in the agent's UI instead of being hidden on a stderr+exit-2 block.
7
+ * THE PIPELINE, from raw stdin bytes to the decision — the whole of `parse -> adapter -> runner ->
8
+ * emit`, as ONE function returning ONE value.
9
+ *
10
+ * `mode` selects which tool kinds to validate; payloads outside the mode's scope pass through
11
+ * (emitAllow). A block is a PreToolUse `permissionDecision:"deny"` JSON on stdout with exit 0 — see
12
+ * agent-response.ts. Fails CLOSED on any unexpected crash (returns a deny) so a broken hook never
13
+ * silently lets an edit through, and the reason surfaces in the agent's UI instead of being hidden on
14
+ * a stderr+exit-2 block.
15
+ *
16
+ * It reads NO stdin, writes NO stdout and calls NO exit: those three couplings are ports owned by
17
+ * HookApp (see hook-ports.ts), which is what makes the composed pipeline drivable from a test. This
18
+ * function is what `runMain` was; it is not a second spelling of it — `runMain` is deleted, and
19
+ * `HookApp.run()` is the only entry point.
11
20
  */
12
- export declare function runMain(mode: HookMode): Promise<void>;
21
+ export declare function runPipeline(raw: string, mode: HookMode): HookOutcome;
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.shimStaleRecoveryDecision = shimStaleRecoveryDecision;
4
- exports.runMain = runMain;
4
+ exports.runPipeline = runPipeline;
5
5
  const tslib_1 = require("tslib");
6
6
  const path = tslib_1.__importStar(require("path"));
7
7
  const runner_1 = require("../core/runner");
@@ -14,28 +14,18 @@ const rules_config_1 = require("@webpieces/rules-config");
14
14
  const types_1 = require("../core/types");
15
15
  const to_error_1 = require("../core/to-error");
16
16
  const agent_response_1 = require("./agent-response");
17
+ const hook_outcome_1 = require("./hook-outcome");
17
18
  const agent_payload_1 = require("./agent-payload");
18
19
  const agent_adapters_1 = require("./agent-adapters");
19
20
  const codex_subagent_guard_1 = require("./codex-subagent-guard");
20
21
  const shim_1 = require("../bin/shim");
21
- const shim_deny_reason_1 = require("../bin/shim-deny-reason");
22
22
  const hook_registration_1 = require("../bin/hook-registration");
23
+ const shim_deny_reason_1 = require("../bin/shim-deny-reason");
23
24
  const l0_matrix_1 = require("../core/l0-matrix");
24
25
  const log_stream_1 = require("../core/log-stream");
25
26
  const l0_fault_codes_1 = require("../core/l0-fault-codes");
26
27
  const ADAPTERS = new agent_adapters_1.AgentAdapters();
27
28
  const SUBAGENT_GUARD = new codex_subagent_guard_1.CodexSubagentSharedTreeGuard();
28
- function readStdin() {
29
- return new Promise((resolve) => {
30
- let data = '';
31
- process.stdin.setEncoding('utf8');
32
- process.stdin.on('data', (chunk) => { data += chunk; });
33
- process.stdin.on('end', () => resolve(data));
34
- process.stdin.on('error', () => resolve(''));
35
- if (process.stdin.isTTY)
36
- resolve('');
37
- });
38
- }
39
29
  // The rule name for a block's audit line: the FIRST rule the report cites, or `fallback` when the
40
30
  // report opens with no `[rule]` header (a hand-written guard message). Comma-joined when a report
41
31
  // cites several, so `rule=` never silently drops one.
@@ -102,6 +92,28 @@ function handleRead(event, filePath, cwd, mode) {
102
92
  (0, rejection_log_1.logRejection)('Read', new types_1.NormalizedToolInput(filePath, []), result, cwd);
103
93
  (0, agent_response_1.emitDeny)(event, result.report, blockingRule(result.report, 'read-guard'), result.fault);
104
94
  }
95
+ /**
96
+ * Read-only tools (Read): audit-log, warm the main-sync cache, then run the ONE read-scoped guard
97
+ * (read-stale-guard) and allow. Runs BEFORE the general rule engine — no code-style rule ever sees a
98
+ * Read, and the only way this path can deny is a stale `main`. The audit trail still records every
99
+ * file the AI opened (see setup.ts).
100
+ *
101
+ * Returns normally ONLY when the event is not a Read; otherwise it ends the invocation.
102
+ */
103
+ // webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design
104
+ function handleReadFastPath(event, cwd, mode) {
105
+ if (event.kind !== 'Read')
106
+ return;
107
+ const readPath = event.reads.length > 0 ? event.reads[0] : '';
108
+ if (mode !== 'rules') {
109
+ decision_log_1.invocationLog.begin(cwd, event.rawToolName, readPath);
110
+ // Reads vastly outnumber edits, so refreshing here is what actually keeps the shared
111
+ // main-sync cache warm for feature-branch-guard. Detached; never slows the read.
112
+ (0, main_sync_refresh_1.triggerMainSyncRefresh)(cwd, (0, main_sync_timeout_1.branchStateHangTimeoutFor)(cwd));
113
+ }
114
+ handleRead(event, readPath, cwd, mode);
115
+ (0, agent_response_1.emitAllow)();
116
+ }
105
117
  /**
106
118
  * The file/edit pipeline, run once per file the call touches.
107
119
  *
@@ -222,20 +234,28 @@ function enforceCommittedShim(payload, event, cwd, mode) {
222
234
  (0, agent_response_1.emitDeny)(event, (0, shim_deny_reason_1.shimStaleDenyReason)((0, shim_1.installedShimRulesVersion)(), shimRoot ?? '', drifted, inSubagent) + (0, l0_matrix_1.guardMatrixPointer)(docPath), 'committed-shim-stale', l0_fault_codes_1.L0_FAULT_SHIM_STALE);
223
235
  }
224
236
  /**
225
- * Shared entry point for every PreToolUse adapter. `mode` selects which tool kinds to validate;
226
- * payloads outside the mode's scope pass through (emitAllow). Blocks by emitting a PreToolUse
227
- * `permissionDecision:"deny"` JSON on stdout (exit 0) — see agent-response.ts. Fails CLOSED on any
228
- * unexpected crash (emits a deny) so a broken hook never silently lets an edit through, and the reason
229
- * surfaces in the agent's UI instead of being hidden on a stderr+exit-2 block.
237
+ * THE PIPELINE, from raw stdin bytes to the decision — the whole of `parse -> adapter -> runner ->
238
+ * emit`, as ONE function returning ONE value.
239
+ *
240
+ * `mode` selects which tool kinds to validate; payloads outside the mode's scope pass through
241
+ * (emitAllow). A block is a PreToolUse `permissionDecision:"deny"` JSON on stdout with exit 0 — see
242
+ * agent-response.ts. Fails CLOSED on any unexpected crash (returns a deny) so a broken hook never
243
+ * silently lets an edit through, and the reason surfaces in the agent's UI instead of being hidden on
244
+ * a stderr+exit-2 block.
245
+ *
246
+ * It reads NO stdin, writes NO stdout and calls NO exit: those three couplings are ports owned by
247
+ * HookApp (see hook-ports.ts), which is what makes the composed pipeline drivable from a test. This
248
+ * function is what `runMain` was; it is not a second spelling of it — `runMain` is deleted, and
249
+ * `HookApp.run()` is the only entry point.
230
250
  */
231
- async function runMain(mode) {
251
+ // webpieces-disable no-function-outside-class -- the module-scope hook body itself, sibling of handleBash()/handleFileTool(); the adapter is module-scope functions by design and must stay callable from a tree too broken to build a DI container
252
+ function runPipeline(raw, mode) {
232
253
  // Captured as soon as the ENVELOPE parses so the fail-closed catch below can tell denyJson which
233
254
  // kind of call it is denying — a crash on a Bash call still gets the visible red systemMessage, a
234
255
  // crash on a file tool does not. Null (before parse / malformed input) → treated as non-Bash.
235
256
  let event = null;
236
257
  // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
237
258
  try {
238
- const raw = await readStdin();
239
259
  const payload = new agent_payload_1.AgentPayloadParser().parse(raw);
240
260
  if (!payload) {
241
261
  (0, agent_response_1.emitAllow)();
@@ -255,21 +275,8 @@ async function runMain(mode) {
255
275
  // recovery path open (cures, reads, config edit). See enforceCommittedShim / shimStaleRecoveryDecision.
256
276
  enforceCommittedShim(payload, event, cwd, mode);
257
277
  event = ADAPTERS.toEvent(payload, cwd);
258
- // Read-only tools (Read): audit-log, warm the main-sync cache, then run the ONE read-scoped
259
- // guard (read-stale-guard) and allow. Runs BEFORE the general rule engine — no code-style rule
260
- // ever sees a Read, and the only way this path can deny is a stale `main`.
261
- // The audit trail still records every file the AI opened (see setup.ts).
262
- if (event.kind === 'Read') {
263
- const readPath = event.reads.length > 0 ? event.reads[0] : '';
264
- if (mode !== 'rules') {
265
- decision_log_1.invocationLog.begin(cwd, event.rawToolName, readPath);
266
- // Reads vastly outnumber edits, so refreshing here is what actually keeps the shared
267
- // main-sync cache warm for feature-branch-guard. Detached; never slows the read.
268
- (0, main_sync_refresh_1.triggerMainSyncRefresh)(cwd, (0, main_sync_timeout_1.branchStateHangTimeoutFor)(cwd));
269
- }
270
- handleRead(event, readPath, cwd, mode);
271
- (0, agent_response_1.emitAllow)();
272
- }
278
+ // Read-only tools: their own fast path, which never returns when it applies.
279
+ handleReadFastPath(event, cwd, mode);
273
280
  // Per-invocation guard log (the `calls/` stream): tool + command/file + live branch +
274
281
  // main-sync-status snapshot, on EVERY guards call, for later cleanup automation. Best-effort;
275
282
  // never blocks the call. (The committed shim is no longer silently healed here — a mismatch is
@@ -283,7 +290,6 @@ async function runMain(mode) {
283
290
  (0, agent_response_1.emitAllow)();
284
291
  }
285
292
  handleBash(event, cwd, mode);
286
- return;
287
293
  }
288
294
  // File payloads run in 'rules' (code-style), 'guards' (file-scoped guards like
289
295
  // feature-branch-guard), and 'all'. The runner filters to the right category.
@@ -291,7 +297,12 @@ async function runMain(mode) {
291
297
  }
292
298
  catch (err) {
293
299
  const error = (0, to_error_1.toError)(err);
294
- denyForCrash(error, event);
300
+ // The pipeline's own terminal control flow, not a failure: emitAllow/emitDeny threw the answer
301
+ // out to here from wherever they were called. Treating it as a crash would turn every allow
302
+ // into a deny, so this branch comes FIRST and returns the carried outcome verbatim.
303
+ if (error instanceof hook_outcome_1.HookTerminated)
304
+ return error.outcome;
305
+ return denyForCrash(error, event);
295
306
  }
296
307
  }
297
308
  // What the `calls/` audit line names as the call's target: the command for a shell call, else the first
@@ -309,15 +320,18 @@ function logTarget(event) {
309
320
  * envelope this parser refuses to guess at) both carry an AI-readable message; anything else is an
310
321
  * unexpected bug. All three DENY and surface their reason, because a hook that crashed established
311
322
  * nothing and must never be read as an allow.
323
+ *
324
+ * It BUILDS the deny (denyOutcome) rather than throwing it (emitDeny), because it is already inside
325
+ * the catch that the throw would land in — see HookTerminated. Same bytes either way.
312
326
  */
313
327
  // webpieces-disable no-function-outside-class -- sibling of the module-scope hook entry points in this adapter; a lone class for one terminal boundary would break the file's shape
314
328
  function denyForCrash(error, event) {
315
329
  if (error instanceof types_1.RuleFailError) {
316
- (0, agent_response_1.emitDeny)(event, (0, rules_config_1.renderRuleFailForAi)(error), 'rule-crash');
330
+ return (0, agent_response_1.denyOutcome)(event, (0, rules_config_1.renderRuleFailForAi)(error), 'rule-crash');
317
331
  }
318
332
  if (error instanceof types_1.InformAiError) {
319
- (0, agent_response_1.emitDeny)(event, error.message, 'bad-config-or-stdin');
333
+ return (0, agent_response_1.denyOutcome)(event, error.message, 'bad-config-or-stdin');
320
334
  }
321
- (0, agent_response_1.emitDeny)(event, `[ai-hooks] hook crashed unexpectedly — failing closed: ${error.message}`, 'hook-crash');
335
+ return (0, agent_response_1.denyOutcome)(event, `[ai-hooks] hook crashed unexpectedly — failing closed: ${error.message}`, 'hook-crash');
322
336
  }
323
337
  //# sourceMappingURL=hook-core.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"hook-core.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/adapters/hook-core.ts"],"names":[],"mappings":";;AA0MA,8DAKC;AAoED,0BAoEC;;AAvVD,mDAA6B;AAE7B,2CAAuD;AACvD,iEAAsE;AACtE,yDAAuE;AACvE,uDAAkI;AAClI,iEAAmE;AACnE,qDAAsD;AACtD,0DAA8E;AAC9E,yCAA2G;AAE3G,+CAA2C;AAC3C,qDAAuD;AACvD,mDAAmE;AACnE,qDAAiD;AACjD,iEAA2F;AAC3F,sCAAsF;AACtF,8DAA8D;AAC9D,gEAA+D;AAC/D,iDAA4E;AAC5E,mDAA+D;AAC/D,2DAA4E;AAW5E,MAAM,QAAQ,GAAG,IAAI,8BAAa,EAAE,CAAC;AACrC,MAAM,cAAc,GAAG,IAAI,mDAA4B,EAAE,CAAC;AAE1D,SAAS,SAAS;IACd,OAAO,IAAI,OAAO,CAAC,CAAC,OAAgC,EAAE,EAAE;QACpD,IAAI,IAAI,GAAG,EAAE,CAAC;QACd,OAAO,CAAC,KAAK,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;QAClC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,KAAa,EAAE,EAAE,GAAG,IAAI,IAAI,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;QAChE,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC;QAC7C,OAAO,CAAC,KAAK,C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AAO,GAAY,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,YAAY,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;IAC/B,CAAC;AACL,CAAC;AAED,wGAAwG;AACxG,wGAAwG;AACxG,6CAA6C;AAC7C,+GAA+G;AAC/G,SAAS,SAAS,CAAC,KAAqB;IACpC,IAAI,KAAK,CAAC,IAAI,KAAK,MAAM;QAAE,OAAO,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC;IAChF,OAAO,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC;AACvE,CAAC;AAED;;;;;;GAMG;AACH,oLAAoL;AACpL,SAAS,YAAY,CAAC,KAAY,EAAE,KAA4B;IAC5D,IAAI,KAAK,YAAY,qBAAa,EAAE,CAAC;QACjC,IAAA,yBAAQ,EAAC,KAAK,EAAE,IAAA,kCAAmB,EAAC,KAAK,CAAC,EAAE,YAAY,CAAC,CAAC;IAC9D,CAAC;IACD,IAAI,KAAK,YAAY,qBAAa,EAAE,CAAC;QACjC,IAAA,yBAAQ,EAAC,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE,qBAAqB,CAAC,CAAC;IAC1D,CAAC;IACD,IAAA,yBAAQ,EAAC,KAAK,EAAE,0DAA0D,KAAK,CAAC,OAAO,EAAE,EAAE,YAAY,CAAC,CAAC;AAC7G,CAAC","sourcesContent":["import * as path from 'path';\n\nimport { run, runBash, runRead } from '../core/runner';\nimport { branchStateHangTimeoutFor } from '../core/main-sync-timeout';\nimport { logRejection, extractRuleNames } from '../core/rejection-log';\nimport { logGuardDecision, GuardDecision, branchForLog, invocationLog, MATRIX_L0_BLOCK, matrixL2Row } from '../core/decision-log';\nimport { triggerMainSyncRefresh } from '../core/main-sync-refresh';\nimport { CONFIG_FILENAME } from '../core/load-config';\nimport { RepoRootFinder, renderRuleFailForAi } from '@webpieces/rules-config';\nimport { NormalizedToolInput, InformAiError, RuleFailError, HookMode, BlockedResult } from '../core/types';\nimport { AgentHookEvent, FileOperation } from '../core/agent-event';\nimport { toError } from '../core/to-error';\nimport { emitDeny, emitAllow } from './agent-response';\nimport { AgentPayload, AgentPayloadParser } from './agent-payload';\nimport { AgentAdapters } from './agent-adapters';\nimport { CodexSubagentSharedTreeGuard, CODEX_SUBAGENT_RULE } from './codex-subagent-guard';\nimport { governingShimRoot, isAllowed, installedShimRulesVersion } from '../bin/shim';\nimport { shimStaleDenyReason } from '../bin/shim-deny-reason';\nimport { managedSurfaceDrift } from '../bin/hook-registration';\nimport { writeGuardMatrixDoc, guardMatrixPointer } from '../core/l0-matrix';\nimport { logStream, StreamIdentity } from '../core/log-stream';\nimport { L0_FAULT_SHIM_STALE, L0_FAULT_NONE } from '../core/l0-fault-codes';\n\n// Which category of rules this hook invocation runs. The hook is split into two independently\n// installable PreToolUse hooks; each runs ONE category (the runner filters by it), and both can\n// receive file AND bash payloads:\n// - 'rules' → code-style rules (file/edit scope). Bash payloads pass through (no code rules apply).\n// - 'guards' → hookGuards section: bash git/PR guards on Bash AND file guards (feature-branch-guard)\n// on Write/Edit, PLUS a log-and-allow audit of Read. Matcher is Write|Edit|MultiEdit|Bash|Read.\n// - 'all' → both categories, used by the openclaw plugin adapter (a single before_tool_call hook).\nexport type { HookMode };\n\nconst ADAPTERS = new AgentAdapters();\nconst SUBAGENT_GUARD = new CodexSubagentSharedTreeGuard();\n\nfunction readStdin(): Promise<string> {\n return new Promise((resolve: (value: string) => void) => {\n let data = '';\n process.stdin.setEncoding('utf8');\n process.stdin.on('data', (chunk: string) => { data += chunk; });\n process.stdin.on('end', () => resolve(data));\n process.stdin.on('error', () => resolve(''));\n if (process.stdin.isTTY) resolve('');\n });\n}\n\n// The rule name for a block's audit line: the FIRST rule the report cites, or `fallback` when the\n// report opens with no `[rule]` header (a hand-written guard message). Comma-joined when a report\n// cites several, so `rule=` never silently drops one.\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction blockingRule(report: string, fallback: string): string {\n const names = extractRuleNames(report);\n return names.length > 0 ? names.join(',') : fallback;\n}\n\n// webpieces-disable no-function-outside-class -- sibling of handleRead()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction handleBash(event: AgentHookEvent, cwd: string, mode: HookMode): void {\n const command = event.bash === null ? '' : event.bash.command;\n if (command.trim() === '') { emitAllow(); }\n\n // READ PARITY, and it can only ever be reached from a Codex event: the adapter leaves `reads`\n // empty for Claude Code, which has a real `Read` tool and its own fast path. A Codex read arrives\n // as `Bash` running a pager, so without this the read guard and the `calls/` audit trail see none\n // of them. The command is STILL run through the bash guards below — this adds a verdict, it never\n // replaces one.\n for (const readPath of event.reads) {\n handleRead(event, readPath, cwd, mode);\n }\n\n const result = runBash(command, cwd, mode);\n if (!result) { emitAllow(); }\n // NO DECISION LINE HERE. This used to write a generic `bash-guard` line because a Bash deny once\n // had no audit trail at all — but every layer now records its own: L1 into `L1-location/` with its\n // row, L2's guards into `L2-decisions/` with their rule and cache, and emitDeny below stamps the\n // call-level outcome onto `calls/`. So this was the THIRD line for one block, and the worst of the\n // three: it re-resolved the root from `cwd` via RepoRootFinder, which is not necessarily the tree\n // the guard actually judged, so a `cd`-relocated command scattered one block across two different\n // `.webpieces` directories.\n //\n // Bash deny → the event's kind is 'Bash', so denyJson adds the ANSI-red systemMessage (the only\n // field a Bash deny shows the human; permissionDecisionReason is invisible on Bash). See\n // agent-response.ts.\n emitDeny(event, result.report, blockingRule(result.report, 'bash-guard'), result.fault);\n}\n\n/**\n * The read-scoped guard pass. Returns normally to ALLOW; only calls emitDeny when the guard fires.\n *\n * Wrapped in its own catch that swallows into an allow. Every other path in this hook fails CLOSED,\n * and that is right for edits and shell commands — but a crash here would block the agent from\n * READING, which includes reading webpieces.config.json to turn the offending guard off. So this one\n * path deliberately inverts the policy: a broken read-guard degrades to a no-op, never to a wedge.\n */\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction handleRead(event: AgentHookEvent, filePath: string, cwd: string, mode: HookMode): void {\n if (filePath === '') return;\n let result: BlockedResult | null = null;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n result = runRead(filePath, cwd, mode);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return; // fail OPEN — see the doc comment\n }\n if (!result) return;\n logRejection('Read', new NormalizedToolInput(filePath, []), result, cwd);\n emitDeny(event, result.report, blockingRule(result.report, 'read-guard'), result.fault);\n}\n\n/**\n * The file/edit pipeline, run once per file the call touches.\n *\n * `event.files` is a LIST because ONE Codex `apply_patch` carries many files with mixed operations.\n * A Claude Code event always has exactly one entry, so the loop runs once and the behaviour is the\n * single-file behaviour it has always had.\n */\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleRead() in this module; the adapter is module-scope functions by design\nfunction handleFileTool(event: AgentHookEvent, cwd: string, mode: HookMode): void {\n if (event.files.length === 0) { emitAllow(); }\n\n // A Codex SUBAGENT writing into the tree it shares with its coordinator. Returns null for every\n // Claude Code event — that harness can hand a subagent its own worktree, and does.\n const subagentBlock = SUBAGENT_GUARD.check(event, new RepoRootFinder().resolveRepoRoot(cwd));\n if (subagentBlock) {\n emitDeny(event, subagentBlock.report, CODEX_SUBAGENT_RULE, subagentBlock.fault);\n }\n\n for (const file of event.files) {\n handleOneFile(event, file, cwd, mode);\n }\n emitAllow();\n}\n\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction handleOneFile(event: AgentHookEvent, file: FileOperation, cwd: string, mode: HookMode): void {\n const input = file.input;\n\n // Always allow edits to webpieces.config.json — it's the fix target when the config is broken.\n // This returns BEFORE run(), so feature-branch-guard never sees a config edit; record that so the\n // audit trail explains why a config edit on a bad branch was not blocked (see decision-log.ts).\n if (path.basename(input.filePath) === CONFIG_FILENAME) {\n if (mode !== 'rules') {\n // `.webpieces/` (the decision log + sync cache these two calls write) lives at the repo\n // root, not the AI's cwd — resolve it so a config edit from a subdir doesn't create a\n // stray `<subdir>/.webpieces` tree.\n const root = new RepoRootFinder().resolveRepoRoot(cwd);\n logGuardDecision(\n root,\n new GuardDecision('feature-branch-guard', file.toolKind, input.filePath, branchForLog(root), 'ALLOW_EXEMPT', 'config-bypass (feature-branch-guard skipped)', '-', L0_FAULT_NONE, matrixL2Row('config-bypass (feature-branch-guard skipped)')),\n );\n // The guard's own refresh trigger lives inside its check(), which we skip here — so warm\n // the cache directly, otherwise a session that only edits webpieces.config.json never\n // refreshes the sync status. Fire-and-forget; never blocks the edit.\n triggerMainSyncRefresh(root, branchStateHangTimeoutFor(cwd));\n }\n return;\n }\n\n const result = run(file.toolKind, input, cwd, mode);\n if (!result) return;\n\n logRejection(file.toolKind, input, result, cwd);\n // File-tool deny → the event's kind is 'File', so denyJson omits systemMessage (the reason\n // already renders red natively for these tools). See agent-response.ts.\n emitDeny(event, result.report, blockingRule(result.report, 'file-guard'), result.fault);\n}\n\n// What a stale committed shim lets through — now a thin adapter over the ONE L0 allowlist (isAllowed in\n// ../bin/shim), not a list of its own. A stale shim must NEVER trap the actions needed to recover: the\n// original \"block everything but the cures\" version also shadowed the always-allowed\n// webpieces.config.json edit (handleFileTool) and blocked reads, so a repo that ALSO needed its config\n// fixed would deadlock — blocked from editing the one file whose edit is normally always allowed, and\n// blocked from reading it to know how.\n//\n// It used to carry its OWN narrower list (isShimCureCommand: the three shim cures only), and that\n// narrowness was a defect, not a safety property: `pnpm install` and `git pull` — the two commands that\n// resolve the version disagreement underneath a stale shim — were denied. Consulting the shared\n// allowlist fixes that by construction.\n//\n// What is NOT a defect, and must not be \"fixed\": those cures rewrite the committed shim from the\n// INSTALLED binary's renderShim(), overwriting whatever was there. That is the invariant, not\n// collateral damage. The shim (D/X/K, in POSIX sh, pre-binary) and this binary (S/C/Y, in JS) are two\n// halves of ONE L0 and they exchange assumptions — the shim parses file_path and carries ALLOW-READ /\n// ALLOW-CONFIG entries this binary relies on. Pair a binary with a shim rendered by a DIFFERENT\n// release and L0 acquires holes that nothing reports. So the rule is absolute: the committed shim\n// equals renderShim() of the binary in node_modules, and a cure that forces that is the cure working.\n// See healShim's header, which states the same invariant from the other side.\n//\n// Corollary for anyone regenerating the shim in a webpieces PR: commit `templates/ai-hook.sh` (source,\n// locked to renderShim() by unit test) and leave `.claude/webpieces/ai-hook.sh` (generated artifact)\n// alone. In THIS repo the local source runs ahead of the pinned node_modules, so committing a shim\n// rendered from local source produces a commit whose shim and whose @webpieces pin come from different\n// releases — precisely the mismatch above. The artifact heals on the next upgrade; that is its job.\n//\n// - 'allow-cure' → a Bash cure on the allowlist: emitAllow directly, bypassing the git guards.\n// - 'pass' → a recovery action the normal flow already permits, so fall THROUGH and let it: ANY\n// Read (you must read to know how to fix — see handleRead, which itself fails open),\n// or an edit to webpieces.config.json (the always-allowed recovery target).\n// - 'deny' → all OTHER work: blocked until the committed shim matches renderShim() again.\nexport type ShimStaleDecision = 'allow-cure' | 'pass' | 'deny';\n// webpieces-disable no-function-outside-class -- pure decision helper beside the adapter's other module-scope functions; exported for direct unit testing.\nexport function shimStaleRecoveryDecision(toolName: string, command: string, filePath: string): ShimStaleDecision {\n const allowed = isAllowed(toolName, command, filePath);\n if (allowed === 'pass') return 'pass';\n if (allowed === 'allow') return 'allow-cure';\n return 'deny';\n}\n\n// MANAGED-HOOK-SURFACE self-guard, moved here from the rendered shim (2026-07-24) and widened from one\n// file to three (2026-08-07). The committed\n// .claude/webpieces/ai-hook.sh is webpieces-MANAGED and generated from renderShim(); if it no longer\n// matches, it was reverted / hand-edited / predates this binary, so its OWN fail-closed logic can't be\n// trusted. We are the CURRENT binary from node_modules — the trustworthy party — so WE decide here\n// instead of the (possibly stale) shim. It used to `cmp` itself inside the shim: a double-edged trap,\n// since the check lived in the very file it guarded and a fix could only ship by regenerating that\n// file. Now we fail closed on all real WORK while always leaving the recovery path open (see\n// shimStaleRecoveryDecision): the whole L0 allowlist, any Read, and editing webpieces.config.json. We deny +\n// tell the AI; we do NOT silently rewrite the file under it. 'rules' hook skips it (guards owns the\n// shim). Returns normally (pass / nothing to do) or exits via emitAllow/emitDeny.\n//\n// It asks the allowlist about the RAW WIRE FIELDS, not about the normalized event, and that ordering is\n// deliberate: L0 has to hold on a tree too broken to trust anything above it, including the adapters.\n// The raw fields are the same key names in both harnesses (measured), so one reading serves both, and\n// the answer cannot change because a normalizer changed. `event` is here only to decorate the deny.\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction enforceCommittedShim(payload: AgentPayload, event: AgentHookEvent, cwd: string, mode: HookMode): void {\n // ONE root for the whole decision, resolved from the RUNNING MODULE (governingShimRoot), never from\n // `cwd`: the shim file we compare and the renderShim() we compare it TO must come from the same\n // install, or the check straddles two trees and can never converge (see governingShimRoot's header).\n // `cwd` still selects where the L0 matrix doc is dropped — that is a \"where does the AI read\" question,\n // not part of the judgement.\n const shimRoot = governingShimRoot();\n if (mode === 'rules') return;\n // WHICH of the three managed things moved — ai-hook.sh, the settings.json registration, or its\n // managed env entry (the Bash-cwd pin that keeps a guard's verdict independent of where an earlier\n // `cd` left the shell; see managed-env.ts). Nothing validated the registration before it joined this\n // fault, so a settings file left on a superseded form silently changed WHO GOVERNS, with no signal\n // anywhere — which is the whole reason the registration is a drift surface and not just an install\n // step.\n const drifted = managedSurfaceDrift(shimRoot);\n if (drifted.length === 0) return;\n const decision = shimStaleRecoveryDecision(payload.tool_name, payload.tool_input.command ?? '', payload.tool_input.file_path ?? '');\n if (decision === 'pass') return;\n if (decision === 'allow-cure') emitAllow();\n // Drop the L0 matrix doc where the AI can read it and point the deny at it — a Read is entry 1 of\n // the same allowlist, so the pointer is always followable. Best-effort: no doc → no pointer.\n const root = new RepoRootFinder().resolveRepoRoot(cwd);\n const docPath = writeGuardMatrixDoc(root);\n // WRITE THE AUDIT LINE HERE. This block happens BEFORE invocationLog.begin() — it has to, since a\n // stale shim invalidates everything downstream — so emitDeny's flush finds nothing pending and an\n // `S` storm left NO trace at all: the one fault most likely to block twenty consecutive tool calls\n // was the one fault the trail could not show. A decision line is the fix that costs no reordering.\n const target = payload.tool_input.command ?? payload.tool_input.file_path ?? '';\n logGuardDecision(\n root,\n new GuardDecision('committed-shim-stale', payload.tool_name, target, branchForLog(root), 'BLOCK_AI_CURE', 'L0 fault S (committed shim != renderShim)', '-', L0_FAULT_SHIM_STALE, MATRIX_L0_BLOCK),\n );\n // L0 fault S in GUARD_MATRIX.md's codebook — named as the blocking rule so the invocation line\n // says WHAT stopped the call, not merely that something did, and stamped as `fault=S` so the same\n // grep finds it here as in the sh half's `L0-shim/` stream.\n // A subagent is discriminated by `agent_id`, which BOTH harnesses populate on stdin only off the\n // main loop (main falls back to the session id / leaves it empty). Its cure differs: the hooks\n // blocking it resolve through CLAUDE_PROJECT_DIR, which names the MAIN tree.\n const inSubagent = event.agentId !== '';\n emitDeny(event, shimStaleDenyReason(installedShimRulesVersion(), shimRoot ?? '', drifted, inSubagent) + guardMatrixPointer(docPath), 'committed-shim-stale', L0_FAULT_SHIM_STALE);\n}\n\n/**\n * Shared entry point for every PreToolUse adapter. `mode` selects which tool kinds to validate;\n * payloads outside the mode's scope pass through (emitAllow). Blocks by emitting a PreToolUse\n * `permissionDecision:\"deny\"` JSON on stdout (exit 0) — see agent-response.ts. Fails CLOSED on any\n * unexpected crash (emits a deny) so a broken hook never silently lets an edit through, and the reason\n * surfaces in the agent's UI instead of being hidden on a stderr+exit-2 block.\n */\nexport async function runMain(mode: HookMode): Promise<void> {\n // Captured as soon as the ENVELOPE parses so the fail-closed catch below can tell denyJson which\n // kind of call it is denying — a crash on a Bash call still gets the visible red systemMessage, a\n // crash on a file tool does not. Null (before parse / malformed input) → treated as non-Bash.\n let event: AgentHookEvent | null = null;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const raw = await readStdin();\n const payload = new AgentPayloadParser().parse(raw);\n if (!payload) { emitAllow(); }\n // The envelope shape first: it reads only `tool_name` and the identity fields, so it cannot\n // fail, and it is what the crash path needs. The full normalization below reads `tool_input`\n // and CAN fail (a malformed Codex patch envelope denies rather than being half-understood).\n event = ADAPTERS.envelope(payload);\n\n // BEFORE enforceCommittedShim(), which can itself write a BLOCK line. See LogStream for why\n // all three of session/agent/hook are needed to keep concurrent writers off one file.\n logStream.identify(new StreamIdentity(event.sessionId, event.agentId, mode));\n\n // Prefer the payload cwd (the AI's actual working dir, follows a persisted `cd`) over\n // process.cwd(); they match today, but the payload is the authoritative signal and stays\n // correct if the hook is ever invoked from a fixed dir (e.g. via $CLAUDE_PROJECT_DIR).\n const cwd = payload.cwd ?? process.cwd();\n\n // Committed-shim self-guard: blocks real work while the committed shim is stale, but keeps the\n // recovery path open (cures, reads, config edit). See enforceCommittedShim / shimStaleRecoveryDecision.\n enforceCommittedShim(payload, event, cwd, mode);\n\n event = ADAPTERS.toEvent(payload, cwd);\n\n // Read-only tools (Read): audit-log, warm the main-sync cache, then run the ONE read-scoped\n // guard (read-stale-guard) and allow. Runs BEFORE the general rule engine — no code-style rule\n // ever sees a Read, and the only way this path can deny is a stale `main`.\n // The audit trail still records every file the AI opened (see setup.ts).\n if (event.kind === 'Read') {\n const readPath = event.reads.length > 0 ? event.reads[0] : '';\n if (mode !== 'rules') {\n invocationLog.begin(cwd, event.rawToolName, readPath);\n // Reads vastly outnumber edits, so refreshing here is what actually keeps the shared\n // main-sync cache warm for feature-branch-guard. Detached; never slows the read.\n triggerMainSyncRefresh(cwd, branchStateHangTimeoutFor(cwd));\n }\n handleRead(event, readPath, cwd, mode);\n emitAllow();\n }\n\n // Per-invocation guard log (the `calls/` stream): tool + command/file + live branch +\n // main-sync-status snapshot, on EVERY guards call, for later cleanup automation. Best-effort;\n // never blocks the call. (The committed shim is no longer silently healed here — a mismatch is\n // reported by the self-guard above, not rewritten out from under the AI.)\n if (mode !== 'rules') {\n invocationLog.begin(cwd, event.rawToolName, logTarget(event));\n }\n\n if (event.kind === 'Bash') {\n // No code-style rule is bash-scoped, so the rules hook ignores Bash.\n if (mode === 'rules') { emitAllow(); }\n handleBash(event, cwd, mode);\n return;\n }\n\n // File payloads run in 'rules' (code-style), 'guards' (file-scoped guards like\n // feature-branch-guard), and 'all'. The runner filters to the right category.\n handleFileTool(event, cwd, mode);\n } catch (err: unknown) {\n const error = toError(err);\n denyForCrash(error, event);\n }\n}\n\n// What the `calls/` audit line names as the call's target: the command for a shell call, else the first\n// file it touches. A Codex `apply_patch` touching several files names the first — the rejection log and\n// the decision log carry the rest, per file.\n// webpieces-disable no-function-outside-class -- sibling of the module-scope hook entry points in this adapter\nfunction logTarget(event: AgentHookEvent): string {\n if (event.kind === 'Bash') return event.bash === null ? '' : event.bash.command;\n return event.files.length > 0 ? event.files[0].input.filePath : '';\n}\n\n/**\n * The fail-closed boundary for anything that escaped the hook body. An escaped RuleFailError (a rule\n * that threw past the runner's per-rule catch) or an InformAiError (bad config/stdin, or a Codex patch\n * envelope this parser refuses to guess at) both carry an AI-readable message; anything else is an\n * unexpected bug. All three DENY and surface their reason, because a hook that crashed established\n * nothing and must never be read as an allow.\n */\n// webpieces-disable no-function-outside-class -- sibling of the module-scope hook entry points in this adapter; a lone class for one terminal boundary would break the file's shape\nfunction denyForCrash(error: Error, event: AgentHookEvent | null): never {\n if (error instanceof RuleFailError) {\n emitDeny(event, renderRuleFailForAi(error), 'rule-crash');\n }\n if (error instanceof InformAiError) {\n emitDeny(event, error.message, 'bad-config-or-stdin');\n }\n emitDeny(event, `[ai-hooks] hook crashed unexpectedly — failing closed: ${error.message}`, 'hook-crash');\n}\n"]}
1
+ {"version":3,"file":"hook-core.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/ad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,kCAAmB,EAAC,KAAK,CAAC,EAAE,YAAY,CAAC,CAAC;IACxE,CAAC;IACD,IAAI,KAAK,YAAY,qBAAa,EAAE,CAAC;QACjC,OAAO,IAAA,4BAAW,EAAC,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE,qBAAqB,CAAC,CAAC;IACpE,CAAC;IACD,OAAO,IAAA,4BAAW,EAAC,KAAK,EAAE,0DAA0D,KAAK,CAAC,OAAO,EAAE,EAAE,YAAY,CAAC,CAAC;AACvH,CAAC","sourcesContent":["import * as path from 'path';\n\nimport { run, runBash, runRead } from '../core/runner';\nimport { branchStateHangTimeoutFor } from '../core/main-sync-timeout';\nimport { logRejection, extractRuleNames } from '../core/rejection-log';\nimport { logGuardDecision, GuardDecision, branchForLog, invocationLog, MATRIX_L0_BLOCK, matrixL2Row } from '../core/decision-log';\nimport { triggerMainSyncRefresh } from '../core/main-sync-refresh';\nimport { CONFIG_FILENAME } from '../core/load-config';\nimport { RepoRootFinder, renderRuleFailForAi } from '@webpieces/rules-config';\nimport { NormalizedToolInput, InformAiError, RuleFailError, HookMode, BlockedResult } from '../core/types';\nimport { AgentHookEvent, FileOperation } from '../core/agent-event';\nimport { toError } from '../core/to-error';\nimport { emitDeny, emitAllow, denyOutcome } from './agent-response';\nimport { HookOutcome, HookTerminated } from './hook-outcome';\nimport { AgentPayload, AgentPayloadParser } from './agent-payload';\nimport { AgentAdapters } from './agent-adapters';\nimport { CodexSubagentSharedTreeGuard, CODEX_SUBAGENT_RULE } from './codex-subagent-guard';\nimport { governingShimRoot, isAllowed, installedShimRulesVersion } from '../bin/shim';\nimport { managedSurfaceDrift } from '../bin/hook-registration';\nimport { shimStaleDenyReason } from '../bin/shim-deny-reason';\nimport { writeGuardMatrixDoc, guardMatrixPointer } from '../core/l0-matrix';\nimport { logStream, StreamIdentity } from '../core/log-stream';\nimport { L0_FAULT_SHIM_STALE, L0_FAULT_NONE } from '../core/l0-fault-codes';\n\n// Which category of rules this hook invocation runs. The hook is split into two independently\n// installable PreToolUse hooks; each runs ONE category (the runner filters by it), and both can\n// receive file AND bash payloads:\n// - 'rules' → code-style rules (file/edit scope). Bash payloads pass through (no code rules apply).\n// - 'guards' → hookGuards section: bash git/PR guards on Bash AND file guards (feature-branch-guard)\n// on Write/Edit, PLUS a log-and-allow audit of Read. Matcher is Write|Edit|MultiEdit|Bash|Read.\n// - 'all' → both categories, used by the openclaw plugin adapter (a single before_tool_call hook).\nexport type { HookMode };\n\nconst ADAPTERS = new AgentAdapters();\nconst SUBAGENT_GUARD = new CodexSubagentSharedTreeGuard();\n\n// The rule name for a block's audit line: the FIRST rule the report cites, or `fallback` when the\n// report opens with no `[rule]` header (a hand-written guard message). Comma-joined when a report\n// cites several, so `rule=` never silently drops one.\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction blockingRule(report: string, fallback: string): string {\n const names = extractRuleNames(report);\n return names.length > 0 ? names.join(',') : fallback;\n}\n\n// webpieces-disable no-function-outside-class -- sibling of handleRead()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction handleBash(event: AgentHookEvent, cwd: string, mode: HookMode): never {\n const command = event.bash === null ? '' : event.bash.command;\n if (command.trim() === '') { emitAllow(); }\n\n // READ PARITY, and it can only ever be reached from a Codex event: the adapter leaves `reads`\n // empty for Claude Code, which has a real `Read` tool and its own fast path. A Codex read arrives\n // as `Bash` running a pager, so without this the read guard and the `calls/` audit trail see none\n // of them. The command is STILL run through the bash guards below — this adds a verdict, it never\n // replaces one.\n for (const readPath of event.reads) {\n handleRead(event, readPath, cwd, mode);\n }\n\n const result = runBash(command, cwd, mode);\n if (!result) { emitAllow(); }\n // NO DECISION LINE HERE. This used to write a generic `bash-guard` line because a Bash deny once\n // had no audit trail at all — but every layer now records its own: L1 into `L1-location/` with its\n // row, L2's guards into `L2-decisions/` with their rule and cache, and emitDeny below stamps the\n // call-level outcome onto `calls/`. So this was the THIRD line for one block, and the worst of the\n // three: it re-resolved the root from `cwd` via RepoRootFinder, which is not necessarily the tree\n // the guard actually judged, so a `cd`-relocated command scattered one block across two different\n // `.webpieces` directories.\n //\n // Bash deny → the event's kind is 'Bash', so denyJson adds the ANSI-red systemMessage (the only\n // field a Bash deny shows the human; permissionDecisionReason is invisible on Bash). See\n // agent-response.ts.\n emitDeny(event, result.report, blockingRule(result.report, 'bash-guard'), result.fault);\n}\n\n/**\n * The read-scoped guard pass. Returns normally to ALLOW; only calls emitDeny when the guard fires.\n *\n * Wrapped in its own catch that swallows into an allow. Every other path in this hook fails CLOSED,\n * and that is right for edits and shell commands — but a crash here would block the agent from\n * READING, which includes reading webpieces.config.json to turn the offending guard off. So this one\n * path deliberately inverts the policy: a broken read-guard degrades to a no-op, never to a wedge.\n */\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction handleRead(event: AgentHookEvent, filePath: string, cwd: string, mode: HookMode): void {\n if (filePath === '') return;\n let result: BlockedResult | null = null;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n result = runRead(filePath, cwd, mode);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return; // fail OPEN — see the doc comment\n }\n if (!result) return;\n logRejection('Read', new NormalizedToolInput(filePath, []), result, cwd);\n emitDeny(event, result.report, blockingRule(result.report, 'read-guard'), result.fault);\n}\n\n/**\n * Read-only tools (Read): audit-log, warm the main-sync cache, then run the ONE read-scoped guard\n * (read-stale-guard) and allow. Runs BEFORE the general rule engine — no code-style rule ever sees a\n * Read, and the only way this path can deny is a stale `main`. The audit trail still records every\n * file the AI opened (see setup.ts).\n *\n * Returns normally ONLY when the event is not a Read; otherwise it ends the invocation.\n */\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction handleReadFastPath(event: AgentHookEvent, cwd: string, mode: HookMode): void {\n if (event.kind !== 'Read') return;\n const readPath = event.reads.length > 0 ? event.reads[0] : '';\n if (mode !== 'rules') {\n invocationLog.begin(cwd, event.rawToolName, readPath);\n // Reads vastly outnumber edits, so refreshing here is what actually keeps the shared\n // main-sync cache warm for feature-branch-guard. Detached; never slows the read.\n triggerMainSyncRefresh(cwd, branchStateHangTimeoutFor(cwd));\n }\n handleRead(event, readPath, cwd, mode);\n emitAllow();\n}\n\n/**\n * The file/edit pipeline, run once per file the call touches.\n *\n * `event.files` is a LIST because ONE Codex `apply_patch` carries many files with mixed operations.\n * A Claude Code event always has exactly one entry, so the loop runs once and the behaviour is the\n * single-file behaviour it has always had.\n */\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleRead() in this module; the adapter is module-scope functions by design\nfunction handleFileTool(event: AgentHookEvent, cwd: string, mode: HookMode): never {\n if (event.files.length === 0) { emitAllow(); }\n\n // A Codex SUBAGENT writing into the tree it shares with its coordinator. Returns null for every\n // Claude Code event — that harness can hand a subagent its own worktree, and does.\n const subagentBlock = SUBAGENT_GUARD.check(event, new RepoRootFinder().resolveRepoRoot(cwd));\n if (subagentBlock) {\n emitDeny(event, subagentBlock.report, CODEX_SUBAGENT_RULE, subagentBlock.fault);\n }\n\n for (const file of event.files) {\n handleOneFile(event, file, cwd, mode);\n }\n emitAllow();\n}\n\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction handleOneFile(event: AgentHookEvent, file: FileOperation, cwd: string, mode: HookMode): void {\n const input = file.input;\n\n // Always allow edits to webpieces.config.json — it's the fix target when the config is broken.\n // This returns BEFORE run(), so feature-branch-guard never sees a config edit; record that so the\n // audit trail explains why a config edit on a bad branch was not blocked (see decision-log.ts).\n if (path.basename(input.filePath) === CONFIG_FILENAME) {\n if (mode !== 'rules') {\n // `.webpieces/` (the decision log + sync cache these two calls write) lives at the repo\n // root, not the AI's cwd — resolve it so a config edit from a subdir doesn't create a\n // stray `<subdir>/.webpieces` tree.\n const root = new RepoRootFinder().resolveRepoRoot(cwd);\n logGuardDecision(\n root,\n new GuardDecision('feature-branch-guard', file.toolKind, input.filePath, branchForLog(root), 'ALLOW_EXEMPT', 'config-bypass (feature-branch-guard skipped)', '-', L0_FAULT_NONE, matrixL2Row('config-bypass (feature-branch-guard skipped)')),\n );\n // The guard's own refresh trigger lives inside its check(), which we skip here — so warm\n // the cache directly, otherwise a session that only edits webpieces.config.json never\n // refreshes the sync status. Fire-and-forget; never blocks the edit.\n triggerMainSyncRefresh(root, branchStateHangTimeoutFor(cwd));\n }\n return;\n }\n\n const result = run(file.toolKind, input, cwd, mode);\n if (!result) return;\n\n logRejection(file.toolKind, input, result, cwd);\n // File-tool deny → the event's kind is 'File', so denyJson omits systemMessage (the reason\n // already renders red natively for these tools). See agent-response.ts.\n emitDeny(event, result.report, blockingRule(result.report, 'file-guard'), result.fault);\n}\n\n// What a stale committed shim lets through — now a thin adapter over the ONE L0 allowlist (isAllowed in\n// ../bin/shim), not a list of its own. A stale shim must NEVER trap the actions needed to recover: the\n// original \"block everything but the cures\" version also shadowed the always-allowed\n// webpieces.config.json edit (handleFileTool) and blocked reads, so a repo that ALSO needed its config\n// fixed would deadlock — blocked from editing the one file whose edit is normally always allowed, and\n// blocked from reading it to know how.\n//\n// It used to carry its OWN narrower list (isShimCureCommand: the three shim cures only), and that\n// narrowness was a defect, not a safety property: `pnpm install` and `git pull` — the two commands that\n// resolve the version disagreement underneath a stale shim — were denied. Consulting the shared\n// allowlist fixes that by construction.\n//\n// What is NOT a defect, and must not be \"fixed\": those cures rewrite the committed shim from the\n// INSTALLED binary's renderShim(), overwriting whatever was there. That is the invariant, not\n// collateral damage. The shim (D/X/K, in POSIX sh, pre-binary) and this binary (S/C/Y, in JS) are two\n// halves of ONE L0 and they exchange assumptions — the shim parses file_path and carries ALLOW-READ /\n// ALLOW-CONFIG entries this binary relies on. Pair a binary with a shim rendered by a DIFFERENT\n// release and L0 acquires holes that nothing reports. So the rule is absolute: the committed shim\n// equals renderShim() of the binary in node_modules, and a cure that forces that is the cure working.\n// See healShim's header, which states the same invariant from the other side.\n//\n// Corollary for anyone regenerating the shim in a webpieces PR: commit `templates/ai-hook.sh` (source,\n// locked to renderShim() by unit test) and leave `.claude/webpieces/ai-hook.sh` (generated artifact)\n// alone. In THIS repo the local source runs ahead of the pinned node_modules, so committing a shim\n// rendered from local source produces a commit whose shim and whose @webpieces pin come from different\n// releases — precisely the mismatch above. The artifact heals on the next upgrade; that is its job.\n//\n// - 'allow-cure' → a Bash cure on the allowlist: emitAllow directly, bypassing the git guards.\n// - 'pass' → a recovery action the normal flow already permits, so fall THROUGH and let it: ANY\n// Read (you must read to know how to fix — see handleRead, which itself fails open),\n// or an edit to webpieces.config.json (the always-allowed recovery target).\n// - 'deny' → all OTHER work: blocked until the committed shim matches renderShim() again.\nexport type ShimStaleDecision = 'allow-cure' | 'pass' | 'deny';\n// webpieces-disable no-function-outside-class -- pure decision helper beside the adapter's other module-scope functions; exported for direct unit testing.\nexport function shimStaleRecoveryDecision(toolName: string, command: string, filePath: string): ShimStaleDecision {\n const allowed = isAllowed(toolName, command, filePath);\n if (allowed === 'pass') return 'pass';\n if (allowed === 'allow') return 'allow-cure';\n return 'deny';\n}\n\n// MANAGED-HOOK-SURFACE self-guard, moved here from the rendered shim (2026-07-24) and widened from one\n// file to three (2026-08-07). The committed\n// .claude/webpieces/ai-hook.sh is webpieces-MANAGED and generated from renderShim(); if it no longer\n// matches, it was reverted / hand-edited / predates this binary, so its OWN fail-closed logic can't be\n// trusted. We are the CURRENT binary from node_modules — the trustworthy party — so WE decide here\n// instead of the (possibly stale) shim. It used to `cmp` itself inside the shim: a double-edged trap,\n// since the check lived in the very file it guarded and a fix could only ship by regenerating that\n// file. Now we fail closed on all real WORK while always leaving the recovery path open (see\n// shimStaleRecoveryDecision): the whole L0 allowlist, any Read, and editing webpieces.config.json. We deny +\n// tell the AI; we do NOT silently rewrite the file under it. 'rules' hook skips it (guards owns the\n// shim). Returns normally (pass / nothing to do) or exits via emitAllow/emitDeny.\n//\n// It asks the allowlist about the RAW WIRE FIELDS, not about the normalized event, and that ordering is\n// deliberate: L0 has to hold on a tree too broken to trust anything above it, including the adapters.\n// The raw fields are the same key names in both harnesses (measured), so one reading serves both, and\n// the answer cannot change because a normalizer changed. `event` is here only to decorate the deny.\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction enforceCommittedShim(payload: AgentPayload, event: AgentHookEvent, cwd: string, mode: HookMode): void {\n // ONE root for the whole decision, resolved from the RUNNING MODULE (governingShimRoot), never from\n // `cwd`: the shim file we compare and the renderShim() we compare it TO must come from the same\n // install, or the check straddles two trees and can never converge (see governingShimRoot's header).\n // `cwd` still selects where the L0 matrix doc is dropped — that is a \"where does the AI read\" question,\n // not part of the judgement.\n const shimRoot = governingShimRoot();\n if (mode === 'rules') return;\n // WHICH of the three managed things moved — ai-hook.sh, the settings.json registration, or its\n // managed env entry (the Bash-cwd pin that keeps a guard's verdict independent of where an earlier\n // `cd` left the shell; see managed-env.ts). Nothing validated the registration before it joined this\n // fault, so a settings file left on a superseded form silently changed WHO GOVERNS, with no signal\n // anywhere — which is the whole reason the registration is a drift surface and not just an install\n // step.\n const drifted = managedSurfaceDrift(shimRoot);\n if (drifted.length === 0) return;\n const decision = shimStaleRecoveryDecision(payload.tool_name, payload.tool_input.command ?? '', payload.tool_input.file_path ?? '');\n if (decision === 'pass') return;\n if (decision === 'allow-cure') emitAllow();\n // Drop the L0 matrix doc where the AI can read it and point the deny at it — a Read is entry 1 of\n // the same allowlist, so the pointer is always followable. Best-effort: no doc → no pointer.\n const root = new RepoRootFinder().resolveRepoRoot(cwd);\n const docPath = writeGuardMatrixDoc(root);\n // WRITE THE AUDIT LINE HERE. This block happens BEFORE invocationLog.begin() — it has to, since a\n // stale shim invalidates everything downstream — so emitDeny's flush finds nothing pending and an\n // `S` storm left NO trace at all: the one fault most likely to block twenty consecutive tool calls\n // was the one fault the trail could not show. A decision line is the fix that costs no reordering.\n const target = payload.tool_input.command ?? payload.tool_input.file_path ?? '';\n logGuardDecision(\n root,\n new GuardDecision('committed-shim-stale', payload.tool_name, target, branchForLog(root), 'BLOCK_AI_CURE', 'L0 fault S (committed shim != renderShim)', '-', L0_FAULT_SHIM_STALE, MATRIX_L0_BLOCK),\n );\n // L0 fault S in GUARD_MATRIX.md's codebook — named as the blocking rule so the invocation line\n // says WHAT stopped the call, not merely that something did, and stamped as `fault=S` so the same\n // grep finds it here as in the sh half's `L0-shim/` stream.\n // A subagent is discriminated by `agent_id`, which BOTH harnesses populate on stdin only off the\n // main loop (main falls back to the session id / leaves it empty). Its cure differs: the hooks\n // blocking it resolve through CLAUDE_PROJECT_DIR, which names the MAIN tree.\n const inSubagent = event.agentId !== '';\n emitDeny(event, shimStaleDenyReason(installedShimRulesVersion(), shimRoot ?? '', drifted, inSubagent) + guardMatrixPointer(docPath), 'committed-shim-stale', L0_FAULT_SHIM_STALE);\n}\n\n/**\n * THE PIPELINE, from raw stdin bytes to the decision — the whole of `parse -> adapter -> runner ->\n * emit`, as ONE function returning ONE value.\n *\n * `mode` selects which tool kinds to validate; payloads outside the mode's scope pass through\n * (emitAllow). A block is a PreToolUse `permissionDecision:\"deny\"` JSON on stdout with exit 0 — see\n * agent-response.ts. Fails CLOSED on any unexpected crash (returns a deny) so a broken hook never\n * silently lets an edit through, and the reason surfaces in the agent's UI instead of being hidden on\n * a stderr+exit-2 block.\n *\n * It reads NO stdin, writes NO stdout and calls NO exit: those three couplings are ports owned by\n * HookApp (see hook-ports.ts), which is what makes the composed pipeline drivable from a test. This\n * function is what `runMain` was; it is not a second spelling of it — `runMain` is deleted, and\n * `HookApp.run()` is the only entry point.\n */\n// webpieces-disable no-function-outside-class -- the module-scope hook body itself, sibling of handleBash()/handleFileTool(); the adapter is module-scope functions by design and must stay callable from a tree too broken to build a DI container\nexport function runPipeline(raw: string, mode: HookMode): HookOutcome {\n // Captured as soon as the ENVELOPE parses so the fail-closed catch below can tell denyJson which\n // kind of call it is denying — a crash on a Bash call still gets the visible red systemMessage, a\n // crash on a file tool does not. Null (before parse / malformed input) → treated as non-Bash.\n let event: AgentHookEvent | null = null;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const payload = new AgentPayloadParser().parse(raw);\n if (!payload) { emitAllow(); }\n // The envelope shape first: it reads only `tool_name` and the identity fields, so it cannot\n // fail, and it is what the crash path needs. The full normalization below reads `tool_input`\n // and CAN fail (a malformed Codex patch envelope denies rather than being half-understood).\n event = ADAPTERS.envelope(payload);\n\n // BEFORE enforceCommittedShim(), which can itself write a BLOCK line. See LogStream for why\n // all three of session/agent/hook are needed to keep concurrent writers off one file.\n logStream.identify(new StreamIdentity(event.sessionId, event.agentId, mode));\n\n // Prefer the payload cwd (the AI's actual working dir, follows a persisted `cd`) over\n // process.cwd(); they match today, but the payload is the authoritative signal and stays\n // correct if the hook is ever invoked from a fixed dir (e.g. via $CLAUDE_PROJECT_DIR).\n const cwd = payload.cwd ?? process.cwd();\n\n // Committed-shim self-guard: blocks real work while the committed shim is stale, but keeps the\n // recovery path open (cures, reads, config edit). See enforceCommittedShim / shimStaleRecoveryDecision.\n enforceCommittedShim(payload, event, cwd, mode);\n\n event = ADAPTERS.toEvent(payload, cwd);\n\n // Read-only tools: their own fast path, which never returns when it applies.\n handleReadFastPath(event, cwd, mode);\n\n // Per-invocation guard log (the `calls/` stream): tool + command/file + live branch +\n // main-sync-status snapshot, on EVERY guards call, for later cleanup automation. Best-effort;\n // never blocks the call. (The committed shim is no longer silently healed here — a mismatch is\n // reported by the self-guard above, not rewritten out from under the AI.)\n if (mode !== 'rules') {\n invocationLog.begin(cwd, event.rawToolName, logTarget(event));\n }\n\n if (event.kind === 'Bash') {\n // No code-style rule is bash-scoped, so the rules hook ignores Bash.\n if (mode === 'rules') { emitAllow(); }\n handleBash(event, cwd, mode);\n }\n\n // File payloads run in 'rules' (code-style), 'guards' (file-scoped guards like\n // feature-branch-guard), and 'all'. The runner filters to the right category.\n handleFileTool(event, cwd, mode);\n } catch (err: unknown) {\n const error = toError(err);\n // The pipeline's own terminal control flow, not a failure: emitAllow/emitDeny threw the answer\n // out to here from wherever they were called. Treating it as a crash would turn every allow\n // into a deny, so this branch comes FIRST and returns the carried outcome verbatim.\n if (error instanceof HookTerminated) return error.outcome;\n return denyForCrash(error, event);\n }\n}\n\n// What the `calls/` audit line names as the call's target: the command for a shell call, else the first\n// file it touches. A Codex `apply_patch` touching several files names the first — the rejection log and\n// the decision log carry the rest, per file.\n// webpieces-disable no-function-outside-class -- sibling of the module-scope hook entry points in this adapter\nfunction logTarget(event: AgentHookEvent): string {\n if (event.kind === 'Bash') return event.bash === null ? '' : event.bash.command;\n return event.files.length > 0 ? event.files[0].input.filePath : '';\n}\n\n/**\n * The fail-closed boundary for anything that escaped the hook body. An escaped RuleFailError (a rule\n * that threw past the runner's per-rule catch) or an InformAiError (bad config/stdin, or a Codex patch\n * envelope this parser refuses to guess at) both carry an AI-readable message; anything else is an\n * unexpected bug. All three DENY and surface their reason, because a hook that crashed established\n * nothing and must never be read as an allow.\n *\n * It BUILDS the deny (denyOutcome) rather than throwing it (emitDeny), because it is already inside\n * the catch that the throw would land in — see HookTerminated. Same bytes either way.\n */\n// webpieces-disable no-function-outside-class -- sibling of the module-scope hook entry points in this adapter; a lone class for one terminal boundary would break the file's shape\nfunction denyForCrash(error: Error, event: AgentHookEvent | null): HookOutcome {\n if (error instanceof RuleFailError) {\n return denyOutcome(event, renderRuleFailForAi(error), 'rule-crash');\n }\n if (error instanceof InformAiError) {\n return denyOutcome(event, error.message, 'bad-config-or-stdin');\n }\n return denyOutcome(event, `[ai-hooks] hook crashed unexpectedly — failing closed: ${error.message}`, 'hook-crash');\n}\n"]}
@@ -0,0 +1,46 @@
1
+ import { HookMode } from '../core/types';
2
+ /**
3
+ * What ONE hook invocation decided, as a value instead of as two side effects.
4
+ *
5
+ * Data class per CLAUDE.md rule 1 — fields only. `stdout` is the EXACT bytes to write (a deny's JSON
6
+ * plus its trailing newline, or '' for an allow, because a silent exit 0 IS the allow) and `exitCode`
7
+ * is the last byte of the PreToolUse contract. Making the decision a value is what lets a test assert
8
+ * the composed pipeline's output without a process to inspect.
9
+ */
10
+ export declare class HookOutcome {
11
+ readonly stdout: string;
12
+ readonly exitCode: number;
13
+ constructor(stdout: string, exitCode: number);
14
+ }
15
+ /**
16
+ * The arguments one hook binary is invoked with. Today that is only WHICH category of rules to run —
17
+ * `guards` for the git/PR/branch guards, `rules` for the code-style rules — but it is a class rather
18
+ * than a bare string so a second argument is an added field and not a changed signature at every call
19
+ * site. Data class per CLAUDE.md rule 1.
20
+ */
21
+ export declare class HookArgs {
22
+ readonly mode: HookMode;
23
+ constructor(mode: HookMode);
24
+ }
25
+ /**
26
+ * THE HOOK'S TERMINAL CONTROL FLOW, as a throw.
27
+ *
28
+ * `emitAllow()` / `emitDeny()` are reached from a dozen places nested several frames deep inside the
29
+ * pipeline, and every one of them means "this invocation is over, here is its answer". They used to
30
+ * say that by writing to stdout and terminating the process on the spot, which is precisely what
31
+ * made the composed pipeline untestable — the answer never became a value anybody could look at.
32
+ *
33
+ * Throwing carries the same "nothing after this line runs" guarantee (both helpers are still typed
34
+ * `never`) while turning the answer into a HookOutcome that `HookApp` writes and exits with. The
35
+ * ORDER of observable effects is unchanged: the audit line is still flushed at the emit site, the
36
+ * bytes are still written before the exit, and the exit still happens at the same point, through the
37
+ * injected HookProcessExit port, in production.
38
+ *
39
+ * The ONE thing this shape requires: any `catch` between an emit site and HookApp must RETHROW it
40
+ * rather than treat it as a crash. There is exactly one such catch (the fail-closed boundary in
41
+ * hook-core's `runPipeline`), and it returns the carried outcome.
42
+ */
43
+ export declare class HookTerminated extends Error {
44
+ readonly outcome: HookOutcome;
45
+ constructor(outcome: HookOutcome);
46
+ }
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HookTerminated = exports.HookArgs = exports.HookOutcome = void 0;
4
+ /**
5
+ * What ONE hook invocation decided, as a value instead of as two side effects.
6
+ *
7
+ * Data class per CLAUDE.md rule 1 — fields only. `stdout` is the EXACT bytes to write (a deny's JSON
8
+ * plus its trailing newline, or '' for an allow, because a silent exit 0 IS the allow) and `exitCode`
9
+ * is the last byte of the PreToolUse contract. Making the decision a value is what lets a test assert
10
+ * the composed pipeline's output without a process to inspect.
11
+ */
12
+ class HookOutcome {
13
+ stdout;
14
+ exitCode;
15
+ constructor(stdout, exitCode) {
16
+ this.stdout = stdout;
17
+ this.exitCode = exitCode;
18
+ }
19
+ }
20
+ exports.HookOutcome = HookOutcome;
21
+ /**
22
+ * The arguments one hook binary is invoked with. Today that is only WHICH category of rules to run —
23
+ * `guards` for the git/PR/branch guards, `rules` for the code-style rules — but it is a class rather
24
+ * than a bare string so a second argument is an added field and not a changed signature at every call
25
+ * site. Data class per CLAUDE.md rule 1.
26
+ */
27
+ class HookArgs {
28
+ mode;
29
+ constructor(mode) {
30
+ this.mode = mode;
31
+ }
32
+ }
33
+ exports.HookArgs = HookArgs;
34
+ /**
35
+ * THE HOOK'S TERMINAL CONTROL FLOW, as a throw.
36
+ *
37
+ * `emitAllow()` / `emitDeny()` are reached from a dozen places nested several frames deep inside the
38
+ * pipeline, and every one of them means "this invocation is over, here is its answer". They used to
39
+ * say that by writing to stdout and terminating the process on the spot, which is precisely what
40
+ * made the composed pipeline untestable — the answer never became a value anybody could look at.
41
+ *
42
+ * Throwing carries the same "nothing after this line runs" guarantee (both helpers are still typed
43
+ * `never`) while turning the answer into a HookOutcome that `HookApp` writes and exits with. The
44
+ * ORDER of observable effects is unchanged: the audit line is still flushed at the emit site, the
45
+ * bytes are still written before the exit, and the exit still happens at the same point, through the
46
+ * injected HookProcessExit port, in production.
47
+ *
48
+ * The ONE thing this shape requires: any `catch` between an emit site and HookApp must RETHROW it
49
+ * rather than treat it as a crash. There is exactly one such catch (the fail-closed boundary in
50
+ * hook-core's `runPipeline`), and it returns the carried outcome.
51
+ */
52
+ class HookTerminated extends Error {
53
+ outcome;
54
+ constructor(outcome) {
55
+ super('hook invocation terminated');
56
+ this.outcome = outcome;
57
+ }
58
+ }
59
+ exports.HookTerminated = HookTerminated;
60
+ //# sourceMappingURL=hook-outcome.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hook-outcome.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/adapters/hook-outcome.ts"],"names":[],"mappings":";;;AAEA;;;;;;;GAOG;AACH,MAAa,WAAW;IACX,MAAM,CAAS;IACf,QAAQ,CAAS;IAE1B,YAAY,MAAc,EAAE,QAAgB;QACxC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC7B,CAAC;CACJ;AARD,kCAQC;AAED;;;;;GAKG;AACH,MAAa,QAAQ;IACR,IAAI,CAAW;IAExB,YAAY,IAAc;QACtB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACrB,CAAC;CACJ;AAND,4BAMC;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAa,cAAe,SAAQ,KAAK;IAC5B,OAAO,CAAc;IAE9B,YAAY,OAAoB;QAC5B,KAAK,CAAC,4BAA4B,CAAC,CAAC;QACpC,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IAC3B,CAAC;CACJ;AAPD,wCAOC","sourcesContent":["import { HookMode } from '../core/types';\n\n/**\n * What ONE hook invocation decided, as a value instead of as two side effects.\n *\n * Data class per CLAUDE.md rule 1 — fields only. `stdout` is the EXACT bytes to write (a deny's JSON\n * plus its trailing newline, or '' for an allow, because a silent exit 0 IS the allow) and `exitCode`\n * is the last byte of the PreToolUse contract. Making the decision a value is what lets a test assert\n * the composed pipeline's output without a process to inspect.\n */\nexport class HookOutcome {\n readonly stdout: string;\n readonly exitCode: number;\n\n constructor(stdout: string, exitCode: number) {\n this.stdout = stdout;\n this.exitCode = exitCode;\n }\n}\n\n/**\n * The arguments one hook binary is invoked with. Today that is only WHICH category of rules to run —\n * `guards` for the git/PR/branch guards, `rules` for the code-style rules — but it is a class rather\n * than a bare string so a second argument is an added field and not a changed signature at every call\n * site. Data class per CLAUDE.md rule 1.\n */\nexport class HookArgs {\n readonly mode: HookMode;\n\n constructor(mode: HookMode) {\n this.mode = mode;\n }\n}\n\n/**\n * THE HOOK'S TERMINAL CONTROL FLOW, as a throw.\n *\n * `emitAllow()` / `emitDeny()` are reached from a dozen places nested several frames deep inside the\n * pipeline, and every one of them means \"this invocation is over, here is its answer\". They used to\n * say that by writing to stdout and terminating the process on the spot, which is precisely what\n * made the composed pipeline untestable — the answer never became a value anybody could look at.\n *\n * Throwing carries the same \"nothing after this line runs\" guarantee (both helpers are still typed\n * `never`) while turning the answer into a HookOutcome that `HookApp` writes and exits with. The\n * ORDER of observable effects is unchanged: the audit line is still flushed at the emit site, the\n * bytes are still written before the exit, and the exit still happens at the same point, through the\n * injected HookProcessExit port, in production.\n *\n * The ONE thing this shape requires: any `catch` between an emit site and HookApp must RETHROW it\n * rather than treat it as a crash. There is exactly one such catch (the fail-closed boundary in\n * hook-core's `runPipeline`), and it returns the carried outcome.\n */\nexport class HookTerminated extends Error {\n readonly outcome: HookOutcome;\n\n constructor(outcome: HookOutcome) {\n super('hook invocation terminated');\n this.outcome = outcome;\n }\n}\n"]}