@webpieces/agent-workflow-rules 0.4.1023 → 0.4.1025

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webpieces/agent-workflow-rules",
3
- "version": "0.4.1023",
3
+ "version": "0.4.1025",
4
4
  "description": "Independent workflow guards, guard hook, installation and shim management for AI coding agents.",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -24,20 +24,20 @@
24
24
  "directory": "packages/tooling/agent-workflow-rules"
25
25
  },
26
26
  "dependencies": {
27
- "@webpieces/hook-runtime": "0.4.1023",
28
- "@webpieces/rules-config": "0.4.1023",
27
+ "@webpieces/hook-runtime": "0.4.1025",
28
+ "@webpieces/rules-config": "0.4.1025",
29
29
  "inversify": "7.10.4",
30
30
  "reflect-metadata": "0.2.2",
31
- "@webpieces/tooling-common": "0.4.1023",
32
- "@webpieces/repo-workflow-core": "0.4.1023",
31
+ "@webpieces/tooling-common": "0.4.1025",
32
+ "@webpieces/repo-workflow-core": "0.4.1025",
33
33
  "tslib": "2.8.1",
34
- "@webpieces/rules-sdk": "0.4.1023"
34
+ "@webpieces/rules-sdk": "0.4.1025"
35
35
  },
36
36
  "publishConfig": {
37
37
  "access": "public"
38
38
  },
39
39
  "devDependencies": {
40
- "@webpieces/tooling-testkit": "0.4.1023"
40
+ "@webpieces/tooling-testkit": "0.4.1025"
41
41
  },
42
42
  "types": "./src/index.d.ts",
43
43
  "bin": {
@@ -55,33 +55,6 @@ import type { ClaudeSettings } from './settings-shape';
55
55
  * and `wp-upgrade-shim` repairs all four. A cure that fixes three of four is worse than no cure, because
56
56
  * it reports success.
57
57
  */
58
- /**
59
- * The RETIRED L-1 hook's committed path. Named here, in the one module that must still recognise it, and
60
- * matched ONLY by isManagedCommand() so repairRegistration() can delete the stale entry. There is no
61
- * guarantee-root.ts any more — this literal is all that remains of it, deliberately.
62
- *
63
- * It is a one-way RECOGNISER, not a shim: nothing emits it, `expectedEntries()` never returns it, and a
64
- * settings file carrying it is reported STALE. Its only job is to make the retired entry findable so it
65
- * can be REMOVED.
66
- */
67
- export declare const LEGACY_GUARANTEE_ROOT_MARKER = ".claude/webpieces/guarantee-root.sh";
68
- /**
69
- * When this recogniser may be deleted, as a value rather than a comment nobody re-reads.
70
- *
71
- * A removal-only migration is still dead weight once no consumer can be carrying the old shape. The
72
- * hazard of deleting it EARLY is severe and silent — repair would stop stripping the retired entry, and
73
- * a hook registered against a deleted file exits 127, which the Claude Code hooks reference defines as a
74
- * NON-BLOCKING error, i.e. every `cd` unjudged while the cure reports success. So it gets a stated date
75
- * and a test that fails once the date passes, instead of an intention.
76
- *
77
- * `legacy-marker-expiry.spec.ts` reads this and fails after it, which is the reminder.
78
- *
79
- * MOVED from 2026-12-01 (issue #1475): the first deadline passed with no one able to confirm that every
80
- * consumer has left the release that wrote `guarantee-root.sh`, and an agent cannot see their machines.
81
- * Deleting early is the severe, silent failure described above, so the date moved and #1475 holds the
82
- * human decision.
83
- */
84
- export declare const LEGACY_MARKER_REMOVE_AFTER = "2027-03-01";
85
58
  /** One PreToolUse hook entry as webpieces registers it. Data-only → a class, per CLAUDE.md. */
86
59
  export declare class HookRegistrationEntry {
87
60
  readonly matcher: string;
@@ -250,15 +223,8 @@ export declare const CODEX_REGISTRATION: HarnessRegistration;
250
223
  */
251
224
  export declare const HARNESS_REGISTRATIONS: readonly HarnessRegistration[];
252
225
  /**
253
- * True when this PreToolUse command is one webpieces owns — in ANY spelling it has ever shipped.
254
- *
255
- * THE SINGLE MOST IMPORTANT LINE IN THIS RELEASE. `LEGACY_GUARANTEE_ROOT_MARKER` is matched here and
256
- * NOWHERE else: it is how `repairRegistration()` finds and REMOVES the retired H1 entry from a settings
257
- * file written by an older release. Drop it and the repair silently leaves a live L-1 hook registered
258
- * against a file this release deletes — exit 127, which the Claude Code hooks reference defines as a
259
- * NON-BLOCKING error, so every `cd` goes unjudged while `wp-upgrade-shim` reports success and no drift
260
- * check can name it. Removal-only, never emitted: it appears in no `expectedEntries()` result, so it is
261
- * a one-way migration and not a second accepted spelling.
226
+ * True when this PreToolUse command is one webpieces owns — any command that runs the managed shim,
227
+ * relative or absolute, so `repairRegistration()` can find a superseded spelling and rewrite it.
262
228
  */
263
229
  export declare function isManagedCommand(command: string): boolean;
264
230
  /** Every webpieces-managed entry of one settings file, flattened to matcher + command pairs. */
@@ -272,14 +238,12 @@ export declare function registeredBins(settings: ClaudeSettings): readonly strin
272
238
  /**
273
239
  * The exact set of entries THIS RELEASE expects in a settings file that registers `bins`.
274
240
  *
275
- * ONE entry per registered bin, and nothing else. There used to be a third, `guarantee-root.sh`, added
276
- * whenever the GUARDS bin was present; it is retired, and a settings file still carrying it is STALE —
277
- * `repairRegistration()` removes it via isManagedCommand()'s legacy marker.
241
+ * ONE entry per registered bin, and nothing else.
278
242
  */
279
243
  export declare function expectedEntries(harness: HarnessRegistration, bins: readonly string[]): readonly HookRegistrationEntry[];
280
244
  /**
281
245
  * True when a settings file registers webpieces hooks in a shape this release does not expect: a
282
- * RELATIVE shim command, a leftover guarantee-root entry, a stray duplicate, or a wrong matcher.
246
+ * RELATIVE shim command, a stray duplicate, or a wrong matcher.
283
247
  *
284
248
  * Compared as a SET, not a sequence: Claude Code runs all matching hooks in parallel, so array order
285
249
  * carries no meaning and reordering must not read as drift.
@@ -407,9 +371,7 @@ export declare function repairRegistrationAt(root: string): readonly SettingsRep
407
371
  *
408
372
  * There were four, then three, and there are now FOUR again — but the fourth is not the one that was
409
373
  * deleted. `GUARANTEE_ROOT_SURFACE` went with L-1 itself: an absolutely-registered shim resolves from
410
- * any cwd, so there is no launch guarantee left to police and no second .sh file to keep byte-locked. A
411
- * settings file still carrying the retired H1 entry is not its own surface — it is ordinary REGISTRATION
412
- * drift, which `registrationStaleAt()` reports and `repairRegistration()` fixes by removing it.
374
+ * any cwd, so there is no launch guarantee left to police and no second .sh file to keep byte-locked.
413
375
  *
414
376
  * The new fourth is `.codex/hooks.json`, and it is here because of what happened while it was NOT a
415
377
  * managed surface: something else wrote it, with a matcher that matched no Codex file tool and a shim
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.REVIEWER_AGENT_SURFACE = exports.ENV_SURFACE = exports.CODEX_REGISTRATION_SURFACE = exports.REGISTRATION_SURFACE = exports.SHIM_SURFACE = exports.SettingsRepair = exports.HARNESS_REGISTRATIONS = exports.CODEX_REGISTRATION = exports.CLAUDE_REGISTRATION = exports.HarnessRegistration = exports.GUARDS_BIN = exports.RULES_BIN = exports.HookRegistrationEntry = exports.LEGACY_MARKER_REMOVE_AFTER = exports.LEGACY_GUARANTEE_ROOT_MARKER = void 0;
3
+ exports.REVIEWER_AGENT_SURFACE = exports.ENV_SURFACE = exports.CODEX_REGISTRATION_SURFACE = exports.REGISTRATION_SURFACE = exports.SHIM_SURFACE = exports.SettingsRepair = exports.HARNESS_REGISTRATIONS = exports.CODEX_REGISTRATION = exports.CLAUDE_REGISTRATION = exports.HarnessRegistration = exports.GUARDS_BIN = exports.RULES_BIN = exports.HookRegistrationEntry = void 0;
4
4
  exports.isManagedCommand = isManagedCommand;
5
5
  exports.managedEntries = managedEntries;
6
6
  exports.registeredBins = registeredBins;
@@ -81,33 +81,6 @@ const managed_env_1 = require("./managed-env");
81
81
  * and `wp-upgrade-shim` repairs all four. A cure that fixes three of four is worse than no cure, because
82
82
  * it reports success.
83
83
  */
84
- /**
85
- * The RETIRED L-1 hook's committed path. Named here, in the one module that must still recognise it, and
86
- * matched ONLY by isManagedCommand() so repairRegistration() can delete the stale entry. There is no
87
- * guarantee-root.ts any more — this literal is all that remains of it, deliberately.
88
- *
89
- * It is a one-way RECOGNISER, not a shim: nothing emits it, `expectedEntries()` never returns it, and a
90
- * settings file carrying it is reported STALE. Its only job is to make the retired entry findable so it
91
- * can be REMOVED.
92
- */
93
- exports.LEGACY_GUARANTEE_ROOT_MARKER = '.claude/webpieces/guarantee-root.sh';
94
- /**
95
- * When this recogniser may be deleted, as a value rather than a comment nobody re-reads.
96
- *
97
- * A removal-only migration is still dead weight once no consumer can be carrying the old shape. The
98
- * hazard of deleting it EARLY is severe and silent — repair would stop stripping the retired entry, and
99
- * a hook registered against a deleted file exits 127, which the Claude Code hooks reference defines as a
100
- * NON-BLOCKING error, i.e. every `cd` unjudged while the cure reports success. So it gets a stated date
101
- * and a test that fails once the date passes, instead of an intention.
102
- *
103
- * `legacy-marker-expiry.spec.ts` reads this and fails after it, which is the reminder.
104
- *
105
- * MOVED from 2026-12-01 (issue #1475): the first deadline passed with no one able to confirm that every
106
- * consumer has left the release that wrote `guarantee-root.sh`, and an agent cannot see their machines.
107
- * Deleting early is the severe, silent failure described above, so the date moved and #1475 holds the
108
- * human decision.
109
- */
110
- exports.LEGACY_MARKER_REMOVE_AFTER = '2027-03-01';
111
84
  /** One PreToolUse hook entry as webpieces registers it. Data-only → a class, per CLAUDE.md. */
112
85
  class HookRegistrationEntry {
113
86
  matcher;
@@ -274,19 +247,12 @@ exports.CODEX_REGISTRATION = new HarnessRegistration('codex', 'Codex', 'apply_pa
274
247
  */
275
248
  exports.HARNESS_REGISTRATIONS = [exports.CLAUDE_REGISTRATION, exports.CODEX_REGISTRATION];
276
249
  /**
277
- * True when this PreToolUse command is one webpieces owns — in ANY spelling it has ever shipped.
278
- *
279
- * THE SINGLE MOST IMPORTANT LINE IN THIS RELEASE. `LEGACY_GUARANTEE_ROOT_MARKER` is matched here and
280
- * NOWHERE else: it is how `repairRegistration()` finds and REMOVES the retired H1 entry from a settings
281
- * file written by an older release. Drop it and the repair silently leaves a live L-1 hook registered
282
- * against a file this release deletes — exit 127, which the Claude Code hooks reference defines as a
283
- * NON-BLOCKING error, so every `cd` goes unjudged while `wp-upgrade-shim` reports success and no drift
284
- * check can name it. Removal-only, never emitted: it appears in no `expectedEntries()` result, so it is
285
- * a one-way migration and not a second accepted spelling.
250
+ * True when this PreToolUse command is one webpieces owns — any command that runs the managed shim,
251
+ * relative or absolute, so `repairRegistration()` can find a superseded spelling and rewrite it.
286
252
  */
287
253
  // webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above
288
254
  function isManagedCommand(command) {
289
- return command.includes(shim_1.SHIM_MARKER) || command.includes(exports.LEGACY_GUARANTEE_ROOT_MARKER);
255
+ return command.includes(shim_1.SHIM_MARKER);
290
256
  }
291
257
  // webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above
292
258
  function preToolUse(settings) {
@@ -317,9 +283,7 @@ function registeredBins(settings) {
317
283
  /**
318
284
  * The exact set of entries THIS RELEASE expects in a settings file that registers `bins`.
319
285
  *
320
- * ONE entry per registered bin, and nothing else. There used to be a third, `guarantee-root.sh`, added
321
- * whenever the GUARDS bin was present; it is retired, and a settings file still carrying it is STALE —
322
- * `repairRegistration()` removes it via isManagedCommand()'s legacy marker.
286
+ * ONE entry per registered bin, and nothing else.
323
287
  */
324
288
  // webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as HarnessRegistration's siblings
325
289
  function expectedEntries(harness, bins) {
@@ -327,7 +291,7 @@ function expectedEntries(harness, bins) {
327
291
  }
328
292
  /**
329
293
  * True when a settings file registers webpieces hooks in a shape this release does not expect: a
330
- * RELATIVE shim command, a leftover guarantee-root entry, a stray duplicate, or a wrong matcher.
294
+ * RELATIVE shim command, a stray duplicate, or a wrong matcher.
331
295
  *
332
296
  * Compared as a SET, not a sequence: Claude Code runs all matching hooks in parallel, so array order
333
297
  * carries no meaning and reordering must not read as drift.
@@ -595,9 +559,9 @@ function repairRegistrationAt(root) {
595
559
  const neededRegistration = registrationStale(harness, settings);
596
560
  const neededEnv = harness.managesEnv && envStale(settings);
597
561
  const changedManaged = repairRegistration(harness, settings);
598
- // AFTER the managed repair, never before: repairRegistration() removes the retired
599
- // guarantee-root entry and rewrites the two managed commands, so by the time the neighbour
600
- // pass runs there is nothing webpieces-owned left for it to look at. Gated on
562
+ // AFTER the managed repair, never before: repairRegistration() rewrites the two managed
563
+ // commands, so by the time the neighbour pass runs there is nothing webpieces-owned left for
564
+ // it to look at. Gated on
601
565
  // registeredBins() for the same reason every other judgement here is — a settings file that
602
566
  // registers no webpieces hooks is not a webpieces install, and rewriting somebody's
603
567
  // unrelated hook lines in it would be webpieces editing a file it was never given.
@@ -615,9 +579,7 @@ function repairRegistrationAt(root) {
615
579
  *
616
580
  * There were four, then three, and there are now FOUR again — but the fourth is not the one that was
617
581
  * deleted. `GUARANTEE_ROOT_SURFACE` went with L-1 itself: an absolutely-registered shim resolves from
618
- * any cwd, so there is no launch guarantee left to police and no second .sh file to keep byte-locked. A
619
- * settings file still carrying the retired H1 entry is not its own surface — it is ordinary REGISTRATION
620
- * drift, which `registrationStaleAt()` reports and `repairRegistration()` fixes by removing it.
582
+ * any cwd, so there is no launch guarantee left to police and no second .sh file to keep byte-locked.
621
583
  *
622
584
  * The new fourth is `.codex/hooks.json`, and it is here because of what happened while it was NOT a
623
585
  * managed surface: something else wrote it, with a matcher that matched no Codex file tool and a shim
@@ -1 +1 @@
1
- {"version":3,"file":"hook-registration.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/bin/hook-registration.ts"],"names":[],"mappings":";;;AA2RA,4CAEC;AASD,wCAQC;AAQD,wCAGC;AAUD,0CAEC;AAUD,8CAOC;AAID,gDAYC;AAID,oCAIC;AA0BD,4BAIC;AAaD,0CAOC;AAkBD,gDAcC;AAGD,oCAWC;AAGD,sCAGC;AAYD,sDAaC;AAcD,kDAUC;AAUD,gCAUC;AAkCD,oDAsBC;AAmCD,kDAeC;;AAnoBD,+CAAyB;AACzB,mDAA6B;AAE7B,iEAA6D;AAE7D,iCAAyD;AACzD,qDAA6E;AAC7E,uDAAwG;AAExG,+CAAqE;AAErE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsDG;AAEH;;;;;;;;GAQG;AACU,QAAA,4BAA4B,GAA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CAAC;IACrF,CAAC;IACD,IAAI,UAAU,CAAC,IAAI,CAAC;QAAE,OAAO,CAAC,IAAI,CAAC,mBAAW,CAAC,CAAC;IAChD,IAAI,IAAA,mCAAkB,EAAC,IAAI,CAAC;QAAE,OAAO,CAAC,IAAI,CAAC,8BAAsB,CAAC,CAAC;IACnE,OAAO,OAAO,CAAC;AACnB,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\n\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { AiType } from '@webpieces/hook-runtime';\nimport { SHIM_MARKER, committedShimStale } from './shim';\nimport { REVIEWER_AGENT_MARKER, reviewerAgentStale } from './reviewer-agent';\nimport { NEIGHBOUR_SURFACE_SUFFIX, anchorNeighbourHooks, neighbourHooksStale } from './neighbour-hooks';\nimport type { ClaudeSettings, HookCommand, HookEntry } from './settings-shape';\nimport { BASH_CWD_ENV_KEY, BASH_CWD_ENV_VALUE } from './managed-env';\n\n/**\n * THE INSTALLED HOOK SURFACE — two hooks per harness, all ABSOLUTE, and the ONE place their spelling is\n * defined. See `HarnessRegistration` below, which is what makes \"per harness\" data rather than four\n * module constants that were only ever true of Claude Code.\n *\n * ─── ONE GOVERNOR: the MAIN tree judges every tree ─────────────────────────────────────────────────\n *\n * Claude Code — .claude/settings.json\n * H1 sh \"$CLAUDE_PROJECT_DIR/.claude/webpieces/ai-hook.sh\" wp-ai-guards-hook Write|…|Bash|Read\n * H2 sh \"$CLAUDE_PROJECT_DIR/.claude/webpieces/ai-hook.sh\" wp-ai-rules-hook Write|Edit|MultiEdit\n * Codex — .codex/hooks.json (the SAME `hooks.PreToolUse` JSON shape, measured)\n * H1 sh \"$PWD/.claude/webpieces/ai-hook.sh\" wp-ai-guards-hook Bash|apply_patch\n * H2 sh \"$PWD/.claude/webpieces/ai-hook.sh\" wp-ai-rules-hook apply_patch\n *\n * ONE shim file serves all four: `.claude/` there is a path, not a claim about who is calling.\n *\n * This REPLACES a three-hook form in which these two were RELATIVE (`sh \".claude/webpieces/ai-hook.sh\"`)\n * and a third hook, L-1 `guarantee-root.sh`, existed solely to guarantee that relative path resolved.\n *\n * ─── Why the relative experiment was reversed ──────────────────────────────────────────────────────\n * Relative registration was adopted so each git tree would be governed by \"its own release, binary and\n * pin\". MEASURED 2026-08-10: it never delivered that. A linked worktree has NO `node_modules`, so\n * ai-hook.sh's upward walk executes the PRIMARY's binary — `readlink -f` resolved a worktree agent's bin\n * to `<primary>/node_modules/@webpieces/agent-workflow-rules`. A worktree ran its own SCRIPT and its own\n * CONFIG; it never ran its own release. Governance was already the primary's, in every tree, the whole\n * time.\n *\n * The price of that fiction was an entire guard layer. A relative path only resolves at a tree root, and\n * a hook that cannot resolve exits 127 — per the hooks reference a NON-BLOCKING error, i.e. a SILENT\n * UNGUARDED ALLOW. So L-1 had to deny every `cd` into a project subdirectory. That denial produced the\n * force-to-root bug class, the reaped-worktree `cd` prescription, and a measured hard deadlock: L-1 told\n * a worktree-isolated agent to `cd` to the primary clone, which the harness refuses for an isolated\n * agent, leaving it unable to stay or to follow the cure.\n *\n * An absolute path resolves from ANY cwd. So the launch guarantee is structural, L-1 has no job left and\n * is deleted, and `cd` into a subdirectory is simply allowed. What used to be true only by policing the\n * shell is now true by construction.\n *\n * ─── What replaces the property that was lost ──────────────────────────────────────────────────────\n * Nothing is lost that was ever delivered — but the case relative registration WANTED to handle (a tree\n * that genuinely needs a different @webpieces) is now DETECTED instead of silently mis-governed:\n * `VersionSyncGuard` (L1 row 8) blocks when a worktree's pin disagrees with the main tree's, and\n * prescribes either aligning the pins (same git hash → same tracked pin → install in each tree that has\n * a node_modules) or using a separate CLONE, which — unlike a worktree — gets its own GOVERNANCE. Note\n * what that does NOT say: a worktree may perfectly well have its own node_modules, and usually does the\n * moment anything installs in it. What it may not have is a DIFFERENT @webpieces version.\n *\n * ─── Why the registration is a DRIFT SURFACE, not just an install step ─────────────────────────────\n * Nothing used to validate `.claude/settings.json` at all, so a settings file left on a superseded form\n * silently changed who governs. The installed surface is FOUR things (ai-hook.sh, the registration, the\n * managed `env` entry — see managed-env.ts — and the ANCHORING of the NEIGHBOUR hook commands the\n * consumer registers beside ours, see neighbour-hooks.ts), all four are compared against this release,\n * and `wp-upgrade-shim` repairs all four. A cure that fixes three of four is worse than no cure, because\n * it reports success.\n */\n\n/**\n * The RETIRED L-1 hook's committed path. Named here, in the one module that must still recognise it, and\n * matched ONLY by isManagedCommand() so repairRegistration() can delete the stale entry. There is no\n * guarantee-root.ts any more — this literal is all that remains of it, deliberately.\n *\n * It is a one-way RECOGNISER, not a shim: nothing emits it, `expectedEntries()` never returns it, and a\n * settings file carrying it is reported STALE. Its only job is to make the retired entry findable so it\n * can be REMOVED.\n */\nexport const LEGACY_GUARANTEE_ROOT_MARKER = '.claude/webpieces/guarantee-root.sh';\n\n/**\n * When this recogniser may be deleted, as a value rather than a comment nobody re-reads.\n *\n * A removal-only migration is still dead weight once no consumer can be carrying the old shape. The\n * hazard of deleting it EARLY is severe and silent — repair would stop stripping the retired entry, and\n * a hook registered against a deleted file exits 127, which the Claude Code hooks reference defines as a\n * NON-BLOCKING error, i.e. every `cd` unjudged while the cure reports success. So it gets a stated date\n * and a test that fails once the date passes, instead of an intention.\n *\n * `legacy-marker-expiry.spec.ts` reads this and fails after it, which is the reminder.\n *\n * MOVED from 2026-12-01 (issue #1475): the first deadline passed with no one able to confirm that every\n * consumer has left the release that wrote `guarantee-root.sh`, and an agent cannot see their machines.\n * Deleting early is the severe, silent failure described above, so the date moved and #1475 holds the\n * human decision.\n */\nexport const LEGACY_MARKER_REMOVE_AFTER = '2027-03-01';\n\n/** One PreToolUse hook entry as webpieces registers it. Data-only → a class, per CLAUDE.md. */\nexport class HookRegistrationEntry {\n constructor(\n readonly matcher: string,\n readonly command: string,\n ) {}\n\n sameAs(other: HookRegistrationEntry): boolean {\n return this.matcher === other.matcher && this.command === other.command;\n }\n}\n\n/**\n * THE SETTINGS-FILE SHAPE lives in `./settings-shape`, a LEAF module, and is imported from THERE by\n * everything that needs it — this module included. It is deliberately NOT re-exported here: a second\n * import path for one type is the \"two spellings of one thing\" shim the compatibility policy rejects,\n * and it would keep advertising `hook-registration` as a source of the shape, which is precisely the\n * edge that has to stay broken (`neighbour-hooks.ts` needs the shape, this module imports the repairs\n * FROM it, and `validate-no-file-import-cycles` counts even a type-only edge back as a cycle).\n */\n\nexport const RULES_BIN = 'wp-ai-rules-hook';\nexport const GUARDS_BIN = 'wp-ai-guards-hook';\n\n/**\n * ONE HARNESS'S registration surface — where its hooks live, what they match, and how they name the\n * shim. Data-only → a class, per CLAUDE.md.\n *\n * ─── Why this exists ──────────────────────────────────────────────────────────────────────────────\n * The matchers and the shim command used to be four module constants written for Claude Code alone.\n * Applied to Codex they are wrong in both halves, and the way they are wrong is SILENT:\n *\n * - MATCHER. Codex's file-editing tool is `apply_patch` (MEASURED, codex-cli 0.151.0). A matcher of\n * `Write|Edit|MultiEdit` matches it never, so every file rule is unreachable while the settings file\n * looks perfectly installed. Its shell tool IS called `Bash` — Codex reuses Claude's name — which is\n * the trap: half the matcher works, so the hooks appear to be running.\n * - ANCHOR. `$CLAUDE_PROJECT_DIR` does not exist in a Codex hook's environment (measured: 46 vars, no\n * such key), so the command expands to `sh \"/.claude/webpieces/ai-hook.sh\"`, which dies — and per the\n * hooks protocol a non-2 non-zero exit is a NON-BLOCKING error, i.e. a silent unguarded allow.\n *\n * Both halves of that were live in real repos, written by a Codex Desktop sync that transliterated the\n * Claude setup. Making the registration per-harness DATA is what stops a future harness inheriting a\n * matcher that was never true for it.\n *\n * ─── ONE SHIM, both harnesses ─────────────────────────────────────────────────────────────────────\n * `SHIM_MARKER` is shared deliberately: `.claude/webpieces/ai-hook.sh` is the single fail-closed entry\n * point, and moving or duplicating it would double the L0 allowlist regexes, the drift surfaces and the\n * cures. The `.claude/` prefix is a path, not a claim about which agent is calling.\n */\nexport class HarnessRegistration {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n readonly aiType: AiType,\n /** How the installer and the drift report name this harness to a human. */\n readonly label: string,\n /** Which tool names the RULES hook (code-style, file-scoped) must see. */\n readonly rulesMatcher: string,\n /**\n * Which tool names the GUARDS hook must see. Wider than the rules matcher by the shell tool and,\n * for Claude Code, by `Read` — Read carries no guard, but the guards hook owns the\n * per-invocation audit log, so matching it records every file the AI opens (log-and-allow fast\n * path in hook-core.ts; a Read is never blocked). Codex has no Read tool at all: a read arrives\n * as `Bash` running a pager, which the shell matcher already covers and read-parity synthesizes.\n */\n readonly guardsMatcher: string,\n /** The settings files this harness's hooks can be installed into, relative to the repo root. */\n readonly settingsFiles: readonly string[],\n /**\n * THE PREFIX THE SHIM PATH IS ANCHORED ON, and the reason each harness needs its own.\n *\n * **BYTE-STABILITY IS A HARD CONSTRAINT ON THE CODEX VALUE.** Codex trusts a hook entry\n * TOFU — `~/.codex/config.toml` records a `trusted_hash` per entry — so ANY change to these bytes\n * invalidates that trust and re-prompts the human, whose third option is `Continue without\n * trusting (hooks won't run)`: one keystroke to a silently unguarded session. Changing this\n * string is therefore never a cosmetic edit. The hash is NOT reproducible from outside Codex\n * (16 encodings tried against a file we authored), so the installer can never repair trust for\n * itself — see ./codex-trust.ts, which REPORTS and never writes.\n */\n readonly shimAnchor: string,\n /**\n * True when this harness's settings file also carries the managed `env` block. Claude Code's\n * settings `env` is inherited by every subagent, which is what makes it the right home for the\n * Bash-cwd pin (see managed-env.ts). Codex has no equivalent surface — and needs none: its cwd\n * is MEASURED not to drift at all (`cd x && pwd` prints x, the next call is back at the repo\n * root, for the coordinator and for subagents alike).\n */\n readonly managesEnv: boolean,\n /** What `managedSurfaceDrift()` calls this harness's registration when it has moved. */\n readonly registrationSurface: string,\n ) {}\n\n /** Which matcher one guard bin registers under. */\n matcherFor(bin: string): string {\n return bin === RULES_BIN ? this.rulesMatcher : this.guardsMatcher;\n }\n\n /**\n * The guard-hook command — `sh \"<anchor>/.claude/webpieces/ai-hook.sh\" <bin>`.\n *\n * ABSOLUTE, in both harnesses. Claude's anchor replaced a RELATIVE spelling and that reversal is\n * documented at length in this file's header: relative resolves only at a tree root, a hook that\n * cannot resolve exits 127, and per the hooks reference that is a NON-BLOCKING error — a silent\n * unguarded allow. It also cost an entire guard layer (L-1) whose only job was to police the `cd`\n * that made the relative path resolvable.\n *\n * Invoked via `sh <file>` rather than executed directly so a missing executable bit on the\n * checked-in shim (fresh clone, a filesystem that drops the bit, git core.fileMode quirks) can never\n * break the hook with a raw `Permission denied` on every tool call. Quoted to survive spaces.\n */\n shimCommand(bin: string): string {\n return `sh \"${this.shimAnchor}/${SHIM_MARKER}\" ${bin}`;\n }\n\n /** The registration entry for one guard bin under this harness. */\n entryFor(bin: string): HookRegistrationEntry {\n return new HookRegistrationEntry(this.matcherFor(bin), this.shimCommand(bin));\n }\n\n /** This harness's settings files under one repo root, absolute. */\n settingsPaths(projectRoot: string): readonly string[] {\n return this.settingsFiles.map((file: string): string => path.join(projectRoot, ...file.split('/')));\n }\n\n /**\n * What `managedSurfaceDrift()` calls this harness's NEIGHBOUR hook commands — the entries a CONSUMER\n * repo registers in the same file — when one of them still carries a repo-RELATIVE entry path.\n *\n * DERIVED rather than a constructor field, unlike `registrationSurface` beside it, because there is\n * nothing here a harness could sensibly disagree about: it is the same file, said a second way. A\n * constructor param would be a second place to keep in step for no decision.\n */\n get neighbourSurface(): string {\n return `${this.settingsFiles[0]} ${NEIGHBOUR_SURFACE_SUFFIX}`;\n }\n}\n\nexport const CLAUDE_REGISTRATION = new HarnessRegistration(\n 'claude-code', 'Claude Code',\n 'Write|Edit|MultiEdit',\n 'Write|Edit|MultiEdit|Bash|Read',\n ['.claude/settings.json', '.claude/settings.local.json'],\n '$CLAUDE_PROJECT_DIR',\n true,\n '.claude/settings.json hook registration',\n);\n\n/**\n * Codex's registration, every value of it MEASURED against codex-cli 0.151.0 rather than assumed.\n *\n * `$PWD` is the anchor because there is no project-dir variable to use and none is needed: the payload\n * `cwd` and the hook process's own `PWD` are both the repo root on EVERY call — for the coordinator and\n * for subagents — and a `cd` inside one command never survives into the next. That was measured, not\n * hoped for, and it is the same effect Claude Code gets from the managed\n * `CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR` env entry. See `shimAnchor` for why these exact bytes are\n * not free to change.\n */\nexport const CODEX_REGISTRATION = new HarnessRegistration(\n 'codex', 'Codex',\n 'apply_patch',\n 'Bash|apply_patch',\n ['.codex/hooks.json'],\n '$PWD',\n false,\n '.codex/hooks.json hook registration',\n);\n\n/**\n * Every harness webpieces arms, in installer order.\n *\n * The drift check, the repair and the installer all iterate THIS, so a harness cannot be armed by the\n * installer and then left unvalidated — which is exactly the state `.codex/hooks.json` was in before it\n * was a managed surface: written by something else, silently wrong, and invisible to every check.\n */\nexport const HARNESS_REGISTRATIONS: readonly HarnessRegistration[] = [CLAUDE_REGISTRATION, CODEX_REGISTRATION];\n\n/**\n * True when this PreToolUse command is one webpieces owns — in ANY spelling it has ever shipped.\n *\n * THE SINGLE MOST IMPORTANT LINE IN THIS RELEASE. `LEGACY_GUARANTEE_ROOT_MARKER` is matched here and\n * NOWHERE else: it is how `repairRegistration()` finds and REMOVES the retired H1 entry from a settings\n * file written by an older release. Drop it and the repair silently leaves a live L-1 hook registered\n * against a file this release deletes — exit 127, which the Claude Code hooks reference defines as a\n * NON-BLOCKING error, so every `cd` goes unjudged while `wp-upgrade-shim` reports success and no drift\n * check can name it. Removal-only, never emitted: it appears in no `expectedEntries()` result, so it is\n * a one-way migration and not a second accepted spelling.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function isManagedCommand(command: string): boolean {\n return command.includes(SHIM_MARKER) || command.includes(LEGACY_GUARANTEE_ROOT_MARKER);\n}\n\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nfunction preToolUse(settings: ClaudeSettings): readonly HookEntry[] {\n return settings.hooks?.PreToolUse ?? [];\n}\n\n/** Every webpieces-managed entry of one settings file, flattened to matcher + command pairs. */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function managedEntries(settings: ClaudeSettings): readonly HookRegistrationEntry[] {\n const found: HookRegistrationEntry[] = [];\n for (const entry of preToolUse(settings)) {\n for (const hook of entry.hooks) {\n if (isManagedCommand(hook.command)) found.push(new HookRegistrationEntry(entry.matcher, hook.command));\n }\n }\n return found;\n}\n\n/**\n * Which guard bins this settings file registers, in installer order. A file registering NEITHER is not\n * a project (relative) install and is therefore never judged — a global/absolute install names the bin\n * path directly and carries no shim marker at all.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function registeredBins(settings: ClaudeSettings): readonly string[] {\n const commands = managedEntries(settings).map((e: HookRegistrationEntry): string => e.command);\n return [GUARDS_BIN, RULES_BIN].filter((bin: string): boolean => commands.some((c: string): boolean => c.includes(bin)));\n}\n\n/**\n * The exact set of entries THIS RELEASE expects in a settings file that registers `bins`.\n *\n * ONE entry per registered bin, and nothing else. There used to be a third, `guarantee-root.sh`, added\n * whenever the GUARDS bin was present; it is retired, and a settings file still carrying it is STALE —\n * `repairRegistration()` removes it via isManagedCommand()'s legacy marker.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as HarnessRegistration's siblings\nexport function expectedEntries(harness: HarnessRegistration, bins: readonly string[]): readonly HookRegistrationEntry[] {\n return bins.map((bin: string): HookRegistrationEntry => harness.entryFor(bin));\n}\n\n/**\n * True when a settings file registers webpieces hooks in a shape this release does not expect: a\n * RELATIVE shim command, a leftover guarantee-root entry, a stray duplicate, or a wrong matcher.\n *\n * Compared as a SET, not a sequence: Claude Code runs all matching hooks in parallel, so array order\n * carries no meaning and reordering must not read as drift.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function registrationStale(harness: HarnessRegistration, settings: ClaudeSettings): boolean {\n const bins = registeredBins(settings);\n if (bins.length === 0) return false;\n const have = managedEntries(settings);\n const want = expectedEntries(harness, bins);\n if (have.length !== want.length) return true;\n return want.some((w: HookRegistrationEntry): boolean => !have.some((h: HookRegistrationEntry): boolean => h.sameAs(w)));\n}\n\n/** Drop every webpieces-managed PreToolUse command; returns true if anything was removed. */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function dropManagedEntries(settings: ClaudeSettings): boolean {\n const entries = settings.hooks?.PreToolUse;\n if (!entries) return false;\n let changed = false;\n const kept: HookEntry[] = [];\n for (const entry of entries) {\n const hooks = entry.hooks.filter((h: HookCommand): boolean => !isManagedCommand(h.command));\n if (hooks.length !== entry.hooks.length) changed = true;\n if (hooks.length > 0) kept.push({ matcher: entry.matcher, hooks });\n }\n if (changed) settings.hooks!.PreToolUse = kept;\n return changed;\n}\n\n/** Append one PreToolUse entry. */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function addHookEntry(settings: ClaudeSettings, entry: HookRegistrationEntry): void {\n if (!settings.hooks) settings.hooks = {};\n if (!Array.isArray(settings.hooks.PreToolUse)) settings.hooks.PreToolUse = [];\n settings.hooks.PreToolUse.push({ matcher: entry.matcher, hooks: [{ type: 'command', command: entry.command }] });\n}\n\n/** The settings `env` block, or null when the file carries none (or carries junk in its place). */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nfunction settingsEnv(settings: ClaudeSettings): Record<string, string> | null {\n // webpieces-disable no-any-unknown -- settings.json is opaque consumer JSON; `env` is only typed after this check\n const env: unknown = settings.env;\n if (typeof env !== 'object' || env === null || Array.isArray(env)) return null;\n return env as Record<string, string>;\n}\n\n/**\n * True when a settings file that registers webpieces hooks is missing the managed `env` entry, or\n * carries any value other than the one required one.\n *\n * Gated on `registeredBins()` for the SAME reason `registrationStale()` is: a settings file that\n * registers no webpieces hooks is not a project install and is never judged — a global install names\n * the bin path directly and carries no shim marker at all, so there is nothing here to keep in step.\n *\n * NOTE what this entry is for NOW. It was originally justified by keeping the then-RELATIVE hook path\n * resolvable; that job is retired, because both hooks are absolute and resolve from any cwd. It is kept\n * for VERDICT STABILITY — a guard's answer must depend on the command, not on where an earlier `cd` left\n * the shell — and because settings `env` is inherited, every subagent shares that cwd and therefore that\n * verdict. See managed-env.ts, which states this at length.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function envStale(settings: ClaudeSettings): boolean {\n if (registeredBins(settings).length === 0) return false;\n const env = settingsEnv(settings);\n return env === null || env[BASH_CWD_ENV_KEY] !== BASH_CWD_ENV_VALUE;\n}\n\n/**\n * Set the managed `env` entry IN PLACE, whatever was there before. Returns true when it changed.\n *\n * A user-set `\"0\"` is BROUGHT TO `\"1\"`, not honoured: this is a managed surface, and \"webpieces sets it\n * unless you disagreed\" would be a second, invisible spelling of the decision. Turning it off means\n * uninstalling the hooks, exactly as it does for every other managed thing.\n *\n * UNGATED on purpose — the installer calls it for the file it is writing hooks into, and the gate lives\n * at the caller (repairRegistration / applyHook), so a file with no webpieces hooks is never touched.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function applyManagedEnv(settings: ClaudeSettings): boolean {\n const existing = settingsEnv(settings);\n if (existing !== null && existing[BASH_CWD_ENV_KEY] === BASH_CWD_ENV_VALUE) return false;\n const env = existing ?? {};\n env[BASH_CWD_ENV_KEY] = BASH_CWD_ENV_VALUE;\n settings.env = env;\n return true;\n}\n\n/**\n * Bring one settings object to the two-hook ABSOLUTE form AND the managed `env` entry IN PLACE. Returns\n * true when it changed anything.\n *\n * REMOVE-then-ADD for the hooks, never add-beside: two spellings of one registration is exactly the\n * compatibility shim the backwards-compat reviewer rejects, and leaving a RELATIVE entry beside the\n * absolute one would run two shims per call — the\n * straddle this whole change exists to delete.\n *\n * THE TWO REPAIRS ARE EVALUATED INDEPENDENTLY, and that is load-bearing rather than tidy: this used to\n * early-return on `!registrationStale(settings)`, so a repo whose hooks are already current but whose\n * `env` entry is missing — the state EVERY existing consumer is in the moment this release lands — would\n * have been reported as drifted by fault S and then left unrepaired by its own prescribed cure. A cure\n * that skips half the surface is the failure mode `upgrade-shim.ts`'s header exists to prevent.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function repairRegistration(harness: HarnessRegistration, settings: ClaudeSettings): boolean {\n const bins = registeredBins(settings);\n if (bins.length === 0) return false;\n let changed = false;\n if (registrationStale(harness, settings)) {\n dropManagedEntries(settings);\n for (const entry of expectedEntries(harness, bins)) addHookEntry(settings, entry);\n changed = true;\n }\n // Only where the harness HAS that surface. Codex's hooks.json has no `env` block to manage, and\n // inventing one there would write a key Codex does not read — a managed surface nothing consumes is\n // a surface that can drift with no consequence and no way to notice.\n if (harness.managesEnv && applyManagedEnv(settings)) changed = true;\n return changed;\n}\n\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function readSettings(settingsPath: string): ClaudeSettings {\n if (!fs.existsSync(settingsPath)) return {};\n const raw = fs.readFileSync(settingsPath, 'utf8');\n if (raw.trim() === '') return {};\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return JSON.parse(raw) as ClaudeSettings;\n } catch (err: unknown) {\n const error = toError(err);\n throw new Error(`${settingsPath} has invalid JSON — fix it, then retry: ${error.message}`, { cause: error });\n }\n}\n\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function writeSettings(settingsPath: string, settings: ClaudeSettings): void {\n fs.mkdirSync(path.dirname(settingsPath), { recursive: true });\n fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 4) + '\\n');\n}\n\n/**\n * True when any settings file ONE HARNESS owns under `root` carries a NEIGHBOUR hook — one the consumer\n * repo wrote — whose entry path is repo-RELATIVE and would therefore fail to resolve from any cwd but\n * the root. See neighbour-hooks.ts for the measured failure and why webpieces owns the repair.\n *\n * Judged ONLY where the file registers webpieces hooks, exactly like `registrationStaleAt` below: a\n * settings file with no webpieces hooks in it is not a webpieces install, and webpieces rewriting\n * somebody's unrelated hook lines there would be editing a file it was never given.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as HarnessRegistration's siblings\nexport function neighbourHooksStaleAt(harness: HarnessRegistration, root: string | null): boolean {\n if (root === null) return false;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return harness.settingsPaths(root).some((p: string): boolean => {\n const settings = readSettings(p);\n return registeredBins(settings).length > 0 && neighbourHooksStale(harness.shimAnchor, settings, root);\n });\n } catch (err: unknown) {\n const error = toError(err);\n void error; // best-effort: unreadable/invalid settings counts as \"not stale\" so it never wedges a call\n return false;\n }\n}\n\n/**\n * True when any settings file ONE HARNESS owns under `root` carries a stale registration.\n *\n * Per harness, not per repo, so the drift report can NAME which one moved — `.claude/settings.json` and\n * `.codex/hooks.json` have different cures, and a fault that says only \"the registration is stale\" sends\n * the reader to the wrong file half the time.\n *\n * A file that does not exist, or exists and registers no webpieces hooks, is never judged (see\n * `registrationStale`). That is what keeps a repo which has never armed Codex from suddenly faulting on\n * a `.codex/hooks.json` it does not have.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as HarnessRegistration's siblings\nexport function registrationStaleAt(harness: HarnessRegistration, root: string | null): boolean {\n if (root === null) return false;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return harness.settingsPaths(root).some((p: string): boolean => registrationStale(harness, readSettings(p)));\n } catch (err: unknown) {\n const error = toError(err);\n void error; // best-effort: unreadable/invalid settings counts as \"not stale\" so it never wedges a call\n return false;\n }\n}\n\n/**\n * True when either Claude project settings file under `root` is missing the managed `env` entry.\n *\n * CLAUDE-ONLY by construction, and stated as such rather than looped over the harnesses: `env` is a\n * Claude Code settings surface, Codex has no equivalent, and Codex's cwd is measured not to drift, which\n * is the whole thing the entry is for. See HarnessRegistration.managesEnv.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as HarnessRegistration's siblings\nexport function envStaleAt(root: string | null): boolean {\n if (root === null) return false;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return CLAUDE_REGISTRATION.settingsPaths(root).some((p: string): boolean => envStale(readSettings(p)));\n } catch (err: unknown) {\n const error = toError(err);\n void error; // best-effort: unreadable/invalid settings counts as \"not stale\" so it never wedges a call\n return false;\n }\n}\n\n/**\n * WHAT was rewritten in ONE settings file. Data-only → a class, per CLAUDE.md.\n *\n * Two independent flags rather than one path, because the cure has to be able to SAY which repair it\n * made: \"rewrote the hook registration\" printed for a file whose registration was already current and\n * whose `env` entry was the only thing missing is a cure lying about its own work.\n */\nexport class SettingsRepair {\n constructor(\n readonly settingsPath: string,\n readonly registration: boolean,\n readonly env: boolean,\n /**\n * The NEW spelling of every NEIGHBOUR hook command this repair anchored — the consumer's own\n * entries, which webpieces rewrites but does not author.\n *\n * The commands themselves rather than a count or a flag, because this is the one repair that\n * edits lines webpieces did not write: the cure has to be able to show the consumer exactly what\n * it changed in their file, or it is a silent edit to somebody else's hooks.\n */\n readonly anchoredNeighbours: readonly string[],\n ) {}\n}\n\n/**\n * Rewrite every stale settings file under `root`, for EVERY harness; returns what changed, per file.\n *\n * Existing files only — this never CREATES a registration. Arming a harness is the installer's decision\n * (`wp-install-ai-hooks`); this is the cure for one that has already been armed and has drifted, so a\n * repo that has never armed Codex is left exactly as it was.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as HarnessRegistration's siblings\nexport function repairRegistrationAt(root: string): readonly SettingsRepair[] {\n const repairs: SettingsRepair[] = [];\n for (const harness of HARNESS_REGISTRATIONS) {\n for (const settingsPath of harness.settingsPaths(root)) {\n if (!fs.existsSync(settingsPath)) continue;\n const settings = readSettings(settingsPath);\n const neededRegistration = registrationStale(harness, settings);\n const neededEnv = harness.managesEnv && envStale(settings);\n const changedManaged = repairRegistration(harness, settings);\n // AFTER the managed repair, never before: repairRegistration() removes the retired\n // guarantee-root entry and rewrites the two managed commands, so by the time the neighbour\n // pass runs there is nothing webpieces-owned left for it to look at. Gated on\n // registeredBins() for the same reason every other judgement here is — a settings file that\n // registers no webpieces hooks is not a webpieces install, and rewriting somebody's\n // unrelated hook lines in it would be webpieces editing a file it was never given.\n const anchored = registeredBins(settings).length === 0 ? [] : anchorNeighbourHooks(harness.shimAnchor, settings, root);\n if (!changedManaged && anchored.length === 0) continue;\n writeSettings(settingsPath, settings);\n repairs.push(new SettingsRepair(settingsPath, neededRegistration, neededEnv, anchored));\n }\n }\n return repairs;\n}\n\n/**\n * The names the drift check reports, so a deny can say WHICH surface moved.\n *\n * There were four, then three, and there are now FOUR again — but the fourth is not the one that was\n * deleted. `GUARANTEE_ROOT_SURFACE` went with L-1 itself: an absolutely-registered shim resolves from\n * any cwd, so there is no launch guarantee left to police and no second .sh file to keep byte-locked. A\n * settings file still carrying the retired H1 entry is not its own surface — it is ordinary REGISTRATION\n * drift, which `registrationStaleAt()` reports and `repairRegistration()` fixes by removing it.\n *\n * The new fourth is `.codex/hooks.json`, and it is here because of what happened while it was NOT a\n * managed surface: something else wrote it, with a matcher that matched no Codex file tool and a shim\n * path anchored on a variable Codex does not set, and no check in this package could see it. A file the\n * guards depend on and nothing validates is the exact shape of that incident.\n *\n * Each harness's registration surface is its own name, from HarnessRegistration.registrationSurface, so\n * the deny sends the reader to the file that actually moved.\n */\nexport const SHIM_SURFACE = SHIM_MARKER;\nexport const REGISTRATION_SURFACE = CLAUDE_REGISTRATION.registrationSurface;\nexport const CODEX_REGISTRATION_SURFACE = CODEX_REGISTRATION.registrationSurface;\nexport const ENV_SURFACE = `.claude/settings.json env.${BASH_CWD_ENV_KEY}`;\n// The generic PR-gate reviewer agent (issue #938): committed, generated, byte-stable — the same contract as\n// the shim, so the same check and the same cure.\nexport const REVIEWER_AGENT_SURFACE = REVIEWER_AGENT_MARKER;\n\n/**\n * WHICH of the managed surfaces disagree with this release — the input to fault S.\n *\n * All of them are checked against the SAME root, resolved from the RUNNING MODULE (governingShimRoot),\n * never from cwd and never from `$CLAUDE_PROJECT_DIR`: the files we compare and the renderers we\n * compare them TO must come from one install, or the check straddles two trees and can never converge.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as HarnessRegistration's siblings\nexport function managedSurfaceDrift(root: string | null): readonly string[] {\n const drifted: string[] = [];\n if (committedShimStale(root)) drifted.push(SHIM_SURFACE);\n for (const harness of HARNESS_REGISTRATIONS) {\n if (registrationStaleAt(harness, root)) drifted.push(harness.registrationSurface);\n // A neighbour hook registered with a RELATIVE entry path dies from any cwd but the root, and per\n // the hooks reference that non-zero exit is a NON-BLOCKING error — a SILENT UNGUARDED ALLOW. It\n // is a drift surface for exactly the reason the managed registration is one: nothing else in\n // this repo can see it, and the way it fails looks like a guard that PASSED. See\n // neighbour-hooks.ts, and issue #852 where it silently disarmed three security guards.\n if (neighbourHooksStaleAt(harness, root)) drifted.push(harness.neighbourSurface);\n }\n if (envStaleAt(root)) drifted.push(ENV_SURFACE);\n if (reviewerAgentStale(root)) drifted.push(REVIEWER_AGENT_SURFACE);\n return drifted;\n}\n"]}
1
+ {"version":3,"file":"hook-registration.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/bin/hook-registration.ts"],"names":[],"mappings":";;;AAuPA,4CAEC;AASD,wCAQC;AAQD,wCAGC;AAQD,0CAEC;AAUD,8CAOC;AAID,gDAYC;AAID,oCAIC;AA0BD,4BAIC;AAaD,0CAOC;AAkBD,gDAcC;AAGD,oCAWC;AAGD,sCAGC;AAYD,sDAaC;AAcD,kDAUC;AAUD,gCAUC;AAkCD,oDAsBC;AAiCD,kDAeC;;AA3lBD,+CAAyB;AACzB,mDAA6B;AAE7B,iEAA6D;AAE7D,iCAAyD;AACzD,qDAA6E;AAC7E,uDAAwG;AAExG,+CAAqE;AAErE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsDG;AAEH,+FAA+F;AAC/F,MAAa,qBAAqB;IAEjB;IACA;IAFb,YACa,OAAe,EACf,OAAe;QADf,YAAO,GAAP,OAAO,CAAQ;QACf,YAAO,GAAP,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path';\n\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { AiType } from '@webpieces/hook-runtime';\nimport { SHIM_MARKER, committedShimStale } from './shim';\nimport { REVIEWER_AGENT_MARKER, reviewerAgentStale } from './reviewer-agent';\nimport { NEIGHBOUR_SURFACE_SUFFIX, anchorNeighbourHooks, neighbourHooksStale } from './neighbour-hooks';\nimport type { ClaudeSettings, HookCommand, HookEntry } from './settings-shape';\nimport { BASH_CWD_ENV_KEY, BASH_CWD_ENV_VALUE } from './managed-env';\n\n/**\n * THE INSTALLED HOOK SURFACE — two hooks per harness, all ABSOLUTE, and the ONE place their spelling is\n * defined. See `HarnessRegistration` below, which is what makes \"per harness\" data rather than four\n * module constants that were only ever true of Claude Code.\n *\n * ─── ONE GOVERNOR: the MAIN tree judges every tree ─────────────────────────────────────────────────\n *\n * Claude Code — .claude/settings.json\n * H1 sh \"$CLAUDE_PROJECT_DIR/.claude/webpieces/ai-hook.sh\" wp-ai-guards-hook Write|…|Bash|Read\n * H2 sh \"$CLAUDE_PROJECT_DIR/.claude/webpieces/ai-hook.sh\" wp-ai-rules-hook Write|Edit|MultiEdit\n * Codex — .codex/hooks.json (the SAME `hooks.PreToolUse` JSON shape, measured)\n * H1 sh \"$PWD/.claude/webpieces/ai-hook.sh\" wp-ai-guards-hook Bash|apply_patch\n * H2 sh \"$PWD/.claude/webpieces/ai-hook.sh\" wp-ai-rules-hook apply_patch\n *\n * ONE shim file serves all four: `.claude/` there is a path, not a claim about who is calling.\n *\n * This REPLACES a three-hook form in which these two were RELATIVE (`sh \".claude/webpieces/ai-hook.sh\"`)\n * and a third hook, L-1 `guarantee-root.sh`, existed solely to guarantee that relative path resolved.\n *\n * ─── Why the relative experiment was reversed ──────────────────────────────────────────────────────\n * Relative registration was adopted so each git tree would be governed by \"its own release, binary and\n * pin\". MEASURED 2026-08-10: it never delivered that. A linked worktree has NO `node_modules`, so\n * ai-hook.sh's upward walk executes the PRIMARY's binary — `readlink -f` resolved a worktree agent's bin\n * to `<primary>/node_modules/@webpieces/agent-workflow-rules`. A worktree ran its own SCRIPT and its own\n * CONFIG; it never ran its own release. Governance was already the primary's, in every tree, the whole\n * time.\n *\n * The price of that fiction was an entire guard layer. A relative path only resolves at a tree root, and\n * a hook that cannot resolve exits 127 — per the hooks reference a NON-BLOCKING error, i.e. a SILENT\n * UNGUARDED ALLOW. So L-1 had to deny every `cd` into a project subdirectory. That denial produced the\n * force-to-root bug class, the reaped-worktree `cd` prescription, and a measured hard deadlock: L-1 told\n * a worktree-isolated agent to `cd` to the primary clone, which the harness refuses for an isolated\n * agent, leaving it unable to stay or to follow the cure.\n *\n * An absolute path resolves from ANY cwd. So the launch guarantee is structural, L-1 has no job left and\n * is deleted, and `cd` into a subdirectory is simply allowed. What used to be true only by policing the\n * shell is now true by construction.\n *\n * ─── What replaces the property that was lost ──────────────────────────────────────────────────────\n * Nothing is lost that was ever delivered — but the case relative registration WANTED to handle (a tree\n * that genuinely needs a different @webpieces) is now DETECTED instead of silently mis-governed:\n * `VersionSyncGuard` (L1 row 8) blocks when a worktree's pin disagrees with the main tree's, and\n * prescribes either aligning the pins (same git hash → same tracked pin → install in each tree that has\n * a node_modules) or using a separate CLONE, which — unlike a worktree — gets its own GOVERNANCE. Note\n * what that does NOT say: a worktree may perfectly well have its own node_modules, and usually does the\n * moment anything installs in it. What it may not have is a DIFFERENT @webpieces version.\n *\n * ─── Why the registration is a DRIFT SURFACE, not just an install step ─────────────────────────────\n * Nothing used to validate `.claude/settings.json` at all, so a settings file left on a superseded form\n * silently changed who governs. The installed surface is FOUR things (ai-hook.sh, the registration, the\n * managed `env` entry — see managed-env.ts — and the ANCHORING of the NEIGHBOUR hook commands the\n * consumer registers beside ours, see neighbour-hooks.ts), all four are compared against this release,\n * and `wp-upgrade-shim` repairs all four. A cure that fixes three of four is worse than no cure, because\n * it reports success.\n */\n\n/** One PreToolUse hook entry as webpieces registers it. Data-only → a class, per CLAUDE.md. */\nexport class HookRegistrationEntry {\n constructor(\n readonly matcher: string,\n readonly command: string,\n ) {}\n\n sameAs(other: HookRegistrationEntry): boolean {\n return this.matcher === other.matcher && this.command === other.command;\n }\n}\n\n/**\n * THE SETTINGS-FILE SHAPE lives in `./settings-shape`, a LEAF module, and is imported from THERE by\n * everything that needs it — this module included. It is deliberately NOT re-exported here: a second\n * import path for one type is the \"two spellings of one thing\" shim the compatibility policy rejects,\n * and it would keep advertising `hook-registration` as a source of the shape, which is precisely the\n * edge that has to stay broken (`neighbour-hooks.ts` needs the shape, this module imports the repairs\n * FROM it, and `validate-no-file-import-cycles` counts even a type-only edge back as a cycle).\n */\n\nexport const RULES_BIN = 'wp-ai-rules-hook';\nexport const GUARDS_BIN = 'wp-ai-guards-hook';\n\n/**\n * ONE HARNESS'S registration surface — where its hooks live, what they match, and how they name the\n * shim. Data-only → a class, per CLAUDE.md.\n *\n * ─── Why this exists ──────────────────────────────────────────────────────────────────────────────\n * The matchers and the shim command used to be four module constants written for Claude Code alone.\n * Applied to Codex they are wrong in both halves, and the way they are wrong is SILENT:\n *\n * - MATCHER. Codex's file-editing tool is `apply_patch` (MEASURED, codex-cli 0.151.0). A matcher of\n * `Write|Edit|MultiEdit` matches it never, so every file rule is unreachable while the settings file\n * looks perfectly installed. Its shell tool IS called `Bash` — Codex reuses Claude's name — which is\n * the trap: half the matcher works, so the hooks appear to be running.\n * - ANCHOR. `$CLAUDE_PROJECT_DIR` does not exist in a Codex hook's environment (measured: 46 vars, no\n * such key), so the command expands to `sh \"/.claude/webpieces/ai-hook.sh\"`, which dies — and per the\n * hooks protocol a non-2 non-zero exit is a NON-BLOCKING error, i.e. a silent unguarded allow.\n *\n * Both halves of that were live in real repos, written by a Codex Desktop sync that transliterated the\n * Claude setup. Making the registration per-harness DATA is what stops a future harness inheriting a\n * matcher that was never true for it.\n *\n * ─── ONE SHIM, both harnesses ─────────────────────────────────────────────────────────────────────\n * `SHIM_MARKER` is shared deliberately: `.claude/webpieces/ai-hook.sh` is the single fail-closed entry\n * point, and moving or duplicating it would double the L0 allowlist regexes, the drift surfaces and the\n * cures. The `.claude/` prefix is a path, not a claim about which agent is calling.\n */\nexport class HarnessRegistration {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n readonly aiType: AiType,\n /** How the installer and the drift report name this harness to a human. */\n readonly label: string,\n /** Which tool names the RULES hook (code-style, file-scoped) must see. */\n readonly rulesMatcher: string,\n /**\n * Which tool names the GUARDS hook must see. Wider than the rules matcher by the shell tool and,\n * for Claude Code, by `Read` — Read carries no guard, but the guards hook owns the\n * per-invocation audit log, so matching it records every file the AI opens (log-and-allow fast\n * path in hook-core.ts; a Read is never blocked). Codex has no Read tool at all: a read arrives\n * as `Bash` running a pager, which the shell matcher already covers and read-parity synthesizes.\n */\n readonly guardsMatcher: string,\n /** The settings files this harness's hooks can be installed into, relative to the repo root. */\n readonly settingsFiles: readonly string[],\n /**\n * THE PREFIX THE SHIM PATH IS ANCHORED ON, and the reason each harness needs its own.\n *\n * **BYTE-STABILITY IS A HARD CONSTRAINT ON THE CODEX VALUE.** Codex trusts a hook entry\n * TOFU — `~/.codex/config.toml` records a `trusted_hash` per entry — so ANY change to these bytes\n * invalidates that trust and re-prompts the human, whose third option is `Continue without\n * trusting (hooks won't run)`: one keystroke to a silently unguarded session. Changing this\n * string is therefore never a cosmetic edit. The hash is NOT reproducible from outside Codex\n * (16 encodings tried against a file we authored), so the installer can never repair trust for\n * itself — see ./codex-trust.ts, which REPORTS and never writes.\n */\n readonly shimAnchor: string,\n /**\n * True when this harness's settings file also carries the managed `env` block. Claude Code's\n * settings `env` is inherited by every subagent, which is what makes it the right home for the\n * Bash-cwd pin (see managed-env.ts). Codex has no equivalent surface — and needs none: its cwd\n * is MEASURED not to drift at all (`cd x && pwd` prints x, the next call is back at the repo\n * root, for the coordinator and for subagents alike).\n */\n readonly managesEnv: boolean,\n /** What `managedSurfaceDrift()` calls this harness's registration when it has moved. */\n readonly registrationSurface: string,\n ) {}\n\n /** Which matcher one guard bin registers under. */\n matcherFor(bin: string): string {\n return bin === RULES_BIN ? this.rulesMatcher : this.guardsMatcher;\n }\n\n /**\n * The guard-hook command — `sh \"<anchor>/.claude/webpieces/ai-hook.sh\" <bin>`.\n *\n * ABSOLUTE, in both harnesses. Claude's anchor replaced a RELATIVE spelling and that reversal is\n * documented at length in this file's header: relative resolves only at a tree root, a hook that\n * cannot resolve exits 127, and per the hooks reference that is a NON-BLOCKING error — a silent\n * unguarded allow. It also cost an entire guard layer (L-1) whose only job was to police the `cd`\n * that made the relative path resolvable.\n *\n * Invoked via `sh <file>` rather than executed directly so a missing executable bit on the\n * checked-in shim (fresh clone, a filesystem that drops the bit, git core.fileMode quirks) can never\n * break the hook with a raw `Permission denied` on every tool call. Quoted to survive spaces.\n */\n shimCommand(bin: string): string {\n return `sh \"${this.shimAnchor}/${SHIM_MARKER}\" ${bin}`;\n }\n\n /** The registration entry for one guard bin under this harness. */\n entryFor(bin: string): HookRegistrationEntry {\n return new HookRegistrationEntry(this.matcherFor(bin), this.shimCommand(bin));\n }\n\n /** This harness's settings files under one repo root, absolute. */\n settingsPaths(projectRoot: string): readonly string[] {\n return this.settingsFiles.map((file: string): string => path.join(projectRoot, ...file.split('/')));\n }\n\n /**\n * What `managedSurfaceDrift()` calls this harness's NEIGHBOUR hook commands — the entries a CONSUMER\n * repo registers in the same file — when one of them still carries a repo-RELATIVE entry path.\n *\n * DERIVED rather than a constructor field, unlike `registrationSurface` beside it, because there is\n * nothing here a harness could sensibly disagree about: it is the same file, said a second way. A\n * constructor param would be a second place to keep in step for no decision.\n */\n get neighbourSurface(): string {\n return `${this.settingsFiles[0]} ${NEIGHBOUR_SURFACE_SUFFIX}`;\n }\n}\n\nexport const CLAUDE_REGISTRATION = new HarnessRegistration(\n 'claude-code', 'Claude Code',\n 'Write|Edit|MultiEdit',\n 'Write|Edit|MultiEdit|Bash|Read',\n ['.claude/settings.json', '.claude/settings.local.json'],\n '$CLAUDE_PROJECT_DIR',\n true,\n '.claude/settings.json hook registration',\n);\n\n/**\n * Codex's registration, every value of it MEASURED against codex-cli 0.151.0 rather than assumed.\n *\n * `$PWD` is the anchor because there is no project-dir variable to use and none is needed: the payload\n * `cwd` and the hook process's own `PWD` are both the repo root on EVERY call — for the coordinator and\n * for subagents — and a `cd` inside one command never survives into the next. That was measured, not\n * hoped for, and it is the same effect Claude Code gets from the managed\n * `CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR` env entry. See `shimAnchor` for why these exact bytes are\n * not free to change.\n */\nexport const CODEX_REGISTRATION = new HarnessRegistration(\n 'codex', 'Codex',\n 'apply_patch',\n 'Bash|apply_patch',\n ['.codex/hooks.json'],\n '$PWD',\n false,\n '.codex/hooks.json hook registration',\n);\n\n/**\n * Every harness webpieces arms, in installer order.\n *\n * The drift check, the repair and the installer all iterate THIS, so a harness cannot be armed by the\n * installer and then left unvalidated — which is exactly the state `.codex/hooks.json` was in before it\n * was a managed surface: written by something else, silently wrong, and invisible to every check.\n */\nexport const HARNESS_REGISTRATIONS: readonly HarnessRegistration[] = [CLAUDE_REGISTRATION, CODEX_REGISTRATION];\n\n/**\n * True when this PreToolUse command is one webpieces owns — any command that runs the managed shim,\n * relative or absolute, so `repairRegistration()` can find a superseded spelling and rewrite it.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function isManagedCommand(command: string): boolean {\n return command.includes(SHIM_MARKER);\n}\n\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nfunction preToolUse(settings: ClaudeSettings): readonly HookEntry[] {\n return settings.hooks?.PreToolUse ?? [];\n}\n\n/** Every webpieces-managed entry of one settings file, flattened to matcher + command pairs. */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function managedEntries(settings: ClaudeSettings): readonly HookRegistrationEntry[] {\n const found: HookRegistrationEntry[] = [];\n for (const entry of preToolUse(settings)) {\n for (const hook of entry.hooks) {\n if (isManagedCommand(hook.command)) found.push(new HookRegistrationEntry(entry.matcher, hook.command));\n }\n }\n return found;\n}\n\n/**\n * Which guard bins this settings file registers, in installer order. A file registering NEITHER is not\n * a project (relative) install and is therefore never judged — a global/absolute install names the bin\n * path directly and carries no shim marker at all.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function registeredBins(settings: ClaudeSettings): readonly string[] {\n const commands = managedEntries(settings).map((e: HookRegistrationEntry): string => e.command);\n return [GUARDS_BIN, RULES_BIN].filter((bin: string): boolean => commands.some((c: string): boolean => c.includes(bin)));\n}\n\n/**\n * The exact set of entries THIS RELEASE expects in a settings file that registers `bins`.\n *\n * ONE entry per registered bin, and nothing else.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as HarnessRegistration's siblings\nexport function expectedEntries(harness: HarnessRegistration, bins: readonly string[]): readonly HookRegistrationEntry[] {\n return bins.map((bin: string): HookRegistrationEntry => harness.entryFor(bin));\n}\n\n/**\n * True when a settings file registers webpieces hooks in a shape this release does not expect: a\n * RELATIVE shim command, a stray duplicate, or a wrong matcher.\n *\n * Compared as a SET, not a sequence: Claude Code runs all matching hooks in parallel, so array order\n * carries no meaning and reordering must not read as drift.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function registrationStale(harness: HarnessRegistration, settings: ClaudeSettings): boolean {\n const bins = registeredBins(settings);\n if (bins.length === 0) return false;\n const have = managedEntries(settings);\n const want = expectedEntries(harness, bins);\n if (have.length !== want.length) return true;\n return want.some((w: HookRegistrationEntry): boolean => !have.some((h: HookRegistrationEntry): boolean => h.sameAs(w)));\n}\n\n/** Drop every webpieces-managed PreToolUse command; returns true if anything was removed. */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function dropManagedEntries(settings: ClaudeSettings): boolean {\n const entries = settings.hooks?.PreToolUse;\n if (!entries) return false;\n let changed = false;\n const kept: HookEntry[] = [];\n for (const entry of entries) {\n const hooks = entry.hooks.filter((h: HookCommand): boolean => !isManagedCommand(h.command));\n if (hooks.length !== entry.hooks.length) changed = true;\n if (hooks.length > 0) kept.push({ matcher: entry.matcher, hooks });\n }\n if (changed) settings.hooks!.PreToolUse = kept;\n return changed;\n}\n\n/** Append one PreToolUse entry. */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function addHookEntry(settings: ClaudeSettings, entry: HookRegistrationEntry): void {\n if (!settings.hooks) settings.hooks = {};\n if (!Array.isArray(settings.hooks.PreToolUse)) settings.hooks.PreToolUse = [];\n settings.hooks.PreToolUse.push({ matcher: entry.matcher, hooks: [{ type: 'command', command: entry.command }] });\n}\n\n/** The settings `env` block, or null when the file carries none (or carries junk in its place). */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nfunction settingsEnv(settings: ClaudeSettings): Record<string, string> | null {\n // webpieces-disable no-any-unknown -- settings.json is opaque consumer JSON; `env` is only typed after this check\n const env: unknown = settings.env;\n if (typeof env !== 'object' || env === null || Array.isArray(env)) return null;\n return env as Record<string, string>;\n}\n\n/**\n * True when a settings file that registers webpieces hooks is missing the managed `env` entry, or\n * carries any value other than the one required one.\n *\n * Gated on `registeredBins()` for the SAME reason `registrationStale()` is: a settings file that\n * registers no webpieces hooks is not a project install and is never judged — a global install names\n * the bin path directly and carries no shim marker at all, so there is nothing here to keep in step.\n *\n * NOTE what this entry is for NOW. It was originally justified by keeping the then-RELATIVE hook path\n * resolvable; that job is retired, because both hooks are absolute and resolve from any cwd. It is kept\n * for VERDICT STABILITY — a guard's answer must depend on the command, not on where an earlier `cd` left\n * the shell — and because settings `env` is inherited, every subagent shares that cwd and therefore that\n * verdict. See managed-env.ts, which states this at length.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function envStale(settings: ClaudeSettings): boolean {\n if (registeredBins(settings).length === 0) return false;\n const env = settingsEnv(settings);\n return env === null || env[BASH_CWD_ENV_KEY] !== BASH_CWD_ENV_VALUE;\n}\n\n/**\n * Set the managed `env` entry IN PLACE, whatever was there before. Returns true when it changed.\n *\n * A user-set `\"0\"` is BROUGHT TO `\"1\"`, not honoured: this is a managed surface, and \"webpieces sets it\n * unless you disagreed\" would be a second, invisible spelling of the decision. Turning it off means\n * uninstalling the hooks, exactly as it does for every other managed thing.\n *\n * UNGATED on purpose — the installer calls it for the file it is writing hooks into, and the gate lives\n * at the caller (repairRegistration / applyHook), so a file with no webpieces hooks is never touched.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function applyManagedEnv(settings: ClaudeSettings): boolean {\n const existing = settingsEnv(settings);\n if (existing !== null && existing[BASH_CWD_ENV_KEY] === BASH_CWD_ENV_VALUE) return false;\n const env = existing ?? {};\n env[BASH_CWD_ENV_KEY] = BASH_CWD_ENV_VALUE;\n settings.env = env;\n return true;\n}\n\n/**\n * Bring one settings object to the two-hook ABSOLUTE form AND the managed `env` entry IN PLACE. Returns\n * true when it changed anything.\n *\n * REMOVE-then-ADD for the hooks, never add-beside: two spellings of one registration is exactly the\n * compatibility shim the backwards-compat reviewer rejects, and leaving a RELATIVE entry beside the\n * absolute one would run two shims per call — the\n * straddle this whole change exists to delete.\n *\n * THE TWO REPAIRS ARE EVALUATED INDEPENDENTLY, and that is load-bearing rather than tidy: this used to\n * early-return on `!registrationStale(settings)`, so a repo whose hooks are already current but whose\n * `env` entry is missing — the state EVERY existing consumer is in the moment this release lands — would\n * have been reported as drifted by fault S and then left unrepaired by its own prescribed cure. A cure\n * that skips half the surface is the failure mode `upgrade-shim.ts`'s header exists to prevent.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function repairRegistration(harness: HarnessRegistration, settings: ClaudeSettings): boolean {\n const bins = registeredBins(settings);\n if (bins.length === 0) return false;\n let changed = false;\n if (registrationStale(harness, settings)) {\n dropManagedEntries(settings);\n for (const entry of expectedEntries(harness, bins)) addHookEntry(settings, entry);\n changed = true;\n }\n // Only where the harness HAS that surface. Codex's hooks.json has no `env` block to manage, and\n // inventing one there would write a key Codex does not read — a managed surface nothing consumes is\n // a surface that can drift with no consequence and no way to notice.\n if (harness.managesEnv && applyManagedEnv(settings)) changed = true;\n return changed;\n}\n\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function readSettings(settingsPath: string): ClaudeSettings {\n if (!fs.existsSync(settingsPath)) return {};\n const raw = fs.readFileSync(settingsPath, 'utf8');\n if (raw.trim() === '') return {};\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return JSON.parse(raw) as ClaudeSettings;\n } catch (err: unknown) {\n const error = toError(err);\n throw new Error(`${settingsPath} has invalid JSON — fix it, then retry: ${error.message}`, { cause: error });\n }\n}\n\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function writeSettings(settingsPath: string, settings: ClaudeSettings): void {\n fs.mkdirSync(path.dirname(settingsPath), { recursive: true });\n fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 4) + '\\n');\n}\n\n/**\n * True when any settings file ONE HARNESS owns under `root` carries a NEIGHBOUR hook — one the consumer\n * repo wrote — whose entry path is repo-RELATIVE and would therefore fail to resolve from any cwd but\n * the root. See neighbour-hooks.ts for the measured failure and why webpieces owns the repair.\n *\n * Judged ONLY where the file registers webpieces hooks, exactly like `registrationStaleAt` below: a\n * settings file with no webpieces hooks in it is not a webpieces install, and webpieces rewriting\n * somebody's unrelated hook lines there would be editing a file it was never given.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as HarnessRegistration's siblings\nexport function neighbourHooksStaleAt(harness: HarnessRegistration, root: string | null): boolean {\n if (root === null) return false;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return harness.settingsPaths(root).some((p: string): boolean => {\n const settings = readSettings(p);\n return registeredBins(settings).length > 0 && neighbourHooksStale(harness.shimAnchor, settings, root);\n });\n } catch (err: unknown) {\n const error = toError(err);\n void error; // best-effort: unreadable/invalid settings counts as \"not stale\" so it never wedges a call\n return false;\n }\n}\n\n/**\n * True when any settings file ONE HARNESS owns under `root` carries a stale registration.\n *\n * Per harness, not per repo, so the drift report can NAME which one moved — `.claude/settings.json` and\n * `.codex/hooks.json` have different cures, and a fault that says only \"the registration is stale\" sends\n * the reader to the wrong file half the time.\n *\n * A file that does not exist, or exists and registers no webpieces hooks, is never judged (see\n * `registrationStale`). That is what keeps a repo which has never armed Codex from suddenly faulting on\n * a `.codex/hooks.json` it does not have.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as HarnessRegistration's siblings\nexport function registrationStaleAt(harness: HarnessRegistration, root: string | null): boolean {\n if (root === null) return false;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return harness.settingsPaths(root).some((p: string): boolean => registrationStale(harness, readSettings(p)));\n } catch (err: unknown) {\n const error = toError(err);\n void error; // best-effort: unreadable/invalid settings counts as \"not stale\" so it never wedges a call\n return false;\n }\n}\n\n/**\n * True when either Claude project settings file under `root` is missing the managed `env` entry.\n *\n * CLAUDE-ONLY by construction, and stated as such rather than looped over the harnesses: `env` is a\n * Claude Code settings surface, Codex has no equivalent, and Codex's cwd is measured not to drift, which\n * is the whole thing the entry is for. See HarnessRegistration.managesEnv.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as HarnessRegistration's siblings\nexport function envStaleAt(root: string | null): boolean {\n if (root === null) return false;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return CLAUDE_REGISTRATION.settingsPaths(root).some((p: string): boolean => envStale(readSettings(p)));\n } catch (err: unknown) {\n const error = toError(err);\n void error; // best-effort: unreadable/invalid settings counts as \"not stale\" so it never wedges a call\n return false;\n }\n}\n\n/**\n * WHAT was rewritten in ONE settings file. Data-only → a class, per CLAUDE.md.\n *\n * Two independent flags rather than one path, because the cure has to be able to SAY which repair it\n * made: \"rewrote the hook registration\" printed for a file whose registration was already current and\n * whose `env` entry was the only thing missing is a cure lying about its own work.\n */\nexport class SettingsRepair {\n constructor(\n readonly settingsPath: string,\n readonly registration: boolean,\n readonly env: boolean,\n /**\n * The NEW spelling of every NEIGHBOUR hook command this repair anchored — the consumer's own\n * entries, which webpieces rewrites but does not author.\n *\n * The commands themselves rather than a count or a flag, because this is the one repair that\n * edits lines webpieces did not write: the cure has to be able to show the consumer exactly what\n * it changed in their file, or it is a silent edit to somebody else's hooks.\n */\n readonly anchoredNeighbours: readonly string[],\n ) {}\n}\n\n/**\n * Rewrite every stale settings file under `root`, for EVERY harness; returns what changed, per file.\n *\n * Existing files only — this never CREATES a registration. Arming a harness is the installer's decision\n * (`wp-install-ai-hooks`); this is the cure for one that has already been armed and has drifted, so a\n * repo that has never armed Codex is left exactly as it was.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as HarnessRegistration's siblings\nexport function repairRegistrationAt(root: string): readonly SettingsRepair[] {\n const repairs: SettingsRepair[] = [];\n for (const harness of HARNESS_REGISTRATIONS) {\n for (const settingsPath of harness.settingsPaths(root)) {\n if (!fs.existsSync(settingsPath)) continue;\n const settings = readSettings(settingsPath);\n const neededRegistration = registrationStale(harness, settings);\n const neededEnv = harness.managesEnv && envStale(settings);\n const changedManaged = repairRegistration(harness, settings);\n // AFTER the managed repair, never before: repairRegistration() rewrites the two managed\n // commands, so by the time the neighbour pass runs there is nothing webpieces-owned left for\n // it to look at. Gated on\n // registeredBins() for the same reason every other judgement here is — a settings file that\n // registers no webpieces hooks is not a webpieces install, and rewriting somebody's\n // unrelated hook lines in it would be webpieces editing a file it was never given.\n const anchored = registeredBins(settings).length === 0 ? [] : anchorNeighbourHooks(harness.shimAnchor, settings, root);\n if (!changedManaged && anchored.length === 0) continue;\n writeSettings(settingsPath, settings);\n repairs.push(new SettingsRepair(settingsPath, neededRegistration, neededEnv, anchored));\n }\n }\n return repairs;\n}\n\n/**\n * The names the drift check reports, so a deny can say WHICH surface moved.\n *\n * There were four, then three, and there are now FOUR again — but the fourth is not the one that was\n * deleted. `GUARANTEE_ROOT_SURFACE` went with L-1 itself: an absolutely-registered shim resolves from\n * any cwd, so there is no launch guarantee left to police and no second .sh file to keep byte-locked.\n *\n * The new fourth is `.codex/hooks.json`, and it is here because of what happened while it was NOT a\n * managed surface: something else wrote it, with a matcher that matched no Codex file tool and a shim\n * path anchored on a variable Codex does not set, and no check in this package could see it. A file the\n * guards depend on and nothing validates is the exact shape of that incident.\n *\n * Each harness's registration surface is its own name, from HarnessRegistration.registrationSurface, so\n * the deny sends the reader to the file that actually moved.\n */\nexport const SHIM_SURFACE = SHIM_MARKER;\nexport const REGISTRATION_SURFACE = CLAUDE_REGISTRATION.registrationSurface;\nexport const CODEX_REGISTRATION_SURFACE = CODEX_REGISTRATION.registrationSurface;\nexport const ENV_SURFACE = `.claude/settings.json env.${BASH_CWD_ENV_KEY}`;\n// The generic PR-gate reviewer agent (issue #938): committed, generated, byte-stable — the same contract as\n// the shim, so the same check and the same cure.\nexport const REVIEWER_AGENT_SURFACE = REVIEWER_AGENT_MARKER;\n\n/**\n * WHICH of the managed surfaces disagree with this release — the input to fault S.\n *\n * All of them are checked against the SAME root, resolved from the RUNNING MODULE (governingShimRoot),\n * never from cwd and never from `$CLAUDE_PROJECT_DIR`: the files we compare and the renderers we\n * compare them TO must come from one install, or the check straddles two trees and can never converge.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as HarnessRegistration's siblings\nexport function managedSurfaceDrift(root: string | null): readonly string[] {\n const drifted: string[] = [];\n if (committedShimStale(root)) drifted.push(SHIM_SURFACE);\n for (const harness of HARNESS_REGISTRATIONS) {\n if (registrationStaleAt(harness, root)) drifted.push(harness.registrationSurface);\n // A neighbour hook registered with a RELATIVE entry path dies from any cwd but the root, and per\n // the hooks reference that non-zero exit is a NON-BLOCKING error — a SILENT UNGUARDED ALLOW. It\n // is a drift surface for exactly the reason the managed registration is one: nothing else in\n // this repo can see it, and the way it fails looks like a guard that PASSED. See\n // neighbour-hooks.ts, and issue #852 where it silently disarmed three security guards.\n if (neighbourHooksStaleAt(harness, root)) drifted.push(harness.neighbourSurface);\n }\n if (envStaleAt(root)) drifted.push(ENV_SURFACE);\n if (reviewerAgentStale(root)) drifted.push(REVIEWER_AGENT_SURFACE);\n return drifted;\n}\n"]}
package/src/bin/setup.js CHANGED
@@ -27,7 +27,7 @@ const setup_config_1 = require("./setup-config");
27
27
  // InstallTarget) so a team can ship the guards while a developer keeps the code-style rules local
28
28
  // while iterating. Both are registered ABSOLUTE via $CLAUDE_PROJECT_DIR, so the MAIN tree governs every
29
29
  // tree. There used to be a third — the L-1 hook, which existed only to keep a RELATIVE registration
30
- // resolvable; it is retired, and purgeRetiredGuaranteeRoot() removes anything left of it.
30
+ // resolvable; an absolute registration resolves from any cwd, so it is gone.
31
31
  // ---------------------------------------------------------------------------
32
32
  class HookSpec {
33
33
  key;
@@ -84,30 +84,6 @@ function markerReferenced(targets, marker) {
84
84
  return entries.some((e) => e.hooks.some((h) => h.command.includes(marker)));
85
85
  });
86
86
  }
87
- /**
88
- * Remove every trace of the RETIRED L-1 hook (`guarantee-root.sh`) — the file and any PreToolUse entry
89
- * still pointing at it. REMOVAL ONLY: nothing here can ever write one back.
90
- *
91
- * L-1 existed to guarantee a RELATIVE guard-hook path resolved, by refusing any `cd` that would park the
92
- * shell in a subdirectory. The guard hooks are ABSOLUTE now (`$CLAUDE_PROJECT_DIR/...`), so they resolve
93
- * from any cwd and the guarantee is structural — there is nothing left to police, and the subdirectory
94
- * denial that used to pay for it is gone with it.
95
- */
96
- // webpieces-disable no-function-outside-class -- setup.ts is deliberately DI-free (it must run on a half-written node_modules; see install-entry.ts), so every function here is module-scope
97
- function purgeRetiredGuaranteeRoot(targets, projectRoot) {
98
- for (const target of targets) {
99
- const settings = (0, hook_registration_1.readSettings)(target.settingsPath);
100
- if (removeHookByMarker(settings, hook_registration_1.LEGACY_GUARANTEE_ROOT_MARKER)) {
101
- (0, hook_registration_1.writeSettings)(target.settingsPath, settings);
102
- console.log(` 🗑️ removed the retired L-1 guarantee-root hook from ${target.label}`);
103
- }
104
- }
105
- const legacyFile = path.join(projectRoot, hook_registration_1.LEGACY_GUARANTEE_ROOT_MARKER);
106
- if (fs.existsSync(legacyFile)) {
107
- fs.rmSync(legacyFile, { force: true });
108
- console.log(' 🗑️ deleted the retired .claude/webpieces/guarantee-root.sh');
109
- }
110
- }
111
87
  class InstallTarget {
112
88
  choice;
113
89
  label;
@@ -177,7 +153,7 @@ function hasHook(settings, bin) {
177
153
  }
178
154
  // Drop every PreToolUse command containing `marker` (a bin name, or a managed .sh path); returns true
179
155
  // if anything was removed. REMOVE-then-ADD is what keeps an upgrade from leaving a superseded spelling
180
- // (a relative command, or the retired L-1 entry) beside the current one — two spellings of one
156
+ // (a relative command) beside the current one — two spellings of one
181
157
  // registration is the compatibility shim the backwards-compat reviewer rejects.
182
158
  // webpieces-disable no-function-outside-class -- setup.ts is deliberately DI-free (it must run on a half-written node_modules; see install-entry.ts), so every function here is module-scope
183
159
  function removeHookByMarker(settings, marker) {
@@ -243,11 +219,6 @@ function applyHook(hook, chosen, targets, projectRoot) {
243
219
  else if (!markerReferenced(targets, shim_1.SHIM_MARKER)) {
244
220
  removeShim(projectRoot);
245
221
  }
246
- // The RETIRED L-1 hook rode with the GUARDS hook, so its removal does too. Doing it here rather than
247
- // at a separate call site means every existing caller of applyHook — the installer's interactive and
248
- // --target paths, and every test — converges on the two-hook absolute form with no second step.
249
- if (hook.bin === hook_registration_1.GUARDS_BIN)
250
- purgeRetiredGuaranteeRoot(targets, projectRoot);
251
222
  if (chosen === null)
252
223
  console.log(` ⛔ ${hook.label} not installed (removed from all locations).`);
253
224
  }
@@ -1 +1 @@
1
- {"version":3,"file":"setup.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/bin/setup.ts"],"names":[],"mappings":";;;AAuJA,wCAaC;AAMD,0BAGC;AAwBD,8BA8CC;AAyCD,kDAWC;AAID,wCAGC;AAUD,k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AK,IAAI,EAAE,CAAC;YAClB,OAAO,CAAC,KAAK,CAAC,uBAAuB,UAAU,2DAA2D,CAAC,CAAC;YAC5G,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;YACrB,OAAO;QACX,CAAC;QACD,WAAW,CAAC,kBAAU,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,CAAC,CAAC;QACtD,WAAW,CAAC,mBAAW,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,CAAC,CAAC;QACvD,OAAO,CAAC,GAAG,CAAC,8BAA8B,UAAU,GAAG,CAAC,CAAC;QACzD,gBAAgB,CAAC,WAAW,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;QAC/C,OAAO;IACX,CAAC;IAED,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IAChB,OAAO,CAAC,GAAG,CAAC,kFAAkF,CAAC,CAAC;IAChG,MAAM,QAAQ,CAAC,kBAAU,EAAE,OAAO,EAAE,WAAW,CAAC,CAAC;IACjD,MAAM,QAAQ,CAAC,mBAAW,EAAE,OAAO,EAAE,WAAW,CAAC,CAAC;IAClD,oGAAoG;IACpG,oEAAoE;IACpE,gBAAgB,CAAC,WAAW,EAAE,OAAO,EAAE,GAAG,CAAC,CAAC;IAC5C,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IAChB,OAAO,CAAC,GAAG,CAAC,8EAA8E,CAAC,CAAC;IAC5F,OAAO,CAAC,GAAG,CAAC,2FAA2F,CAAC,CAAC;AAC7G,CAAC;AAED,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;IAC1B,KAAK,IAAI,EAAE,CAAC;AAChB,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { homedir } from 'os';\nimport { createInterface } from 'readline';\n\nimport { RepoRootFinder, writeTemplate, writeTemplateIfMissing, CONFIG_POLICY_DOC } from '@webpieces/rules-config';\n\nimport { SHIM_MARKER, shimPath, renderShim } from './shim';\nimport { REVIEWER_AGENT_MARKER, writeReviewerAgent } from './reviewer-agent';\nimport { HookRegistrationEntry, GUARDS_BIN, LEGACY_GUARANTEE_ROOT_MARKER, RULES_BIN, addHookEntry, applyManagedEnv, readSettings, writeSettings, HarnessRegistration, CLAUDE_REGISTRATION, CODEX_REGISTRATION } from './hook-registration';\nimport type { ClaudeSettings, HookCommand, HookEntry } from './settings-shape';\nimport { BASH_CWD_ENV_KEY, BASH_CWD_ENV_VALUE } from './managed-env';\nimport { CodexTrustProbe } from './codex-trust';\n// The config half of the installer — seeding and migrating webpieces.config.json. Split for size along\n// the seam that was already there: this module is hook WIRING, that one is CONFIG SHAPE.\nimport { seedOrSyncConfig } from './setup-config';\n\n\n// ---------------------------------------------------------------------------\n// The two independently-installable GUARD hooks. Each can land in a different settings file (see\n// InstallTarget) so a team can ship the guards while a developer keeps the code-style rules local\n// while iterating. Both are registered ABSOLUTE via $CLAUDE_PROJECT_DIR, so the MAIN tree governs every\n// tree. There used to be a third — the L-1 hook, which existed only to keep a RELATIVE registration\n// resolvable; it is retired, and purgeRetiredGuaranteeRoot() removes anything left of it.\n// ---------------------------------------------------------------------------\nclass HookSpec {\n constructor(\n readonly key: string,\n readonly label: string,\n readonly bin: string,\n ) {}\n\n /**\n * WHICH TOOL NAMES this hook must see, in the harness the target belongs to.\n *\n * It is a lookup on the target rather than a field on the spec because the answer is not a property\n * of the hook: the rules hook matches `Write|Edit|MultiEdit` under Claude Code and `apply_patch`\n * under Codex, and a single stored matcher is exactly how `.codex/hooks.json` came to be registered\n * against tool names Codex never emits.\n */\n matcherFor(target: InstallTarget): string {\n return target.harness.matcherFor(this.bin);\n }\n\n // Absolute targets (global) need the exact path to this repo's bin — no ~/.webpieces bridge.\n // Project targets get the ABSOLUTE shim command, anchored on the harness's own project-root variable\n // (see HarnessRegistration.shimCommand): it resolves from ANY cwd, so a hook can never fail to\n // launch — which per the hooks reference would be exit 127, a SILENT UNGUARDED ALLOW, not a block.\n commandFor(target: InstallTarget, projectRoot: string): string {\n if (target.absolute) {\n return `node ${path.join(projectRoot, 'node_modules', '.bin', this.bin)}`;\n }\n return target.harness.shimCommand(this.bin);\n }\n}\n\n// Idempotent: re-running the installer overwrites the managed shim in place.\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nfunction writeShim(projectRoot: string): void {\n const target = shimPath(projectRoot);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, renderShim(), { mode: 0o755 });\n // writeFileSync's mode is only applied when creating the file; force it on overwrite too.\n fs.chmodSync(target, 0o755);\n}\n\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nfunction removeShim(projectRoot: string): void {\n const target = shimPath(projectRoot);\n if (fs.existsSync(target)) fs.rmSync(target);\n}\n\n// A managed .sh is shared by the project hooks — only safe to delete once no project settings file\n// references it anymore (i.e. the other hook was moved to global or uninstalled too).\n// webpieces-disable no-function-outside-class -- setup.ts is deliberately DI-free (it must run on a half-written node_modules; see install-entry.ts), so every function here is module-scope\nfunction markerReferenced(targets: InstallTarget[], marker: string): boolean {\n return targets.some((t: InstallTarget) => {\n const entries = readSettings(t.settingsPath).hooks?.PreToolUse ?? [];\n return entries.some((e: HookEntry) => e.hooks.some((h: HookCommand) => h.command.includes(marker)));\n });\n}\n\n/**\n * Remove every trace of the RETIRED L-1 hook (`guarantee-root.sh`) — the file and any PreToolUse entry\n * still pointing at it. REMOVAL ONLY: nothing here can ever write one back.\n *\n * L-1 existed to guarantee a RELATIVE guard-hook path resolved, by refusing any `cd` that would park the\n * shell in a subdirectory. The guard hooks are ABSOLUTE now (`$CLAUDE_PROJECT_DIR/...`), so they resolve\n * from any cwd and the guarantee is structural — there is nothing left to police, and the subdirectory\n * denial that used to pay for it is gone with it.\n */\n// webpieces-disable no-function-outside-class -- setup.ts is deliberately DI-free (it must run on a half-written node_modules; see install-entry.ts), so every function here is module-scope\nfunction purgeRetiredGuaranteeRoot(targets: InstallTarget[], projectRoot: string): void {\n for (const target of targets) {\n const settings = readSettings(target.settingsPath);\n if (removeHookByMarker(settings, LEGACY_GUARANTEE_ROOT_MARKER)) {\n writeSettings(target.settingsPath, settings);\n console.log(` 🗑️ removed the retired L-1 guarantee-root hook from ${target.label}`);\n }\n }\n const legacyFile = path.join(projectRoot, LEGACY_GUARANTEE_ROOT_MARKER);\n if (fs.existsSync(legacyFile)) {\n fs.rmSync(legacyFile, { force: true });\n console.log(' 🗑️ deleted the retired .claude/webpieces/guarantee-root.sh');\n }\n}\n\nexport class InstallTarget {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n readonly choice: string,\n readonly label: string,\n readonly settingsPath: string,\n readonly absolute: boolean,\n /**\n * WHICH HARNESS this file arms — it decides the matcher and the shim anchor written into it.\n *\n * REQUIRED, with no default, and the absence of one is the point. A default of\n * CLAUDE_REGISTRATION would make \"omit the harness\" mean \"Claude Code\" — a widening that is an\n * ABSENCE rather than a token, so a target built for Codex without it would silently carry\n * `Write|Edit|MultiEdit` and `$CLAUDE_PROJECT_DIR`, which is EXACTLY the silently-unguarded\n * state this class exists to end, and ungreppable besides.\n */\n readonly harness: HarnessRegistration,\n ) {}\n}\n\n// The bin names come from ./hook-registration, which is also what the drift check and wp-upgrade-shim\n// compare against — one spelling of the registration, or the installer and the validator can disagree\n// about what \"installed\" means. The MATCHER is not here: it belongs to the harness, not the hook (see\n// HookSpec.matcherFor).\nexport const RULES_HOOK = new HookSpec('rules', 'Rules hook (code-style validation)', RULES_BIN);\nexport const GUARDS_HOOK = new HookSpec('guards', 'Guards hook (git/PR/branch protection)', GUARDS_BIN);\n\n/**\n * Every file the installer can write, keyed by the CHOICE a human makes.\n *\n * TWO TARGETS SHARE CHOICE `1`, and that is the design rather than an oversight: \"the project, committed,\n * for the team\" is ONE intention, and a repo that is worked on by both harnesses needs both files armed\n * to mean it. Splitting it into two questions would let a human answer them differently and end up with a\n * repo where Codex is silently unguarded — which is the state this whole change exists to end. Every\n * caller selects by choice id (`targets.filter(t => t.choice === answer)`), never by index, so adding a\n * harness adds a row and changes no numbering.\n *\n * `2` (personal) and `3` (global) stay Claude-only because neither has a Codex counterpart: Codex reads\n * one repo-local `hooks.json` and has no personal or home-scoped hook file.\n *\n * `homeDir` is injectable so tests can point the global target at a temp dir instead of the real\n * ~/.claude/settings.json (a unit test must never write the user's actual global settings).\n */\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nexport function installTargets(projectRoot: string, homeDir: string = homedir()): InstallTarget[] {\n return [\n new InstallTarget('1', 'project (.claude/settings.json — committed, for the team)',\n path.join(projectRoot, '.claude', 'settings.json'), false, CLAUDE_REGISTRATION),\n new InstallTarget('2', 'project for you (.claude/settings.local.json — personal)',\n path.join(projectRoot, '.claude', 'settings.local.json'), false, CLAUDE_REGISTRATION),\n new InstallTarget('3', 'global (~/.claude/settings.json — exact path, this repo only)',\n path.join(homeDir, '.claude', 'settings.json'), true, CLAUDE_REGISTRATION),\n // Given choice `1` so one answer arms the whole project — see the docblock. Its position in the\n // array carries no meaning: every caller selects by choice id.\n new InstallTarget('1', 'project, for Codex too (.codex/hooks.json — committed, for the team)',\n path.join(projectRoot, ...CODEX_REGISTRATION.settingsFiles[0].split('/')), false, CODEX_REGISTRATION),\n ];\n}\n\n// ---------------------------------------------------------------------------\n// Claude Code settings.json hook wiring.\n// ---------------------------------------------------------------------------\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nexport function hasHook(settings: ClaudeSettings, bin: string): boolean {\n const entries = settings.hooks?.PreToolUse ?? [];\n return entries.some((e: HookEntry) => e.hooks.some((h: HookCommand) => h.command.includes(bin)));\n}\n\n// Drop every PreToolUse command containing `marker` (a bin name, or a managed .sh path); returns true\n// if anything was removed. REMOVE-then-ADD is what keeps an upgrade from leaving a superseded spelling\n// (a relative command, or the retired L-1 entry) beside the current one — two spellings of one\n// registration is the compatibility shim the backwards-compat reviewer rejects.\n// webpieces-disable no-function-outside-class -- setup.ts is deliberately DI-free (it must run on a half-written node_modules; see install-entry.ts), so every function here is module-scope\nfunction removeHookByMarker(settings: ClaudeSettings, marker: string): boolean {\n const entries = settings.hooks?.PreToolUse;\n if (!entries) return false;\n let changed = false;\n const kept: HookEntry[] = [];\n for (const entry of entries) {\n const hooks = entry.hooks.filter((h: HookCommand) => !h.command.includes(marker));\n if (hooks.length !== entry.hooks.length) changed = true;\n if (hooks.length > 0) kept.push({ matcher: entry.matcher, hooks });\n }\n if (changed) settings.hooks!.PreToolUse = kept;\n return changed;\n}\n\n// Apply the chosen install for one hook: remove it from every target file, then add it back to the\n// chosen one (or nowhere, for uninstall). Writes only the files that changed.\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nexport function applyHook(hook: HookSpec, chosen: InstallTarget | null, targets: InstallTarget[], projectRoot: string): void {\n // SCOPED TO THE CHOSEN HARNESS, and this is what makes one call per target composable. Installing\n // the Claude hook must not strip the Codex one, so \"remove it from everywhere else\" means everywhere\n // else THIS HARNESS could live. Uninstall (chosen === null) is the one case that means every\n // harness, because \"not installed\" has to be true everywhere or the hook is still armed somewhere.\n const scope = chosen === null ? targets : targets.filter((t: InstallTarget) => t.harness === chosen.harness);\n for (const target of scope) {\n const settings = readSettings(target.settingsPath);\n const removed = removeHookByMarker(settings, hook.bin);\n const isChosen = chosen !== null && chosen.settingsPath === target.settingsPath;\n if (isChosen) {\n addHookEntry(settings, new HookRegistrationEntry(hook.matcherFor(target), hook.commandFor(target, projectRoot)));\n // The managed `env` entry goes into the SAME file the hooks go into, on every path that\n // writes hooks — interactive or `--target=`. It pins the Bash cwd to the project root, so a\n // guard's answer depends on the command rather than on where an earlier `cd` left the shell,\n // and settings `env` is inherited, so every subagent gets the identical cwd and therefore the\n // identical guard verdict. (It no longer has a RESOLUTION job — the hooks are absolute.) See\n // hook-registration.ts for the full argument; `wp-upgrade-shim` self-heals it afterwards.\n // …in the harness that HAS that surface. Codex has no settings `env`, and needs none: its\n // cwd is MEASURED not to drift, which is the whole thing this entry buys under Claude Code.\n if (target.harness.managesEnv && applyManagedEnv(settings)) {\n console.log(` ✅ env.${BASH_CWD_ENV_KEY}=${BASH_CWD_ENV_VALUE} → ${target.label} (pins the Bash cwd to the project root, for this session and every subagent)`);\n }\n writeSettings(target.settingsPath, settings);\n console.log(` ✅ ${hook.label} → ${target.label}`);\n } else if (removed) {\n writeSettings(target.settingsPath, settings);\n }\n }\n // Manage the shared checked-in shim: (re)write it whenever a project (relative) install exists,\n // otherwise clean it up once neither hook references it anymore.\n if (chosen !== null && !chosen.absolute) {\n writeShim(projectRoot);\n // The generic PR-gate reviewer agent is part of the same committed, managed set as the shim — the\n // drift check reports it beside the shim, so the installer writes it beside the shim.\n if (writeReviewerAgent(projectRoot)) {\n console.log(` ✅ ${REVIEWER_AGENT_MARKER} (the generic PR-gate reviewer; generated — commit it, do not edit it)`);\n }\n } else if (!markerReferenced(targets, SHIM_MARKER)) {\n removeShim(projectRoot);\n }\n // The RETIRED L-1 hook rode with the GUARDS hook, so its removal does too. Doing it here rather than\n // at a separate call site means every existing caller of applyHook — the installer's interactive and\n // --target paths, and every test — converges on the two-hook absolute form with no second step.\n if (hook.bin === GUARDS_BIN) purgeRetiredGuaranteeRoot(targets, projectRoot);\n if (chosen === null) console.log(` ⛔ ${hook.label} not installed (removed from all locations).`);\n}\n\n/**\n * Say whether Codex will actually RUN what we just registered — the one thing the installer cannot do\n * anything about and therefore must not leave silent.\n *\n * Codex trusts a hook entry TOFU and re-prompts whenever its bytes change, and the prompt's third option\n * is \"Continue without trusting (hooks won't run)\". So a perfectly successful install can be followed by\n * a fully unguarded session, and the only honest thing to print is what is true plus the one action a\n * HUMAN has to take. Nothing here writes `~/.codex/config.toml` — see codex-trust.ts for why forging a\n * `trusted_hash` is not on the table.\n *\n * Silent when this repo did not arm Codex, so a Claude-only install gains no noise.\n */\n// webpieces-disable no-function-outside-class -- setup.ts is deliberately DI-free (it must run on a half-written node_modules; see install-entry.ts), so every function here is module-scope\nfunction reportCodexTrust(projectRoot: string, targets: InstallTarget[], choice: string): void {\n const armed = targets.some((t: InstallTarget): boolean => t.choice === choice && t.harness === CODEX_REGISTRATION);\n if (!armed) return;\n const lines = new CodexTrustProbe().read(projectRoot).lines();\n if (lines.length === 0) return;\n console.log('');\n for (const line of lines) console.log(line);\n}\n\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nfunction currentLocation(hook: HookSpec, targets: InstallTarget[]): string {\n const here = targets.filter((t: InstallTarget) => hasHook(readSettings(t.settingsPath), hook.bin));\n return here.length === 0 ? 'none' : here.map((t: InstallTarget) => t.label.split(' (')[0]).join(', ');\n}\n\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nfunction prompt(question: string): Promise<string> {\n return new Promise((resolve: (answer: string) => void) => {\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n rl.question(question, (answer: string) => { rl.close(); resolve(answer.trim()); });\n });\n}\n\n// Map a friendly `--target` name to an InstallTarget choice id (see installTargets). Returns null\n// for an unknown name so the caller can error out. Kept separate + exported for unit testing.\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nexport function resolveTargetChoice(name: string): string | null {\n switch (name) {\n case 'project': return '1';\n case 'project-personal':\n case 'projectpersonal':\n case 'local': return '2';\n case 'global': return '3';\n case 'none':\n case 'uninstall': return '4';\n default: return null;\n }\n}\n\n// Extract the value of `--target=<name>` from argv (null if the flag is absent).\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nexport function parseTargetArg(args: string[]): string | null {\n const flag = args.find((a: string): boolean => a.startsWith('--target='));\n return flag ? flag.slice('--target='.length) : null;\n}\n\n/**\n * Apply ONE choice for one hook: every target that answer selects, or uninstall when it selects none.\n *\n * The loop is what lets one choice arm several harnesses (choice `1` writes both the Claude settings\n * file and the Codex hooks file — see installTargets). `applyHook` scopes its removals to the chosen\n * target's harness, which is what keeps these calls from undoing one another.\n */\n// webpieces-disable no-function-outside-class -- setup.ts is deliberately DI-free (it must run on a half-written node_modules; see install-entry.ts), so every function here is module-scope\nexport function applyChoice(hook: HookSpec, choice: string, targets: InstallTarget[], projectRoot: string): void {\n const chosen = targets.filter((t: InstallTarget): boolean => t.choice === choice);\n if (chosen.length === 0) {\n applyHook(hook, null, targets, projectRoot);\n return;\n }\n for (const target of chosen) applyHook(hook, target, targets, projectRoot);\n}\n\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nasync function wireHook(hook: HookSpec, targets: InstallTarget[], projectRoot: string): Promise<void> {\n console.log('');\n console.log(`${hook.label}`);\n console.log(` currently installed in: ${currentLocation(hook, targets)}`);\n // The matcher is printed PER TARGET now, because it differs per harness — Codex's file tool is\n // `apply_patch`, Claude's are Write|Edit|MultiEdit — and one matcher printed above the list would be\n // wrong for whichever harness it did not describe.\n for (const target of targets) console.log(` ${target.choice}) ${target.label} [matcher: ${hook.matcherFor(target)}]`);\n console.log(' 4) none / uninstall');\n const answer = await prompt(' Where should it live? [1/2/3/4, default 4]: ');\n applyChoice(hook, answer, targets, projectRoot);\n}\n\n/**\n * Scaffold the SERVER-SIDE PR gate: the CI workflow plus the doc explaining how to turn it on.\n *\n * This lives in the installer, not the PR flow. `wp-start-upsert-pr` used to do it — printing\n * copy-to-`.github` and branch-protection instructions on EVERY run, at an agent doing feature work\n * that could not act on them anyway (marking a check required needs a repo admin). Setup is a\n * one-time, admin-shaped act, so it belongs with the other one-time setup.\n *\n * Written UNCONDITIONALLY, unlike the old version which required a `gateSalt` to already be set: the\n * whole point of the doc is to tell you to set one, so gating it on the thing it teaches meant the\n * instructions only appeared to repos that no longer needed them.\n *\n * Both land in gitignored `.webpieces/instruct-ai/`, never `.github/` directly — writing there would\n * dirty the tree, and copying it is the human's decision. `IfMissing` for the yml so a repo that has\n * customized its workflow never gets it clobbered; the doc itself is refreshed so it cannot go stale.\n */\n// webpieces-disable no-function-outside-class -- setup.ts is deliberately DI-free (it must run on a half-written node_modules; see install-entry.ts), so every function here is module-scope\nfunction scaffoldCiGate(projectRoot: string): void {\n writeTemplateIfMissing(projectRoot, 'webpieces-pr-gate.yml');\n writeTemplate(projectRoot, 'webpieces.ci-gate-setup.md');\n console.log('');\n console.log('ℹ️ Optional: server-side PR gate (stops an UNHOOKED teammate opening a PR in the web UI).');\n console.log(' It is OFF until you set a gateSalt. Three steps, one of which needs a repo admin:');\n console.log(' .webpieces/instruct-ai/webpieces.ci-gate-setup.md');\n}\n\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nexport async function main(): Promise<void> {\n const args = process.argv.slice(2);\n // Anchor the install at the repo root (git toplevel — webpieces.config.json may not exist yet on\n // a first install), never a subdir cwd, so `.webpieces`/hooks/config all land at the root.\n const projectRoot = new RepoRootFinder().resolveRepoRoot(process.cwd());\n\n // Always refreshed: it explains why a retired key is rejected rather than accepted, and what to do\n // about it — which is exactly what an agent needs on the run where a migration just moved keys out\n // from under its config.\n writeTemplate(projectRoot, CONFIG_POLICY_DOC);\n seedOrSyncConfig(projectRoot);\n scaffoldCiGate(projectRoot);\n\n const targets = installTargets(projectRoot);\n\n // Non-interactive: `--target=project|project-personal|global|none` installs BOTH hooks at that\n // location without prompting, so an agent or CI can run the installer unattended (e.g. after a\n // @webpieces upgrade that changed the hook entry). Omit the flag for the interactive per-hook chooser.\n const targetName = parseTargetArg(args);\n if (targetName !== null) {\n const choice = resolveTargetChoice(targetName);\n if (choice === null) {\n console.error(`❌ Unknown --target '${targetName}'. Use one of: project | project-personal | global | none`);\n process.exitCode = 1;\n return;\n }\n applyChoice(RULES_HOOK, choice, targets, projectRoot);\n applyChoice(GUARDS_HOOK, choice, targets, projectRoot);\n console.log(`\\nDone. Both hooks set to: ${targetName}.`);\n reportCodexTrust(projectRoot, targets, choice);\n return;\n }\n\n console.log('');\n console.log('Two webpieces hooks can be installed independently — choose a location for each:');\n await wireHook(RULES_HOOK, targets, projectRoot);\n await wireHook(GUARDS_HOOK, targets, projectRoot);\n // Whichever choices were made above, report Codex trust for the project choice — an interactive run\n // that armed Codex needs the same warning the --target path prints.\n reportCodexTrust(projectRoot, targets, '1');\n console.log('');\n console.log('Done. Re-run `pnpm wp-install-ai-hooks` anytime to move or uninstall a hook.');\n console.log('(Non-interactive: pnpm wp-install-ai-hooks --target=project|project-personal|global|none)');\n}\n\nif (require.main === module) {\n void main();\n}\n"]}
1
+ {"version":3,"file":"setup.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/bin/setup.ts"],"names":[],"mappings":";;;AA8HA,wCAaC;AAMD,0BAGC;AAwBD,8BA0CC;AAyCD,kDAWC;AAID,wCAGC;AAUD,kCAOC;AA2CD,oBA2CC;;AAxXD,+CAAyB;AACzB,mDAA6B;AAC7B,2BAA6B;AAC7B,uCAA2C;AAE3C,0DAAmH;AAEnH,iCAA2D;AAC3D,qDAA6E;AAC7E,2DAA6M;AAE7M,+CAAqE;AACrE,+CAAgD;AAChD,uGAAuG;AACvG,yFAAyF;AACzF,iDAAkD;AAGlD,8EAA8E;AAC9E,iGAAiG;AACjG,kGAAkG;AAClG,wGAAwG;AACxG,oGAAoG;AACpG,6EAA6E;AAC7E,8EAA8E;AAC9E,MAAM,QAAQ;IAEG;IACA;IACA;IAHb,YACa,GAAW,EACX,KAAa,EACb,GAAW;QAFX,QAAG,GAAH,GAAG,CAAQ;QACX,UAAK,GAAL,KAAK,CAAQ;QACb,QAAG,GAAH,GAAG,CAAQ;IACrB,CAAC;IAEJ;;;;;;;OAOG;IACH,UAAU,CAAC,MAAqB;QAC5B,OAAO,MAAM,CAAC,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC/C,CAAC;IAED,6FAA6F;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QACvD,OAAO,CAAC,GAAG,CAAC,8BAA8B,UAAU,GAAG,CAAC,CAAC;QACzD,gBAAgB,CAAC,WAAW,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;QAC/C,OAAO;IACX,CAAC;IAED,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IAChB,OAAO,CAAC,GAAG,CAAC,kFAAkF,CAAC,CAAC;IAChG,MAAM,QAAQ,CAAC,kBAAU,EAAE,OAAO,EAAE,WAAW,CAAC,CAAC;IACjD,MAAM,QAAQ,CAAC,mBAAW,EAAE,OAAO,EAAE,WAAW,CAAC,CAAC;IAClD,oGAAoG;IACpG,oEAAoE;IACpE,gBAAgB,CAAC,WAAW,EAAE,OAAO,EAAE,GAAG,CAAC,CAAC;IAC5C,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IAChB,OAAO,CAAC,GAAG,CAAC,8EAA8E,CAAC,CAAC;IAC5F,OAAO,CAAC,GAAG,CAAC,2FAA2F,CAAC,CAAC;AAC7G,CAAC;AAED,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;IAC1B,KAAK,IAAI,EAAE,CAAC;AAChB,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { homedir } from 'os';\nimport { createInterface } from 'readline';\n\nimport { RepoRootFinder, writeTemplate, writeTemplateIfMissing, CONFIG_POLICY_DOC } from '@webpieces/rules-config';\n\nimport { SHIM_MARKER, shimPath, renderShim } from './shim';\nimport { REVIEWER_AGENT_MARKER, writeReviewerAgent } from './reviewer-agent';\nimport { HookRegistrationEntry, GUARDS_BIN, RULES_BIN, addHookEntry, applyManagedEnv, readSettings, writeSettings, HarnessRegistration, CLAUDE_REGISTRATION, CODEX_REGISTRATION } from './hook-registration';\nimport type { ClaudeSettings, HookCommand, HookEntry } from './settings-shape';\nimport { BASH_CWD_ENV_KEY, BASH_CWD_ENV_VALUE } from './managed-env';\nimport { CodexTrustProbe } from './codex-trust';\n// The config half of the installer — seeding and migrating webpieces.config.json. Split for size along\n// the seam that was already there: this module is hook WIRING, that one is CONFIG SHAPE.\nimport { seedOrSyncConfig } from './setup-config';\n\n\n// ---------------------------------------------------------------------------\n// The two independently-installable GUARD hooks. Each can land in a different settings file (see\n// InstallTarget) so a team can ship the guards while a developer keeps the code-style rules local\n// while iterating. Both are registered ABSOLUTE via $CLAUDE_PROJECT_DIR, so the MAIN tree governs every\n// tree. There used to be a third — the L-1 hook, which existed only to keep a RELATIVE registration\n// resolvable; an absolute registration resolves from any cwd, so it is gone.\n// ---------------------------------------------------------------------------\nclass HookSpec {\n constructor(\n readonly key: string,\n readonly label: string,\n readonly bin: string,\n ) {}\n\n /**\n * WHICH TOOL NAMES this hook must see, in the harness the target belongs to.\n *\n * It is a lookup on the target rather than a field on the spec because the answer is not a property\n * of the hook: the rules hook matches `Write|Edit|MultiEdit` under Claude Code and `apply_patch`\n * under Codex, and a single stored matcher is exactly how `.codex/hooks.json` came to be registered\n * against tool names Codex never emits.\n */\n matcherFor(target: InstallTarget): string {\n return target.harness.matcherFor(this.bin);\n }\n\n // Absolute targets (global) need the exact path to this repo's bin — no ~/.webpieces bridge.\n // Project targets get the ABSOLUTE shim command, anchored on the harness's own project-root variable\n // (see HarnessRegistration.shimCommand): it resolves from ANY cwd, so a hook can never fail to\n // launch — which per the hooks reference would be exit 127, a SILENT UNGUARDED ALLOW, not a block.\n commandFor(target: InstallTarget, projectRoot: string): string {\n if (target.absolute) {\n return `node ${path.join(projectRoot, 'node_modules', '.bin', this.bin)}`;\n }\n return target.harness.shimCommand(this.bin);\n }\n}\n\n// Idempotent: re-running the installer overwrites the managed shim in place.\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nfunction writeShim(projectRoot: string): void {\n const target = shimPath(projectRoot);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, renderShim(), { mode: 0o755 });\n // writeFileSync's mode is only applied when creating the file; force it on overwrite too.\n fs.chmodSync(target, 0o755);\n}\n\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nfunction removeShim(projectRoot: string): void {\n const target = shimPath(projectRoot);\n if (fs.existsSync(target)) fs.rmSync(target);\n}\n\n// A managed .sh is shared by the project hooks — only safe to delete once no project settings file\n// references it anymore (i.e. the other hook was moved to global or uninstalled too).\n// webpieces-disable no-function-outside-class -- setup.ts is deliberately DI-free (it must run on a half-written node_modules; see install-entry.ts), so every function here is module-scope\nfunction markerReferenced(targets: InstallTarget[], marker: string): boolean {\n return targets.some((t: InstallTarget) => {\n const entries = readSettings(t.settingsPath).hooks?.PreToolUse ?? [];\n return entries.some((e: HookEntry) => e.hooks.some((h: HookCommand) => h.command.includes(marker)));\n });\n}\n\nexport class InstallTarget {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n readonly choice: string,\n readonly label: string,\n readonly settingsPath: string,\n readonly absolute: boolean,\n /**\n * WHICH HARNESS this file arms — it decides the matcher and the shim anchor written into it.\n *\n * REQUIRED, with no default, and the absence of one is the point. A default of\n * CLAUDE_REGISTRATION would make \"omit the harness\" mean \"Claude Code\" — a widening that is an\n * ABSENCE rather than a token, so a target built for Codex without it would silently carry\n * `Write|Edit|MultiEdit` and `$CLAUDE_PROJECT_DIR`, which is EXACTLY the silently-unguarded\n * state this class exists to end, and ungreppable besides.\n */\n readonly harness: HarnessRegistration,\n ) {}\n}\n\n// The bin names come from ./hook-registration, which is also what the drift check and wp-upgrade-shim\n// compare against — one spelling of the registration, or the installer and the validator can disagree\n// about what \"installed\" means. The MATCHER is not here: it belongs to the harness, not the hook (see\n// HookSpec.matcherFor).\nexport const RULES_HOOK = new HookSpec('rules', 'Rules hook (code-style validation)', RULES_BIN);\nexport const GUARDS_HOOK = new HookSpec('guards', 'Guards hook (git/PR/branch protection)', GUARDS_BIN);\n\n/**\n * Every file the installer can write, keyed by the CHOICE a human makes.\n *\n * TWO TARGETS SHARE CHOICE `1`, and that is the design rather than an oversight: \"the project, committed,\n * for the team\" is ONE intention, and a repo that is worked on by both harnesses needs both files armed\n * to mean it. Splitting it into two questions would let a human answer them differently and end up with a\n * repo where Codex is silently unguarded — which is the state this whole change exists to end. Every\n * caller selects by choice id (`targets.filter(t => t.choice === answer)`), never by index, so adding a\n * harness adds a row and changes no numbering.\n *\n * `2` (personal) and `3` (global) stay Claude-only because neither has a Codex counterpart: Codex reads\n * one repo-local `hooks.json` and has no personal or home-scoped hook file.\n *\n * `homeDir` is injectable so tests can point the global target at a temp dir instead of the real\n * ~/.claude/settings.json (a unit test must never write the user's actual global settings).\n */\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nexport function installTargets(projectRoot: string, homeDir: string = homedir()): InstallTarget[] {\n return [\n new InstallTarget('1', 'project (.claude/settings.json — committed, for the team)',\n path.join(projectRoot, '.claude', 'settings.json'), false, CLAUDE_REGISTRATION),\n new InstallTarget('2', 'project for you (.claude/settings.local.json — personal)',\n path.join(projectRoot, '.claude', 'settings.local.json'), false, CLAUDE_REGISTRATION),\n new InstallTarget('3', 'global (~/.claude/settings.json — exact path, this repo only)',\n path.join(homeDir, '.claude', 'settings.json'), true, CLAUDE_REGISTRATION),\n // Given choice `1` so one answer arms the whole project — see the docblock. Its position in the\n // array carries no meaning: every caller selects by choice id.\n new InstallTarget('1', 'project, for Codex too (.codex/hooks.json — committed, for the team)',\n path.join(projectRoot, ...CODEX_REGISTRATION.settingsFiles[0].split('/')), false, CODEX_REGISTRATION),\n ];\n}\n\n// ---------------------------------------------------------------------------\n// Claude Code settings.json hook wiring.\n// ---------------------------------------------------------------------------\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nexport function hasHook(settings: ClaudeSettings, bin: string): boolean {\n const entries = settings.hooks?.PreToolUse ?? [];\n return entries.some((e: HookEntry) => e.hooks.some((h: HookCommand) => h.command.includes(bin)));\n}\n\n// Drop every PreToolUse command containing `marker` (a bin name, or a managed .sh path); returns true\n// if anything was removed. REMOVE-then-ADD is what keeps an upgrade from leaving a superseded spelling\n// (a relative command) beside the current one — two spellings of one\n// registration is the compatibility shim the backwards-compat reviewer rejects.\n// webpieces-disable no-function-outside-class -- setup.ts is deliberately DI-free (it must run on a half-written node_modules; see install-entry.ts), so every function here is module-scope\nfunction removeHookByMarker(settings: ClaudeSettings, marker: string): boolean {\n const entries = settings.hooks?.PreToolUse;\n if (!entries) return false;\n let changed = false;\n const kept: HookEntry[] = [];\n for (const entry of entries) {\n const hooks = entry.hooks.filter((h: HookCommand) => !h.command.includes(marker));\n if (hooks.length !== entry.hooks.length) changed = true;\n if (hooks.length > 0) kept.push({ matcher: entry.matcher, hooks });\n }\n if (changed) settings.hooks!.PreToolUse = kept;\n return changed;\n}\n\n// Apply the chosen install for one hook: remove it from every target file, then add it back to the\n// chosen one (or nowhere, for uninstall). Writes only the files that changed.\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nexport function applyHook(hook: HookSpec, chosen: InstallTarget | null, targets: InstallTarget[], projectRoot: string): void {\n // SCOPED TO THE CHOSEN HARNESS, and this is what makes one call per target composable. Installing\n // the Claude hook must not strip the Codex one, so \"remove it from everywhere else\" means everywhere\n // else THIS HARNESS could live. Uninstall (chosen === null) is the one case that means every\n // harness, because \"not installed\" has to be true everywhere or the hook is still armed somewhere.\n const scope = chosen === null ? targets : targets.filter((t: InstallTarget) => t.harness === chosen.harness);\n for (const target of scope) {\n const settings = readSettings(target.settingsPath);\n const removed = removeHookByMarker(settings, hook.bin);\n const isChosen = chosen !== null && chosen.settingsPath === target.settingsPath;\n if (isChosen) {\n addHookEntry(settings, new HookRegistrationEntry(hook.matcherFor(target), hook.commandFor(target, projectRoot)));\n // The managed `env` entry goes into the SAME file the hooks go into, on every path that\n // writes hooks — interactive or `--target=`. It pins the Bash cwd to the project root, so a\n // guard's answer depends on the command rather than on where an earlier `cd` left the shell,\n // and settings `env` is inherited, so every subagent gets the identical cwd and therefore the\n // identical guard verdict. (It no longer has a RESOLUTION job — the hooks are absolute.) See\n // hook-registration.ts for the full argument; `wp-upgrade-shim` self-heals it afterwards.\n // …in the harness that HAS that surface. Codex has no settings `env`, and needs none: its\n // cwd is MEASURED not to drift, which is the whole thing this entry buys under Claude Code.\n if (target.harness.managesEnv && applyManagedEnv(settings)) {\n console.log(` ✅ env.${BASH_CWD_ENV_KEY}=${BASH_CWD_ENV_VALUE} → ${target.label} (pins the Bash cwd to the project root, for this session and every subagent)`);\n }\n writeSettings(target.settingsPath, settings);\n console.log(` ✅ ${hook.label} → ${target.label}`);\n } else if (removed) {\n writeSettings(target.settingsPath, settings);\n }\n }\n // Manage the shared checked-in shim: (re)write it whenever a project (relative) install exists,\n // otherwise clean it up once neither hook references it anymore.\n if (chosen !== null && !chosen.absolute) {\n writeShim(projectRoot);\n // The generic PR-gate reviewer agent is part of the same committed, managed set as the shim — the\n // drift check reports it beside the shim, so the installer writes it beside the shim.\n if (writeReviewerAgent(projectRoot)) {\n console.log(` ✅ ${REVIEWER_AGENT_MARKER} (the generic PR-gate reviewer; generated — commit it, do not edit it)`);\n }\n } else if (!markerReferenced(targets, SHIM_MARKER)) {\n removeShim(projectRoot);\n }\n if (chosen === null) console.log(` ⛔ ${hook.label} not installed (removed from all locations).`);\n}\n\n/**\n * Say whether Codex will actually RUN what we just registered — the one thing the installer cannot do\n * anything about and therefore must not leave silent.\n *\n * Codex trusts a hook entry TOFU and re-prompts whenever its bytes change, and the prompt's third option\n * is \"Continue without trusting (hooks won't run)\". So a perfectly successful install can be followed by\n * a fully unguarded session, and the only honest thing to print is what is true plus the one action a\n * HUMAN has to take. Nothing here writes `~/.codex/config.toml` — see codex-trust.ts for why forging a\n * `trusted_hash` is not on the table.\n *\n * Silent when this repo did not arm Codex, so a Claude-only install gains no noise.\n */\n// webpieces-disable no-function-outside-class -- setup.ts is deliberately DI-free (it must run on a half-written node_modules; see install-entry.ts), so every function here is module-scope\nfunction reportCodexTrust(projectRoot: string, targets: InstallTarget[], choice: string): void {\n const armed = targets.some((t: InstallTarget): boolean => t.choice === choice && t.harness === CODEX_REGISTRATION);\n if (!armed) return;\n const lines = new CodexTrustProbe().read(projectRoot).lines();\n if (lines.length === 0) return;\n console.log('');\n for (const line of lines) console.log(line);\n}\n\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nfunction currentLocation(hook: HookSpec, targets: InstallTarget[]): string {\n const here = targets.filter((t: InstallTarget) => hasHook(readSettings(t.settingsPath), hook.bin));\n return here.length === 0 ? 'none' : here.map((t: InstallTarget) => t.label.split(' (')[0]).join(', ');\n}\n\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nfunction prompt(question: string): Promise<string> {\n return new Promise((resolve: (answer: string) => void) => {\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n rl.question(question, (answer: string) => { rl.close(); resolve(answer.trim()); });\n });\n}\n\n// Map a friendly `--target` name to an InstallTarget choice id (see installTargets). Returns null\n// for an unknown name so the caller can error out. Kept separate + exported for unit testing.\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nexport function resolveTargetChoice(name: string): string | null {\n switch (name) {\n case 'project': return '1';\n case 'project-personal':\n case 'projectpersonal':\n case 'local': return '2';\n case 'global': return '3';\n case 'none':\n case 'uninstall': return '4';\n default: return null;\n }\n}\n\n// Extract the value of `--target=<name>` from argv (null if the flag is absent).\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nexport function parseTargetArg(args: string[]): string | null {\n const flag = args.find((a: string): boolean => a.startsWith('--target='));\n return flag ? flag.slice('--target='.length) : null;\n}\n\n/**\n * Apply ONE choice for one hook: every target that answer selects, or uninstall when it selects none.\n *\n * The loop is what lets one choice arm several harnesses (choice `1` writes both the Claude settings\n * file and the Codex hooks file — see installTargets). `applyHook` scopes its removals to the chosen\n * target's harness, which is what keeps these calls from undoing one another.\n */\n// webpieces-disable no-function-outside-class -- setup.ts is deliberately DI-free (it must run on a half-written node_modules; see install-entry.ts), so every function here is module-scope\nexport function applyChoice(hook: HookSpec, choice: string, targets: InstallTarget[], projectRoot: string): void {\n const chosen = targets.filter((t: InstallTarget): boolean => t.choice === choice);\n if (chosen.length === 0) {\n applyHook(hook, null, targets, projectRoot);\n return;\n }\n for (const target of chosen) applyHook(hook, target, targets, projectRoot);\n}\n\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nasync function wireHook(hook: HookSpec, targets: InstallTarget[], projectRoot: string): Promise<void> {\n console.log('');\n console.log(`${hook.label}`);\n console.log(` currently installed in: ${currentLocation(hook, targets)}`);\n // The matcher is printed PER TARGET now, because it differs per harness — Codex's file tool is\n // `apply_patch`, Claude's are Write|Edit|MultiEdit — and one matcher printed above the list would be\n // wrong for whichever harness it did not describe.\n for (const target of targets) console.log(` ${target.choice}) ${target.label} [matcher: ${hook.matcherFor(target)}]`);\n console.log(' 4) none / uninstall');\n const answer = await prompt(' Where should it live? [1/2/3/4, default 4]: ');\n applyChoice(hook, answer, targets, projectRoot);\n}\n\n/**\n * Scaffold the SERVER-SIDE PR gate: the CI workflow plus the doc explaining how to turn it on.\n *\n * This lives in the installer, not the PR flow. `wp-start-upsert-pr` used to do it — printing\n * copy-to-`.github` and branch-protection instructions on EVERY run, at an agent doing feature work\n * that could not act on them anyway (marking a check required needs a repo admin). Setup is a\n * one-time, admin-shaped act, so it belongs with the other one-time setup.\n *\n * Written UNCONDITIONALLY, unlike the old version which required a `gateSalt` to already be set: the\n * whole point of the doc is to tell you to set one, so gating it on the thing it teaches meant the\n * instructions only appeared to repos that no longer needed them.\n *\n * Both land in gitignored `.webpieces/instruct-ai/`, never `.github/` directly — writing there would\n * dirty the tree, and copying it is the human's decision. `IfMissing` for the yml so a repo that has\n * customized its workflow never gets it clobbered; the doc itself is refreshed so it cannot go stale.\n */\n// webpieces-disable no-function-outside-class -- setup.ts is deliberately DI-free (it must run on a half-written node_modules; see install-entry.ts), so every function here is module-scope\nfunction scaffoldCiGate(projectRoot: string): void {\n writeTemplateIfMissing(projectRoot, 'webpieces-pr-gate.yml');\n writeTemplate(projectRoot, 'webpieces.ci-gate-setup.md');\n console.log('');\n console.log('ℹ️ Optional: server-side PR gate (stops an UNHOOKED teammate opening a PR in the web UI).');\n console.log(' It is OFF until you set a gateSalt. Three steps, one of which needs a repo admin:');\n console.log(' .webpieces/instruct-ai/webpieces.ci-gate-setup.md');\n}\n\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nexport async function main(): Promise<void> {\n const args = process.argv.slice(2);\n // Anchor the install at the repo root (git toplevel — webpieces.config.json may not exist yet on\n // a first install), never a subdir cwd, so `.webpieces`/hooks/config all land at the root.\n const projectRoot = new RepoRootFinder().resolveRepoRoot(process.cwd());\n\n // Always refreshed: it explains why a retired key is rejected rather than accepted, and what to do\n // about it — which is exactly what an agent needs on the run where a migration just moved keys out\n // from under its config.\n writeTemplate(projectRoot, CONFIG_POLICY_DOC);\n seedOrSyncConfig(projectRoot);\n scaffoldCiGate(projectRoot);\n\n const targets = installTargets(projectRoot);\n\n // Non-interactive: `--target=project|project-personal|global|none` installs BOTH hooks at that\n // location without prompting, so an agent or CI can run the installer unattended (e.g. after a\n // @webpieces upgrade that changed the hook entry). Omit the flag for the interactive per-hook chooser.\n const targetName = parseTargetArg(args);\n if (targetName !== null) {\n const choice = resolveTargetChoice(targetName);\n if (choice === null) {\n console.error(`❌ Unknown --target '${targetName}'. Use one of: project | project-personal | global | none`);\n process.exitCode = 1;\n return;\n }\n applyChoice(RULES_HOOK, choice, targets, projectRoot);\n applyChoice(GUARDS_HOOK, choice, targets, projectRoot);\n console.log(`\\nDone. Both hooks set to: ${targetName}.`);\n reportCodexTrust(projectRoot, targets, choice);\n return;\n }\n\n console.log('');\n console.log('Two webpieces hooks can be installed independently — choose a location for each:');\n await wireHook(RULES_HOOK, targets, projectRoot);\n await wireHook(GUARDS_HOOK, targets, projectRoot);\n // Whichever choices were made above, report Codex trust for the project choice — an interactive run\n // that armed Codex needs the same warning the --target path prints.\n reportCodexTrust(projectRoot, targets, '1');\n console.log('');\n console.log('Done. Re-run `pnpm wp-install-ai-hooks` anytime to move or uninstall a hook.');\n console.log('(Non-interactive: pnpm wp-install-ai-hooks --target=project|project-personal|global|none)');\n}\n\nif (require.main === module) {\n void main();\n}\n"]}
@@ -42,7 +42,7 @@ const to_error_1 = require("@webpieces/tooling-common/to-error");
42
42
  // generated file with the same contract as the shim; see reviewer-agent.ts
43
43
  //
44
44
  // WHAT IT DELIBERATELY DOES *NOT* DO: sweep this tree's dangling `node_modules/.bin/wp-*` symlinks. That
45
- // is the same class of defect as the retired-file removal below — an entry pointing at a missing file is
45
+ // is a real defect — an entry pointing at a missing file is
46
46
  // worse than absence, because `ls node_modules/.bin` advertises a capability that only fails on execution
47
47
  // — and it WOULD read naturally here. It is not here because the one implementation of that sweep lives in
48
48
  // `@webpieces/rules-config` (`stale-bin-sweep.ts`), which this module may not import: the barrel pulls in
@@ -55,13 +55,6 @@ const to_error_1 = require("@webpieces/tooling-common/to-error");
55
55
  // `.webpieces/instruct-ai/*`, so ANY `wp-*` command heals the tree — including the `pnpm install` +
56
56
  // `pnpm exec wp-upgrade-shim` sequence this bin's own advice ends with.
57
57
  //
58
- // It also DELETES the retired `.claude/webpieces/guarantee-root.sh` and any settings entry still naming
59
- // it. That file was the L-1 hook, which existed only to guarantee the once-RELATIVE shim path resolved;
60
- // an absolute path resolves from any cwd, so it has no job left. Removing the file without removing the
61
- // entry (or vice versa) is the worst possible half-state — a registered hook pointing at a missing file
62
- // exits 127, which per the hooks reference is a NON-BLOCKING error, i.e. a SILENT UNGUARDED ALLOW — so
63
- // both happen here, file first.
64
- //
65
58
  // A cure that fixes some of them is worse than no cure, because it reports success. This bin is the
66
59
  // sanctioned cure named in fault S's message and is on the L0 allowlist, so it must repair everything.
67
60
  //
@@ -89,20 +82,12 @@ function runUpgradeShim(cwd) {
89
82
  fs.writeFileSync(target, (0, shim_1.renderShim)(), { mode: 0o755 });
90
83
  // writeFileSync's mode only applies on create; force it on overwrite too (matches writeShim).
91
84
  fs.chmodSync(target, 0o755);
92
- // ORDER MATTERS, and it is registration-FIRST. The reverse leaves a window in which a settings
93
- // entry still names a file that is gone — exit 127, which the hooks reference defines as a
94
- // NON-BLOCKING error, i.e. a SILENT UNGUARDED ALLOW. This way round the transient state is an
95
- // ORPHANED FILE that nothing references, which is inert. (An earlier draft of this function
96
- // argued file-first was safer; it is not. repairRegistration() also early-returns when the file
97
- // registers no guard bins, and the retired H1 command contains neither bin name, so a
98
- // guarantee-root-ONLY settings file would have lost the file and kept the entry.)
99
85
  const repairs = (0, hook_registration_1.repairRegistrationAt)(root);
100
- const removedLegacy = removeRetiredGuaranteeRoot(root);
101
86
  // The generic PR-gate reviewer agent — a managed file like the shim, so the one cure rewrites it too.
102
87
  if ((0, reviewer_agent_1.writeReviewerAgent)(root)) {
103
88
  console.log(`✅ @webpieces: wrote the generic PR-gate reviewer agent ${reviewer_agent_1.REVIEWER_AGENT_MARKER} (generated — commit it, do not edit it).`);
104
89
  }
105
- reportRepairs(target, removedLegacy, repairs);
90
+ reportRepairs(target, repairs);
106
91
  // ADVISORY ONLY, and deliberately after the ✅ lines: it never touches the exit code (see
107
92
  // reportTreeDivergence).
108
93
  reportTreeDivergence(root);
@@ -124,40 +109,15 @@ function runUpgradeShim(cwd) {
124
109
  * the only thing missing would be the same class of dishonesty one level down.
125
110
  */
126
111
  // webpieces-disable no-function-outside-class -- sibling of runUpgradeShim in this deliberately dependency-free bin module
127
- /**
128
- * Delete the RETIRED L-1 hook file, returning whether there was one. Removal-only, one way, no writer.
129
- *
130
- * This runs AFTER repairRegistrationAt(), which strips the stale H1 ENTRY from settings.json. Removing
131
- * the entry first means the file is merely orphaned in between — inert, because nothing references it.
132
- * File-first would instead leave a registered hook pointing at a missing file, and per the hooks
133
- * reference a non-2 non-zero exit is a NON-BLOCKING error: every `cd` would go unjudged.
134
- */
135
- // webpieces-disable no-function-outside-class -- module-scope like every other helper in this bin, which must load on a tree too broken to build a DI container
136
- function removeRetiredGuaranteeRoot(root) {
137
- // The path comes from LEGACY_GUARANTEE_ROOT_MARKER, never re-spelled here: a second literal is a
138
- // second spelling, and when the expiry in hook-registration.ts fires the documented removal would
139
- // miss this copy and the dead name would survive in a file nobody thought to grep.
140
- const legacy = path.join(root, hook_registration_1.LEGACY_GUARANTEE_ROOT_MARKER);
141
- if (!fs.existsSync(legacy))
142
- return false;
143
- fs.rmSync(legacy, { force: true });
144
- return true;
145
- }
146
- // webpieces-disable no-function-outside-class -- module-scope like every other helper in this bin, which must load on a tree too broken to build a DI container
147
- function reportRepairs(shimFile, removedLegacy, repairs) {
112
+ function reportRepairs(shimFile, repairs) {
148
113
  console.log(`✅ @webpieces: regenerated the managed shim at ${shimFile} — tool calls are re-armed.`);
149
- if (removedLegacy) {
150
- console.log('✅ @webpieces: deleted the RETIRED L-1 hook .claude/webpieces/guarantee-root.sh.');
151
- console.log(' The guard hooks are ABSOLUTE now, so the launch guarantee it provided is structural.');
152
- }
153
114
  if (repairs.length === 0) {
154
115
  console.log(' .claude/settings.json (hook registration + managed env) already matches this release — no change.');
155
116
  }
156
117
  for (const repair of repairs) {
157
118
  if (repair.registration) {
158
119
  console.log(`✅ @webpieces: rewrote the hook registration in ${repair.settingsPath} to the two-hook form`);
159
- console.log(' (both guard hooks ABSOLUTE via $CLAUDE_PROJECT_DIR, so the MAIN tree governs every tree;');
160
- console.log(' any retired guarantee-root.sh entry was removed).');
120
+ console.log(' (both guard hooks ABSOLUTE via $CLAUDE_PROJECT_DIR, so the MAIN tree governs every tree).');
161
121
  }
162
122
  for (const command of repair.anchoredNeighbours) {
163
123
  console.log(`✅ @webpieces: anchored a RELATIVE hook command in ${repair.settingsPath} so it resolves from any cwd`);
@@ -1 +1 @@
1
- {"version":3,"file":"upgrade-shim.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/bin/upgrade-shim.ts"],"names":[],"mappings":";;;AA0EA,wCAsCC;AAqKD,oBAEC;;AAtRD,mFAA+E;AAC/E,+CAAyB;AACzB,mDAA6B;AAE7B,iCAA4D;AAC5D,qDAA6E;AAC7E,2DAA8H;AAC9H,+CAAqE;AACrE,iEAA6D;AAE7D,8EAA8E;AAC9E,qGAAqG;AACrG,EAAE;AACF,oGAAoG;AACpG,uGAAuG;AACvG,mGAAmG;AACnG,gFAAgF;AAChF,EAAE;AACF,wGAAwG;AACxG,2FAA2F;AAC3F,qDAAqD;AACrD,sGAAsG;AACtG,yGAAyG;AACzG,iDAAiD;AACjD,mGAAmG;AACnG,mGAAmG;AACnG,qGAAqG;AACrG,mGAAmG;AACnG,sGAAsG;AACtG,sGAAsG;AACtG,oGAAoG;AACpG,0BAA0B;AAC1B,wGAAwG;AACxG,wGAAwG;AACxG,wGAAwG;AACxG,yEAAyE;AACzE,4GAA4G;AAC5G,gFAAgF;AAChF,EAAE;AACF,yGAAyG;AACzG,yGAAyG;AACzG,0GAA0G;AAC1G,2GAA2G;AAC3G,0GAA0G;AAC1G,2GAA2G;AAC3G,kGAAkG;AAClG,yGAAyG;AACzG,wFAAwF;AACxF,EAAE;AACF,wFAAwF;AACxF,oGAAoG;AACpG,wEAAwE;AACxE,EAAE;AACF,wGAAwG;AACxG,wGAAwG;AACxG,wGAAwG;AACxG,wGAAwG;AACxG,uGAAuG;AACvG,gCAAgC;AAChC,EAAE;AACF,oGAAoG;AACpG,uGAAuG;AACvG,EAAE;AACF,kFAAkF;AAClF,sGAAsG;AACtG,8EAA8E;AAC9E,8EAA8E;AAC9E,MAAM,GAAG,GAAG,QAAQ,CAAC;AACrB,MAAM,KAAK,GAAG,KAAK,CAAC;AAEpB,yGAAyG;AACzG,yBAAyB;AACzB,uRAAuR;A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qCAAqC,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,KAAK,EAAE,CAAC,CAAC;IACrJ,OAAO,CAAC,KAAK,CAAC,uFAAuF,IAAI,wEAAwE,CAAC,CAAC;IACnL,OAAO,CAAC,CAAC;AACb,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,yHAAyH;AACzH,SAAgB,IAAI;IAChB,OAAO,CAAC,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;AAChD,CAAC;AAED,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;IAC1B,IAAI,EAAE,CAAC;AACX,CAAC","sourcesContent":["#!/usr/bin/env node\nimport { RepositoryLayout } from '@webpieces/tooling-common/repository-layout';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nimport { renderShim, shimPath, findShimRoot } from './shim';\nimport { REVIEWER_AGENT_MARKER, writeReviewerAgent } from './reviewer-agent';\nimport { repairRegistrationAt, managedSurfaceDrift, SettingsRepair, LEGACY_GUARANTEE_ROOT_MARKER } from './hook-registration';\nimport { BASH_CWD_ENV_KEY, BASH_CWD_ENV_VALUE } from './managed-env';\nimport { toError } from '@webpieces/tooling-common/to-error';\n\n// ---------------------------------------------------------------------------\n// The `wp-upgrade-shim` entry point — the CURE for the managed-hook-surface self-guard (L0 fault S).\n//\n// WHAT IT REPAIRS, and why all of them (2026-08-07, extended). This used to write EXACTLY ONE FILE,\n// ai-hook.sh, and touch nothing else. That was correct while the installed surface WAS one file. It is\n// now five (the name `wp-upgrade-shim` is older than the job and is NOT renamed — a rename with no\n// functional change is a cost with no payer; the prose is what gets corrected):\n//\n// 1. .claude/webpieces/ai-hook.sh the ONE guard shim, shared by every harness and registered\n// ABSOLUTE, so the MAIN tree governs every tree\n// 2. the .claude/settings.json registration itself\n// 3. the .codex/hooks.json registration — the SAME two hooks under Codex's own matchers and its own\n// $PWD anchor. Repaired only where it already EXISTS: arming a harness is the installer's decision,\n// this is the cure for one that has drifted\n// 3b. the NEIGHBOUR hook commands in both of those files — the entries a CONSUMER repo registers\n// beside webpieces' own. A repo-RELATIVE entry path (`node \".claude/hooks/guard-deploy.mjs\"`)\n// resolves against the hook process's cwd, so it dies the moment that cwd is not the repo root,\n// and per the hooks reference that non-zero exit is a NON-BLOCKING error — a SILENT UNGUARDED\n// ALLOW. Measured in a consumer repo (issue #852) silently disarming three security guards while\n// printing nothing but a `node:internal/modules/cjs/loader` fragment with no rule name. They are\n// anchored to the harness's own prefix, the same reversal webpieces made for its own hook. See\n// neighbour-hooks.ts\n// 4. the .claude/settings.json `env` entry CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR=1, which pins the\n// Bash cwd to the project root — and, because settings `env` is inherited, pins it identically for\n// every subagent, so a verdict never depends on where an earlier `cd` left the shell. Claude-only:\n// Codex has no settings `env`, and its cwd is measured not to drift\n// 5. .claude/agents/webpieces-reviewer.md — the generic PR-gate reviewer agent (issue #938), a committed,\n// generated file with the same contract as the shim; see reviewer-agent.ts\n//\n// WHAT IT DELIBERATELY DOES *NOT* DO: sweep this tree's dangling `node_modules/.bin/wp-*` symlinks. That\n// is the same class of defect as the retired-file removal below — an entry pointing at a missing file is\n// worse than absence, because `ls node_modules/.bin` advertises a capability that only fails on execution\n// — and it WOULD read naturally here. It is not here because the one implementation of that sweep lives in\n// `@webpieces/rules-config` (`stale-bin-sweep.ts`), which this module may not import: the barrel pulls in\n// inversify and the config loader, and a subpath import resolves against the INSTALLED rules-config, which\n// is a release behind this source (see .claude/rules/published-vs-local-source.md) — so a spawned\n// `wp-upgrade-shim` would die on module resolution, in the one command an L0-blocked session has left. A\n// second copy of the sweep here would be a second spelling of it, which is worse again.\n//\n// It does not need to be here. The sweep rides the `wp-*` startup pass that regenerates\n// `.webpieces/instruct-ai/*`, so ANY `wp-*` command heals the tree — including the `pnpm install` +\n// `pnpm exec wp-upgrade-shim` sequence this bin's own advice ends with.\n//\n// It also DELETES the retired `.claude/webpieces/guarantee-root.sh` and any settings entry still naming\n// it. That file was the L-1 hook, which existed only to guarantee the once-RELATIVE shim path resolved;\n// an absolute path resolves from any cwd, so it has no job left. Removing the file without removing the\n// entry (or vice versa) is the worst possible half-state — a registered hook pointing at a missing file\n// exits 127, which per the hooks reference is a NON-BLOCKING error, i.e. a SILENT UNGUARDED ALLOW — so\n// both happen here, file first.\n//\n// A cure that fixes some of them is worse than no cure, because it reports success. This bin is the\n// sanctioned cure named in fault S's message and is on the L0 allowlist, so it must repair everything.\n//\n// Deliberately imports only ./shim and ./hook-registration (fs + path) + toError,\n// exactly like install-entry: the whole job is to rewrite webpieces-managed files, which never needed\n// the rule engine, and it must stay runnable on a tree too broken to load it.\n// ---------------------------------------------------------------------------\nconst RED = '[31;1m';\nconst RESET = '[0m';\n\n// Returns the process exit code (0 = ok). Kept as a function (not top-level code) so it is unit-testable\n// without spawning node.\n// webpieces-disable no-function-outside-class -- bin entry point: this module MUST load with only fs+path (see header), mirroring install-entry.ts. A DI-managed class would pull the container in and reintroduce the require-time crash this dependency-free path exists to survive.\nexport function runUpgradeShim(cwd: string): number {\n const root = findShimRoot(cwd);\n if (root === null) {\n console.error(`${RED}🛑 @webpieces: no committed .claude/webpieces/ai-hook.sh found to regenerate.${RESET}`);\n console.error(' Run this from a repo that installs @webpieces/agent-workflow-rules, or run the installer (pnpm wp-install-ai-hooks).');\n return 1;\n }\n const target = shimPath(root);\n // webpieces-disable no-unmanaged-exceptions -- bin entry chokepoint: turn an fs error into an actionable line + non-zero exit rather than a raw node trace; there is no caller above a bin to handle it.\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n new RepositoryLayout().migrate(root);\n fs.writeFileSync(target, renderShim(), { mode: 0o755 });\n // writeFileSync's mode only applies on create; force it on overwrite too (matches writeShim).\n fs.chmodSync(target, 0o755);\n // ORDER MATTERS, and it is registration-FIRST. The reverse leaves a window in which a settings\n // entry still names a file that is gone — exit 127, which the hooks reference defines as a\n // NON-BLOCKING error, i.e. a SILENT UNGUARDED ALLOW. This way round the transient state is an\n // ORPHANED FILE that nothing references, which is inert. (An earlier draft of this function\n // argued file-first was safer; it is not. repairRegistration() also early-returns when the file\n // registers no guard bins, and the retired H1 command contains neither bin name, so a\n // guarantee-root-ONLY settings file would have lost the file and kept the entry.)\n const repairs = repairRegistrationAt(root);\n const removedLegacy = removeRetiredGuaranteeRoot(root);\n // The generic PR-gate reviewer agent — a managed file like the shim, so the one cure rewrites it too.\n if (writeReviewerAgent(root)) {\n console.log(`✅ @webpieces: wrote the generic PR-gate reviewer agent ${REVIEWER_AGENT_MARKER} (generated — commit it, do not edit it).`);\n }\n reportRepairs(target, removedLegacy, repairs);\n // ADVISORY ONLY, and deliberately after the ✅ lines: it never touches the exit code (see\n // reportTreeDivergence).\n reportTreeDivergence(root);\n return verifyRepaired(root);\n } catch (err: unknown) {\n const error = toError(err);\n console.error(`${RED}🛑 @webpieces: could not write under ${root}: ${error.message}${RESET}`);\n return 1;\n }\n}\n\n/**\n * Say what was actually done, per managed thing. The old single line (\"regenerated the managed shim\")\n * would now be a lie by omission on the three most important repairs — and an agent reading a cure's\n * output is how it decides whether the cure worked.\n *\n * Each settings file reports the repairs IT needed, from the flags recorded before the rewrite. Printing\n * \"rewrote the hook registration\" for a file whose hooks were already current and whose `env` entry was\n * the only thing missing would be the same class of dishonesty one level down.\n */\n// webpieces-disable no-function-outside-class -- sibling of runUpgradeShim in this deliberately dependency-free bin module\n/**\n * Delete the RETIRED L-1 hook file, returning whether there was one. Removal-only, one way, no writer.\n *\n * This runs AFTER repairRegistrationAt(), which strips the stale H1 ENTRY from settings.json. Removing\n * the entry first means the file is merely orphaned in between — inert, because nothing references it.\n * File-first would instead leave a registered hook pointing at a missing file, and per the hooks\n * reference a non-2 non-zero exit is a NON-BLOCKING error: every `cd` would go unjudged.\n */\n// webpieces-disable no-function-outside-class -- module-scope like every other helper in this bin, which must load on a tree too broken to build a DI container\nfunction removeRetiredGuaranteeRoot(root: string): boolean {\n // The path comes from LEGACY_GUARANTEE_ROOT_MARKER, never re-spelled here: a second literal is a\n // second spelling, and when the expiry in hook-registration.ts fires the documented removal would\n // miss this copy and the dead name would survive in a file nobody thought to grep.\n const legacy = path.join(root, LEGACY_GUARANTEE_ROOT_MARKER);\n if (!fs.existsSync(legacy)) return false;\n fs.rmSync(legacy, { force: true });\n return true;\n}\n\n// webpieces-disable no-function-outside-class -- module-scope like every other helper in this bin, which must load on a tree too broken to build a DI container\nfunction reportRepairs(shimFile: string, removedLegacy: boolean, repairs: readonly SettingsRepair[]): void {\n console.log(`✅ @webpieces: regenerated the managed shim at ${shimFile} — tool calls are re-armed.`);\n if (removedLegacy) {\n console.log('✅ @webpieces: deleted the RETIRED L-1 hook .claude/webpieces/guarantee-root.sh.');\n console.log(' The guard hooks are ABSOLUTE now, so the launch guarantee it provided is structural.');\n }\n if (repairs.length === 0) {\n console.log(' .claude/settings.json (hook registration + managed env) already matches this release — no change.');\n }\n for (const repair of repairs) {\n if (repair.registration) {\n console.log(`✅ @webpieces: rewrote the hook registration in ${repair.settingsPath} to the two-hook form`);\n console.log(' (both guard hooks ABSOLUTE via $CLAUDE_PROJECT_DIR, so the MAIN tree governs every tree;');\n console.log(' any retired guarantee-root.sh entry was removed).');\n }\n for (const command of repair.anchoredNeighbours) {\n console.log(`✅ @webpieces: anchored a RELATIVE hook command in ${repair.settingsPath} so it resolves from any cwd`);\n console.log(` now: ${command}`);\n console.log(' (a relative entry path resolves against the hook process cwd; off the repo root it fails to load, and');\n console.log(' per the hooks reference that non-zero exit is NON-BLOCKING — the guard silently stops guarding.)');\n }\n if (repair.env) {\n console.log(`✅ @webpieces: set env.${BASH_CWD_ENV_KEY}=${BASH_CWD_ENV_VALUE} in ${repair.settingsPath}`);\n console.log(' (pins the Bash cwd to the project root, so the guard hooks resolve identically for every subagent — for');\n console.log(' this session and, because settings env is inherited, for every subagent it spawns).');\n }\n }\n console.log(' These files are generated + committed by webpieces; do not revert or hand-edit them.');\n}\n\n/**\n * WAS THE REPAIRED TREE THE TREE THE HOOKS LAUNCH FROM — the second way this cure can report success\n * while changing nothing the session is actually governed by.\n *\n * H1 is registered ABSOLUTE, `sh \"$CLAUDE_PROJECT_DIR/…\"`, and `$CLAUDE_PROJECT_DIR` never moves off the\n * PRIMARY clone (the two-tree straddle recorded in shim.ts, and the whole reason H2/H3 are relative\n * while H1 is not). So repairing a LINKED WORKTREE leaves the running session still loading the\n * PRIMARY's files, the PRIMARY's binary and the PRIMARY's pin. Four green lines, and the block does not\n * lift. Nothing printed above is false — but the question the reader has (\"will the block lift?\") went\n * unanswered, which is the same failure this file's header exists to prevent, one level out.\n *\n * THE PREDICATE IS TREE DIVERGENCE, NOT \"am I a subagent\". There is no runtime subagent marker in the\n * hook environment to read, and divergence is the more accurate question anyway: a MAIN agent in a\n * linked worktree HAS this problem (a subagent test would miss it), and a SUBAGENT in the same tree does\n * NOT (a subagent test would cry wolf). Both paths are realpath'd before comparing — a worktree path can\n * arrive symlinked, and /tmp vs /private/tmp on darwin is a live case in this repo's own specs.\n *\n * SILENT when `$CLAUDE_PROJECT_DIR` is unset: a plain CLI run outside Claude Code has no second tree to\n * talk about. And ADVISORY always — it must never turn a verified repair into a failure, so it returns\n * nothing and `verifyRepaired()`'s contract (non-zero only when a surface in THIS tree still differs) is\n * untouched.\n */\n// webpieces-disable no-function-outside-class -- sibling of runUpgradeShim in this deliberately dependency-free bin module\nfunction reportTreeDivergence(root: string): void {\n const projectDir = process.env['CLAUDE_PROJECT_DIR'];\n if (projectDir === undefined || projectDir === '') return;\n if (sameTree(root, projectDir)) return;\n console.log('');\n console.log('⚠️ @webpieces: the tree just repaired is NOT the tree the hooks launch from.');\n console.log(` repaired: ${root}`);\n console.log(` CLAUDE_PROJECT_DIR: ${projectDir}`);\n console.log(' The hooks governing this session resolve through CLAUDE_PROJECT_DIR (H1 is registered');\n console.log(' absolute), so this repair has not changed what is currently enforcing — it made THIS');\n console.log(' tree correct for when its own branch is the one being judged, which is not wasted work.');\n console.log(' To change what is enforcing NOW, run the same repair in the primary tree, and install');\n console.log(' there too — the hooks execute the INSTALLED release, not this tree\\'s source:');\n console.log(` cd ${projectDir} && pnpm install && pnpm exec wp-upgrade-shim`);\n console.log(' Repaired in BOTH trees is the aligned end state, and running it twice is safe.');\n}\n\n/**\n * Do two paths name the same tree? realpath'd (symlinked worktrees, /tmp vs /private/tmp) and stripped\n * of a trailing separator before comparing. A path that cannot be realpath'd falls back to `resolve`,\n * so an absent CLAUDE_PROJECT_DIR directory reads as \"different\" rather than throwing inside a cure.\n */\n// webpieces-disable no-function-outside-class -- sibling of runUpgradeShim in this deliberately dependency-free bin module\nfunction sameTree(a: string, b: string): boolean {\n return canonicalTree(a) === canonicalTree(b);\n}\n\n// webpieces-disable no-function-outside-class -- sibling of runUpgradeShim in this deliberately dependency-free bin module\nfunction canonicalTree(dir: string): string {\n // webpieces-disable no-unmanaged-exceptions -- realpath throws on a path that does not exist; the fallback IS the handling, and an advisory notice must never crash the cure it annotates.\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return path.resolve(fs.realpathSync(dir));\n } catch (err: unknown) {\n const error = toError(err);\n void error; // best-effort: an unresolvable path simply compares as itself\n return path.resolve(dir);\n }\n}\n\n/**\n * DID THE CURE ACTUALLY CURE IT — asked of the same predicate the guard asks, not of our own writes.\n *\n * A cure that cannot fail loudly is worse than no cure. This bin used to print three ✅ lines and\n * return 0 the moment `writeFileSync` did not throw, which asserts only \"the bytes we chose were\n * written\", never \"the surface the guard measures now agrees\". Fault S blocks EVERY tool call, so the\n * one thing a blocked agent must be able to trust is whether the block will lift — and a success line\n * that is not backed by the guard's own check is exactly the false certainty that leaves it retrying a\n * cure that cannot work. So re-run `managedSurfaceDrift()`, the very function `enforceCommittedShim()`\n * calls, and return NON-ZERO naming whatever still differs.\n *\n * Measured against `root` (the tree we just repaired), not `governingShimRoot()` (the tree the running\n * binary came from). Those differ when the cure is run across trees, and the honest claim here is about\n * the files this invocation wrote.\n */\n// webpieces-disable no-function-outside-class -- sibling of runUpgradeShim in this deliberately dependency-free bin module\nfunction verifyRepaired(root: string): number {\n const stillDrifted = managedSurfaceDrift(root);\n if (stillDrifted.length === 0) return 0;\n console.error(`${RED}🛑 @webpieces: the repair ran but ${stillDrifted.length} managed surface(s) STILL differ: ${stillDrifted.join(', ')}.${RESET}`);\n console.error(` The guard will keep blocking. This is a webpieces bug or an unwritable tree under ${root} - do not retry this command in a loop; report it with the list above.`);\n return 1;\n}\n\n/**\n * THE PROCESS ENTRY POINT — the thing whose absence made this whole bin a lie.\n *\n * Up to and including 0.4.588 this module ENDED at the closing brace above. `pnpm exec wp-upgrade-shim`\n * loaded it, defined two functions, and exited 0 having printed nothing and changed no file. Fault S\n * names this command as OPTION 1, the only option that repairs every managed surface, so the\n * guard's own \"THIS IS NOT A DEADLOCK\" promise was false: OPTION 2 repairs one of three, and OPTION 1\n * did nothing at all. Twenty-one unit tests missed it because every one of them called\n * `runUpgradeShim()` as a FUNCTION — the defect lived entirely in what the module does when SPAWNED.\n *\n * `runMain` from @webpieces/rules-config is the repo-wide wrapper and is deliberately NOT used here:\n * this bin must load with fs+path only (see the header) so it still runs on the broken tree it exists\n * to repair. `main()` is the sanctioned exit site instead, and `bin-process-entry.spec.ts` spawns\n * this file as a process so a future refactor cannot silently drop the launcher again.\n */\n// webpieces-disable no-function-outside-class -- bin entry point in this deliberately dependency-free module; see header\nexport function main(): void {\n process.exit(runUpgradeShim(process.cwd()));\n}\n\nif (require.main === module) {\n main();\n}\n"]}
1
+ {"version":3,"file":"upgrade-shim.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/bin/upgrade-shim.ts"],"names":[],"mappings":";;;AAmEA,wCA8BC;AA4ID,oBAEC;;AA9OD,mFAA+E;AAC/E,+CAAyB;AACzB,mDAA6B;AAE7B,iCAA4D;AAC5D,qDAA6E;AAC7E,2DAAgG;AAChG,+CAAqE;AACrE,iEAA6D;AAE7D,8EAA8E;AAC9E,qGAAqG;A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,CAAC,MAAM,qCAAqC,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,KAAK,EAAE,CAAC,CAAC;IACrJ,OAAO,CAAC,KAAK,CAAC,uFAAuF,IAAI,wEAAwE,CAAC,CAAC;IACnL,OAAO,CAAC,CAAC;AACb,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,yHAAyH;AACzH,SAAgB,IAAI;IAChB,OAAO,CAAC,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;AAChD,CAAC;AAED,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;IAC1B,IAAI,EAAE,CAAC;AACX,CAAC","sourcesContent":["#!/usr/bin/env node\nimport { RepositoryLayout } from '@webpieces/tooling-common/repository-layout';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nimport { renderShim, shimPath, findShimRoot } from './shim';\nimport { REVIEWER_AGENT_MARKER, writeReviewerAgent } from './reviewer-agent';\nimport { repairRegistrationAt, managedSurfaceDrift, SettingsRepair } from './hook-registration';\nimport { BASH_CWD_ENV_KEY, BASH_CWD_ENV_VALUE } from './managed-env';\nimport { toError } from '@webpieces/tooling-common/to-error';\n\n// ---------------------------------------------------------------------------\n// The `wp-upgrade-shim` entry point — the CURE for the managed-hook-surface self-guard (L0 fault S).\n//\n// WHAT IT REPAIRS, and why all of them (2026-08-07, extended). This used to write EXACTLY ONE FILE,\n// ai-hook.sh, and touch nothing else. That was correct while the installed surface WAS one file. It is\n// now five (the name `wp-upgrade-shim` is older than the job and is NOT renamed — a rename with no\n// functional change is a cost with no payer; the prose is what gets corrected):\n//\n// 1. .claude/webpieces/ai-hook.sh the ONE guard shim, shared by every harness and registered\n// ABSOLUTE, so the MAIN tree governs every tree\n// 2. the .claude/settings.json registration itself\n// 3. the .codex/hooks.json registration — the SAME two hooks under Codex's own matchers and its own\n// $PWD anchor. Repaired only where it already EXISTS: arming a harness is the installer's decision,\n// this is the cure for one that has drifted\n// 3b. the NEIGHBOUR hook commands in both of those files — the entries a CONSUMER repo registers\n// beside webpieces' own. A repo-RELATIVE entry path (`node \".claude/hooks/guard-deploy.mjs\"`)\n// resolves against the hook process's cwd, so it dies the moment that cwd is not the repo root,\n// and per the hooks reference that non-zero exit is a NON-BLOCKING error — a SILENT UNGUARDED\n// ALLOW. Measured in a consumer repo (issue #852) silently disarming three security guards while\n// printing nothing but a `node:internal/modules/cjs/loader` fragment with no rule name. They are\n// anchored to the harness's own prefix, the same reversal webpieces made for its own hook. See\n// neighbour-hooks.ts\n// 4. the .claude/settings.json `env` entry CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR=1, which pins the\n// Bash cwd to the project root — and, because settings `env` is inherited, pins it identically for\n// every subagent, so a verdict never depends on where an earlier `cd` left the shell. Claude-only:\n// Codex has no settings `env`, and its cwd is measured not to drift\n// 5. .claude/agents/webpieces-reviewer.md — the generic PR-gate reviewer agent (issue #938), a committed,\n// generated file with the same contract as the shim; see reviewer-agent.ts\n//\n// WHAT IT DELIBERATELY DOES *NOT* DO: sweep this tree's dangling `node_modules/.bin/wp-*` symlinks. That\n// is a real defect — an entry pointing at a missing file is\n// worse than absence, because `ls node_modules/.bin` advertises a capability that only fails on execution\n// — and it WOULD read naturally here. It is not here because the one implementation of that sweep lives in\n// `@webpieces/rules-config` (`stale-bin-sweep.ts`), which this module may not import: the barrel pulls in\n// inversify and the config loader, and a subpath import resolves against the INSTALLED rules-config, which\n// is a release behind this source (see .claude/rules/published-vs-local-source.md) — so a spawned\n// `wp-upgrade-shim` would die on module resolution, in the one command an L0-blocked session has left. A\n// second copy of the sweep here would be a second spelling of it, which is worse again.\n//\n// It does not need to be here. The sweep rides the `wp-*` startup pass that regenerates\n// `.webpieces/instruct-ai/*`, so ANY `wp-*` command heals the tree — including the `pnpm install` +\n// `pnpm exec wp-upgrade-shim` sequence this bin's own advice ends with.\n//\n// A cure that fixes some of them is worse than no cure, because it reports success. This bin is the\n// sanctioned cure named in fault S's message and is on the L0 allowlist, so it must repair everything.\n//\n// Deliberately imports only ./shim and ./hook-registration (fs + path) + toError,\n// exactly like install-entry: the whole job is to rewrite webpieces-managed files, which never needed\n// the rule engine, and it must stay runnable on a tree too broken to load it.\n// ---------------------------------------------------------------------------\nconst RED = '[31;1m';\nconst RESET = '[0m';\n\n// Returns the process exit code (0 = ok). Kept as a function (not top-level code) so it is unit-testable\n// without spawning node.\n// webpieces-disable no-function-outside-class -- bin entry point: this module MUST load with only fs+path (see header), mirroring install-entry.ts. A DI-managed class would pull the container in and reintroduce the require-time crash this dependency-free path exists to survive.\nexport function runUpgradeShim(cwd: string): number {\n const root = findShimRoot(cwd);\n if (root === null) {\n console.error(`${RED}🛑 @webpieces: no committed .claude/webpieces/ai-hook.sh found to regenerate.${RESET}`);\n console.error(' Run this from a repo that installs @webpieces/agent-workflow-rules, or run the installer (pnpm wp-install-ai-hooks).');\n return 1;\n }\n const target = shimPath(root);\n // webpieces-disable no-unmanaged-exceptions -- bin entry chokepoint: turn an fs error into an actionable line + non-zero exit rather than a raw node trace; there is no caller above a bin to handle it.\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n new RepositoryLayout().migrate(root);\n fs.writeFileSync(target, renderShim(), { mode: 0o755 });\n // writeFileSync's mode only applies on create; force it on overwrite too (matches writeShim).\n fs.chmodSync(target, 0o755);\n const repairs = repairRegistrationAt(root);\n // The generic PR-gate reviewer agent — a managed file like the shim, so the one cure rewrites it too.\n if (writeReviewerAgent(root)) {\n console.log(`✅ @webpieces: wrote the generic PR-gate reviewer agent ${REVIEWER_AGENT_MARKER} (generated — commit it, do not edit it).`);\n }\n reportRepairs(target, repairs);\n // ADVISORY ONLY, and deliberately after the ✅ lines: it never touches the exit code (see\n // reportTreeDivergence).\n reportTreeDivergence(root);\n return verifyRepaired(root);\n } catch (err: unknown) {\n const error = toError(err);\n console.error(`${RED}🛑 @webpieces: could not write under ${root}: ${error.message}${RESET}`);\n return 1;\n }\n}\n\n/**\n * Say what was actually done, per managed thing. The old single line (\"regenerated the managed shim\")\n * would now be a lie by omission on the three most important repairs — and an agent reading a cure's\n * output is how it decides whether the cure worked.\n *\n * Each settings file reports the repairs IT needed, from the flags recorded before the rewrite. Printing\n * \"rewrote the hook registration\" for a file whose hooks were already current and whose `env` entry was\n * the only thing missing would be the same class of dishonesty one level down.\n */\n// webpieces-disable no-function-outside-class -- sibling of runUpgradeShim in this deliberately dependency-free bin module\nfunction reportRepairs(shimFile: string, repairs: readonly SettingsRepair[]): void {\n console.log(`✅ @webpieces: regenerated the managed shim at ${shimFile} — tool calls are re-armed.`);\n if (repairs.length === 0) {\n console.log(' .claude/settings.json (hook registration + managed env) already matches this release — no change.');\n }\n for (const repair of repairs) {\n if (repair.registration) {\n console.log(`✅ @webpieces: rewrote the hook registration in ${repair.settingsPath} to the two-hook form`);\n console.log(' (both guard hooks ABSOLUTE via $CLAUDE_PROJECT_DIR, so the MAIN tree governs every tree).');\n }\n for (const command of repair.anchoredNeighbours) {\n console.log(`✅ @webpieces: anchored a RELATIVE hook command in ${repair.settingsPath} so it resolves from any cwd`);\n console.log(` now: ${command}`);\n console.log(' (a relative entry path resolves against the hook process cwd; off the repo root it fails to load, and');\n console.log(' per the hooks reference that non-zero exit is NON-BLOCKING — the guard silently stops guarding.)');\n }\n if (repair.env) {\n console.log(`✅ @webpieces: set env.${BASH_CWD_ENV_KEY}=${BASH_CWD_ENV_VALUE} in ${repair.settingsPath}`);\n console.log(' (pins the Bash cwd to the project root, so the guard hooks resolve identically for every subagent — for');\n console.log(' this session and, because settings env is inherited, for every subagent it spawns).');\n }\n }\n console.log(' These files are generated + committed by webpieces; do not revert or hand-edit them.');\n}\n\n/**\n * WAS THE REPAIRED TREE THE TREE THE HOOKS LAUNCH FROM — the second way this cure can report success\n * while changing nothing the session is actually governed by.\n *\n * H1 is registered ABSOLUTE, `sh \"$CLAUDE_PROJECT_DIR/…\"`, and `$CLAUDE_PROJECT_DIR` never moves off the\n * PRIMARY clone (the two-tree straddle recorded in shim.ts, and the whole reason H2/H3 are relative\n * while H1 is not). So repairing a LINKED WORKTREE leaves the running session still loading the\n * PRIMARY's files, the PRIMARY's binary and the PRIMARY's pin. Four green lines, and the block does not\n * lift. Nothing printed above is false — but the question the reader has (\"will the block lift?\") went\n * unanswered, which is the same failure this file's header exists to prevent, one level out.\n *\n * THE PREDICATE IS TREE DIVERGENCE, NOT \"am I a subagent\". There is no runtime subagent marker in the\n * hook environment to read, and divergence is the more accurate question anyway: a MAIN agent in a\n * linked worktree HAS this problem (a subagent test would miss it), and a SUBAGENT in the same tree does\n * NOT (a subagent test would cry wolf). Both paths are realpath'd before comparing — a worktree path can\n * arrive symlinked, and /tmp vs /private/tmp on darwin is a live case in this repo's own specs.\n *\n * SILENT when `$CLAUDE_PROJECT_DIR` is unset: a plain CLI run outside Claude Code has no second tree to\n * talk about. And ADVISORY always — it must never turn a verified repair into a failure, so it returns\n * nothing and `verifyRepaired()`'s contract (non-zero only when a surface in THIS tree still differs) is\n * untouched.\n */\n// webpieces-disable no-function-outside-class -- sibling of runUpgradeShim in this deliberately dependency-free bin module\nfunction reportTreeDivergence(root: string): void {\n const projectDir = process.env['CLAUDE_PROJECT_DIR'];\n if (projectDir === undefined || projectDir === '') return;\n if (sameTree(root, projectDir)) return;\n console.log('');\n console.log('⚠️ @webpieces: the tree just repaired is NOT the tree the hooks launch from.');\n console.log(` repaired: ${root}`);\n console.log(` CLAUDE_PROJECT_DIR: ${projectDir}`);\n console.log(' The hooks governing this session resolve through CLAUDE_PROJECT_DIR (H1 is registered');\n console.log(' absolute), so this repair has not changed what is currently enforcing — it made THIS');\n console.log(' tree correct for when its own branch is the one being judged, which is not wasted work.');\n console.log(' To change what is enforcing NOW, run the same repair in the primary tree, and install');\n console.log(' there too — the hooks execute the INSTALLED release, not this tree\\'s source:');\n console.log(` cd ${projectDir} && pnpm install && pnpm exec wp-upgrade-shim`);\n console.log(' Repaired in BOTH trees is the aligned end state, and running it twice is safe.');\n}\n\n/**\n * Do two paths name the same tree? realpath'd (symlinked worktrees, /tmp vs /private/tmp) and stripped\n * of a trailing separator before comparing. A path that cannot be realpath'd falls back to `resolve`,\n * so an absent CLAUDE_PROJECT_DIR directory reads as \"different\" rather than throwing inside a cure.\n */\n// webpieces-disable no-function-outside-class -- sibling of runUpgradeShim in this deliberately dependency-free bin module\nfunction sameTree(a: string, b: string): boolean {\n return canonicalTree(a) === canonicalTree(b);\n}\n\n// webpieces-disable no-function-outside-class -- sibling of runUpgradeShim in this deliberately dependency-free bin module\nfunction canonicalTree(dir: string): string {\n // webpieces-disable no-unmanaged-exceptions -- realpath throws on a path that does not exist; the fallback IS the handling, and an advisory notice must never crash the cure it annotates.\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return path.resolve(fs.realpathSync(dir));\n } catch (err: unknown) {\n const error = toError(err);\n void error; // best-effort: an unresolvable path simply compares as itself\n return path.resolve(dir);\n }\n}\n\n/**\n * DID THE CURE ACTUALLY CURE IT — asked of the same predicate the guard asks, not of our own writes.\n *\n * A cure that cannot fail loudly is worse than no cure. This bin used to print three ✅ lines and\n * return 0 the moment `writeFileSync` did not throw, which asserts only \"the bytes we chose were\n * written\", never \"the surface the guard measures now agrees\". Fault S blocks EVERY tool call, so the\n * one thing a blocked agent must be able to trust is whether the block will lift — and a success line\n * that is not backed by the guard's own check is exactly the false certainty that leaves it retrying a\n * cure that cannot work. So re-run `managedSurfaceDrift()`, the very function `enforceCommittedShim()`\n * calls, and return NON-ZERO naming whatever still differs.\n *\n * Measured against `root` (the tree we just repaired), not `governingShimRoot()` (the tree the running\n * binary came from). Those differ when the cure is run across trees, and the honest claim here is about\n * the files this invocation wrote.\n */\n// webpieces-disable no-function-outside-class -- sibling of runUpgradeShim in this deliberately dependency-free bin module\nfunction verifyRepaired(root: string): number {\n const stillDrifted = managedSurfaceDrift(root);\n if (stillDrifted.length === 0) return 0;\n console.error(`${RED}🛑 @webpieces: the repair ran but ${stillDrifted.length} managed surface(s) STILL differ: ${stillDrifted.join(', ')}.${RESET}`);\n console.error(` The guard will keep blocking. This is a webpieces bug or an unwritable tree under ${root} - do not retry this command in a loop; report it with the list above.`);\n return 1;\n}\n\n/**\n * THE PROCESS ENTRY POINT — the thing whose absence made this whole bin a lie.\n *\n * Up to and including 0.4.588 this module ENDED at the closing brace above. `pnpm exec wp-upgrade-shim`\n * loaded it, defined two functions, and exited 0 having printed nothing and changed no file. Fault S\n * names this command as OPTION 1, the only option that repairs every managed surface, so the\n * guard's own \"THIS IS NOT A DEADLOCK\" promise was false: OPTION 2 repairs one of three, and OPTION 1\n * did nothing at all. Twenty-one unit tests missed it because every one of them called\n * `runUpgradeShim()` as a FUNCTION — the defect lived entirely in what the module does when SPAWNED.\n *\n * `runMain` from @webpieces/rules-config is the repo-wide wrapper and is deliberately NOT used here:\n * this bin must load with fs+path only (see the header) so it still runs on the broken tree it exists\n * to repair. `main()` is the sanctioned exit site instead, and `bin-process-entry.spec.ts` spawns\n * this file as a process so a future refactor cannot silently drop the launcher again.\n */\n// webpieces-disable no-function-outside-class -- bin entry point in this deliberately dependency-free module; see header\nexport function main(): void {\n process.exit(runUpgradeShim(process.cwd()));\n}\n\nif (require.main === module) {\n main();\n}\n"]}
@@ -193,8 +193,7 @@ exports.L0_FAULTS = [
193
193
  // and prompts for a target twice, which hangs a non-interactive agent.
194
194
  bashCure(shim_1.UPGRADE_SHIM_CMD, true, 'this fault fires at all — it is the only cure that repairs EVERY managed surface '
195
195
  + '(ai-hook.sh, each harness hook registration, the anchoring of the neighbour hook '
196
- + 'commands registered beside ours, and the Claude settings env entry), and it also '
197
- + 'deletes the retired guarantee-root.sh and any entry still naming it, and it '
196
+ + 'commands registered beside ours, and the Claude settings env entry), and it '
198
197
  + 'touches no config; needs installed @webpieces/agent-workflow-rules 0.4.408 or newer'),
199
198
  // 2026-07-21: the version gap below caused a real "command not found" deadlock.
200
199
  bashCure(shim_1.RESTORE_SHIM_CMD, false, 'the installed @webpieces/agent-workflow-rules is OLDER than 0.4.408, so wp-upgrade-shim does '
@@ -1 +1 @@
1
- {"version":3,"file":"l0-matrix.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/core/l0-matrix.ts"],"names":[],"mappings":";;;AA0QA,oDAqCC;AA/SD,0DAA2F;AAC3F,0DAAyE;AAEzE,sCAAmN;AACnN,0DAA6D;AAE7D,gEAA2H;AAC3H,8DAA8D;AAC9D,0DAAsS;AAGtS,8EAA8E;AAC9E,6CAA6C;AAC7C,EAAE;AACF,uFAAuF;AACvF,kGAAkG;AAClG,qGAAqG;AACrG,EAAE;AACF,gFAAgF;AAChF,EAAE;AACF,gGAAgG;AAChG,qGAAqG;AACrG,+FAA+F;AAC/F,8EAA8E;AAE9E;;;;;;;;;GASG;AACH,wDAAoG;AAA3F,gHAAA,gBAAgB,OAAA;AAAE,mHAAA,mBAAmB,OAAA;AAAE,kHAAA,kBAAkB,OAAA;AAGlE;;;;;;;GAOG;AACH,MAAa,MAAM;IAGF;IACA;IAKA;IAKA;IAbb,yDAAyD;IACzD,YACa,OAAe,EACf,IAAY;IACrB;;;OAGG;IACM,SAAkB;IAC3B;;;OAGG;IACM,aAAqB;QAXrB,YAAO,GAAP,OAAO,CAAQ;QACf,SAAI,GAAJ,IAAI,CAAQ;QAKZ,cAAS,GAAT,SAAS,CAAS;QAKlB,kBAAa,GAAb,aAAa,CAAQ;IAC/B,CAAC;IAEJ,qGAAqG;IACrG,SAAS;QACL,OAAO,IAAI,CAAC,IAAI,CAAC,QAAQ,KAAK,MAAM,CAAC;IACzC,CAAC;CACJ;AArBD,wBAqBC;AAED,wDAAwD;AACxD,MAAa,OAAO;IAOH;IACA;IACA;IACA;IACA;IAMA;IAhBb;IACI;;;;OAIG;IACM,IAAiB,EACjB,IAAY,EACZ,UAAkB,EAClB,UAAkB,EAClB,KAAwB;IACjC;;;;OAIG;IACM,QAAgB;QAVhB,SAAI,GAAJ,IAAI,CAAa;QACjB,SAAI,GAAJ,IAAI,CAAQ;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YNC_HEADER } from '@webpieces/rules-config';\nimport { CONFIG_FILENAME, writeTemplate } from '@webpieces/rules-config';\n\nimport { ADD_HOOK_PKG_CMD, CHECKOUT_MAIN_PULL_CMD, HOOK_PKG, INSTALL_HOOKS_CMD, L0AllowEntry, L0Call, L0_ALLOWLIST, RECOVERY_CMD, RESTORE_SHIM_CMD, SHIM_MARKER, UPGRADE_SHIM_CMD, renderShim } from '../bin/shim';\nimport { WORKSPACE_MANIFEST } from '@webpieces/rules-config';\nimport { CODEX_READ_STILL_ALLOWED } from '@webpieces/rules-config';\nimport { ENV_SURFACE, HARNESS_REGISTRATIONS, HarnessRegistration, REVIEWER_AGENT_SURFACE } from '../bin/hook-registration';\nimport { shimStaleDenyReason } from '../bin/shim-deny-reason';\nimport { L0_FAULT_BIN_BROKEN, L0_FAULT_BIN_MISSING, L0_FAULT_CONFIG_MISSING, L0_FAULT_CONFIG_OUT_OF_SYNC, L0_FAULT_DRIFT, L0_FAULT_NAMES, L0_FAULT_SHIM_STALE, L0_FAULT_UNDECLARED, L0FaultCode, L0_ROW_ALLOWLISTED, L0_ROW_BLOCKED, l0GuardHeader, l0MatrixCitation } from '@webpieces/rules-config';\nimport { toError } from '@webpieces/tooling-common/to-error';\n\n// ---------------------------------------------------------------------------\n// L0 — the TOOLING-INTEGRITY layer, as data.\n//\n// L0 is the outermost guard: it blocks work while node_modules, the committed shim, or\n// webpieces.config.json are in a state that makes every OTHER guard untrustworthy. Its faults are\n// enumerated in L0_FAULTS below and — drawn as a decision matrix — have NO genuine second dimension:\n//\n// fault present AND call not on the allowlist -> BLOCK(messageFor(fault))\n//\n// so the only thing that varies per fault is the MESSAGE. This module holds the fault table and\n// renders it, together with L0_ALLOWLIST (../bin/shim), into webpieces.guard-matrix.md — the doc the\n// deny messages point the AI at. Doc and code come from the SAME arrays, so they cannot drift.\n// ---------------------------------------------------------------------------\n\n/**\n * The doc L0's deny messages point at. Lives in @webpieces/rules-config/templates alongside the others,\n * and is written to <root>/.webpieces/instruct-ai/ lazily, only on an L0 BLOCK.\n *\n * That generated doc is the AUTHORITY for the fault table and the allowlist (same arrays, cannot\n * drift). guards/L0-tooling.md is the hand-written companion: it adds L0's evaluation\n * ORDER, the use cases and the known gaps, and it documents L1, none of which are rendered from code.\n * Change L0_FAULTS or L0_ALLOWLIST and the generated doc follows automatically — guards/L0-tooling.md does\n * not, so update it in the same PR.\n */\nexport { GUARD_MATRIX_DOC, writeGuardMatrixDoc, guardMatrixPointer } from '@webpieces/rules-config';\nimport { GUARD_MATRIX_DOC } from '@webpieces/rules-config';\n\n/**\n * One CURE for a fault: the exact call, plus the `mention` that must appear in that fault's deny text.\n *\n * Both halves are asserted (l0-matrix.spec.ts): the call must be accepted by isAllowed(), and the deny\n * message must actually name it. That pairing is the anti-deadlock invariant — a message that\n * prescribes a command the allowlist rejects is exactly the shape of the three deadlocks\n * `.claude/rules/*.md` records, and it is how the dead `wp-setup-ai-hooks` bin in the config-missing text was caught.\n */\nexport class L0Cure {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n readonly mention: string,\n readonly call: L0Call,\n /**\n * The one to reach for first when a fault has several. Exactly one cure per fault carries it,\n * so the rendered Fix section never asks the reader to choose between equals.\n */\n readonly preferred: boolean,\n /**\n * WHEN to pick this cure over its siblings — the sentence that makes a list of commands\n * actionable instead of a menu (\"when the PIN is the stale side\", not \"an alternative\").\n */\n readonly discriminator: string,\n ) {}\n\n /** A Bash cure renders as a literal command; a tool-shaped one renders as the edit it stands for. */\n isCommand(): boolean {\n return this.call.toolName === 'Bash';\n }\n}\n\n/** One L0 fault. Data-only → a class, per CLAUDE.md. */\nexport class L0Fault {\n constructor(\n /**\n * The codebook's letter — typed as the UNION of every declared code, not `string`, so\n * `L0_FAULT_NAMES[code]` is total and neither this module nor the deny builders need a\n * `?? 'unknown'` fallback. A fault added without a name fails to compile.\n */\n readonly code: L0FaultCode,\n readonly name: string,\n readonly detectedBy: string,\n readonly enforcedIn: string,\n readonly cures: readonly L0Cure[],\n /**\n * The artifact carrying this fault's deny text. For S/C/Y that is the deny string itself; for\n * D/X/U/K the text is built in POSIX sh inside the rendered shim, so it is the rendered shim —\n * the same bytes the consumer runs, which is what the mention assertion needs to search.\n */\n readonly denyText: string,\n ) {}\n}\n\n// The deny for fault C, and the ONLY message L0 has for a repo with no webpieces.config.json at all.\n// Moved here from runner.ts so the fault table and the runner cannot state different cures.\n//\n// It used to name `./node_modules/.bin/wp-setup-ai-hooks` — a bin that HAS NOT EXISTED since it was\n// renamed to wp-install-ai-hooks. So the one command this deny prescribed was (a) not installable and\n// (b) not on the L0 allowlist in that spelling, i.e. the AI was handed a cure it could neither run nor\n// get past the guard. Now it names the installer that actually seeds the config AND is entry 8 of the\n// allowlist, and it says out loud that writing the config yourself is allowed through.\n//\n// ORDERING (2026-08-02): writing the file yourself now LEADS. The bare installer used to be OPTION 1,\n// but it seeds the config and then PROMPTS twice for a hook target, which hangs a non-interactive\n// agent. Writing the file is the one cure that always works, and it is the same cure every other config\n// problem has (see the config-validation invariant in guards/L0-tooling.md): the validator reports every\n// error at once, so the write/validate loop converges in a couple of passes.\n// Writing/repairing the file yourself. PREFERRED for both config faults, per the config-validation\n// invariant in guards/L0-tooling.md: every config problem cures to \"make the file right\", the validator\n// reports all errors at once so the loop converges in a couple of passes, and allowlist entry 2 permits\n// this edit unconditionally. (That section is the authority — do not restate its reasoning here.)\nconst CONFIG_WRITE_CURE = new L0Cure(\n CONFIG_FILENAME, new L0Call('Edit', '', `/repo/${CONFIG_FILENAME}`), true,\n 'this fault fires at all — it is the only cure that needs no other tool, and it is never denied',\n);\n\n// Cure calls are spelled exactly as the deny messages spell them, so the mention assertion is a real\n// string search rather than a paraphrase.\n// webpieces-disable no-function-outside-class -- pure constructor helper for the L0_FAULTS literal below, in this data module\nfunction bashCure(command: string, preferred: boolean, discriminator: string): L0Cure {\n return new L0Cure(command, new L0Call('Bash', command, ''), preferred, discriminator);\n}\n\n/**\n * THE L0 faults, in first-match-wins order. D/X/U/K are decided in POSIX sh BEFORE the bin runs (a\n * stale, missing or broken validator cannot be trusted to validate itself); S/C/Y are decided inside\n * the bin, in JS. One model, two enforcement points.\n */\nexport const L0_FAULTS: readonly L0Fault[] = [\n new L0Fault(L0_FAULT_DRIFT, 'version drift — root package.json pin != installed version',\n 'sh, before the bin runs', 'sh',\n [\n // `pnpm install` clears D in BOTH directions — it makes installed == pin by definition — so\n // it is always the preferred cure. The direction only decides whether the PIN is the version\n // you WANT, which is what the second cure is for.\n bashCure('pnpm install', true,\n 'node_modules is OLDER than the pin, OR you are on a feature branch and want YOUR '\n + 'branch pin (usually the case) — it always clears the drift'),\n // The on-main sync is spelled `git checkout main && git pull origin main` and NOT `git pull`:\n // a raw pull on a FEATURE branch merges main into it and destroys the fork point, so it is\n // no longer on the L0 allowlist at all (see CHECKOUT_MAIN_PULL_BODY_ERE). This spelling ends\n // ON main, which is why it is safe from any branch — and it is a no-op checkout when you are\n // already there.\n //\n // And it is RAW GIT on purpose, where the workflow guards now say `pnpm wp-sync-main`\n // instead. The fault being cured here is `node_modules` disagreeing with the pin, so\n // `node_modules` is the untrustworthy thing — and every `pnpm wp-*` bin resolves through it.\n // An L0 cure may never be a command that has to load the package it is repairing. See the\n // long note on CHECKOUT_MAIN_PULL_BODY_ERE in bin/l0-allowlist.ts.\n bashCure(CHECKOUT_MAIN_PULL_CMD, false,\n 'node_modules is NEWER than the pin AND you are on main — the PIN is the stale side, so '\n + 'sync first and install second; a bare install would downgrade you'),\n ], renderShim()),\n new L0Fault(L0_FAULT_BIN_MISSING, 'guard bin missing (fresh clone / new worktree / package removed)',\n 'sh, before the bin runs', 'sh',\n [bashCure('pnpm install', true,\n 'this fault fires at all — nothing is installed in THIS tree, and a new git worktree '\n + 'copies no node_modules')],\n renderShim()),\n // U is X with the ONE input that inverts X's cure, which is why it is a separate fault and not a\n // sentence inside X's message: a BARE `pnpm install` is not a weaker fix here, it is a PROVABLE\n // no-op, and an agent that trusts the X text will run it until it gives up. See the ADD_HOOK_PKG\n // entry in l0-allowlist.ts for the incident.\n //\n // The ORDER of these three is the correction bought by a second incident. `pnpm add` used to be the\n // preferred cure, and it is the one cure that CANNOT be committed: a direct root dependency on\n // HOOK_PKG violates the umbrella rule (the root manifest depends on the umbrella ALONE), and the\n // message never said to revert it — so it was followed, and the workaround landed in a real\n // package.json. The package normally arrives WITH the umbrella, so a tree that is merely BEHIND is\n // the common cause and syncing is the cure that leaves a committable tree. The add stays last,\n // reachable, and explicitly labelled as a session unblock rather than a fix.\n new L0Fault(L0_FAULT_UNDECLARED, `guard bin missing AND ${HOOK_PKG} is not declared in package.json`,\n 'sh, before the bin runs', 'sh',\n [\n bashCure(CHECKOUT_MAIN_PULL_CMD, true,\n `${HOOK_PKG} arrives WITH the umbrella, so a tree that is behind explains this without `\n + 'anything being mis-declared — sync first, then install'),\n bashCure('pnpm install', false,\n 'the sync (or a raised catalog pin in ' + WORKSPACE_MANIFEST + ', which is editable '\n + 'while the block is up) gave the installer something new to do — a BARE install with '\n + 'nothing changed reports \"Lockfile is up to date\" and leaves the tree as broken as it '\n + 'found it'),\n bashCure(ADD_HOOK_PKG_CMD, false,\n 'nothing else worked and you need this session back — it is a session unblock, NOT a '\n + `fix: revert it with 'pnpm remove ${HOOK_PKG}' before committing, because a direct `\n + 'root dependency on it violates the umbrella rule'),\n ],\n renderShim()),\n new L0Fault(L0_FAULT_BIN_BROKEN, 'guard bin present but CRASHED (exit code not 0 or 2 — corrupt node_modules)',\n 'sh, before the bin runs', 'sh',\n [bashCure(RECOVERY_CMD, true,\n 'this fault fires at all — a BARE pnpm install SKIPS the corrupt package, because pnpm sees '\n + 'the right version on disk and considers it installed; only the delete forces a rewrite')],\n renderShim()),\n // S covers the WHOLE managed hook surface, not just the shim: the committed ai-hook.sh, the\n // .claude/settings.json entries that register them AND the managed `env` entry that pins the Bash\n // cwd so the hooks resolve identically for every subagent. They only work as a set — a settings file left\n // on a superseded form silently changes who governs, re-pinning every tree to the\n // primary's release — and nothing validated the registration at all before it joined this fault.\n new L0Fault(L0_FAULT_SHIM_STALE, 'a webpieces-managed hook file, one of the harness hook registrations (.claude/settings.json, .codex/hooks.json) or the managed env entry does not match this release',\n 'the guard bin', 'JS',\n [\n // wp-upgrade-shim leads because it is the ONLY cure that repairs EVERY managed surface, and\n // it is still surgical: it rewrites ai-hook.sh, each harness's registration and the env entry\n // and touches no config, and it imports only fs/path so it runs on a tree too broken to load\n // the rule engine. The INSTALLER is deliberately NOT a cure here: it also migrates the config\n // and prompts for a target twice, which hangs a non-interactive agent.\n bashCure(UPGRADE_SHIM_CMD, true,\n 'this fault fires at all — it is the only cure that repairs EVERY managed surface '\n + '(ai-hook.sh, each harness hook registration, the anchoring of the neighbour hook '\n + 'commands registered beside ours, and the Claude settings env entry), and it also '\n + 'deletes the retired guarantee-root.sh and any entry still naming it, and it '\n + 'touches no config; needs installed @webpieces/agent-workflow-rules 0.4.408 or newer'),\n // 2026-07-21: the version gap below caused a real \"command not found\" deadlock.\n bashCure(RESTORE_SHIM_CMD, false,\n 'the installed @webpieces/agent-workflow-rules is OLDER than 0.4.408, so wp-upgrade-shim does '\n + 'not exist yet — it is PARTIAL (it repairs ai-hook.sh and NOTHING else), so upgrade '\n + '@webpieces afterwards and run Option 1 to finish'),\n ],\n // The SAMPLE deny renders EVERY managed surface, built from HARNESS_REGISTRATIONS rather than\n // a hand-written trio — a doc that shows a three-surface deny while the guard can report four\n // is exactly the drift this generated-doc arrangement exists to make impossible.\n shimStaleDenyReason('', '', [\n SHIM_MARKER,\n ...HARNESS_REGISTRATIONS.flatMap((h: HarnessRegistration): readonly string[] => [h.registrationSurface, h.neighbourSurface]),\n ENV_SURFACE,\n REVIEWER_AGENT_SURFACE,\n ], false)),\n new L0Fault(L0_FAULT_CONFIG_MISSING, `${CONFIG_FILENAME} missing`,\n 'the guard bin', 'JS',\n [\n CONFIG_WRITE_CURE,\n // Kept, but demoted: it seeds the file and then PROMPTS twice for a hook target.\n bashCure(INSTALL_HOOKS_CMD, false,\n 'you are at an INTERACTIVE terminal and can answer its two hook-target prompts'),\n ], CONFIG_MISSING_REPORT),\n new L0Fault(L0_FAULT_CONFIG_OUT_OF_SYNC, `a loaded rule has no ${CONFIG_FILENAME} key`,\n 'the guard bin', 'JS',\n [CONFIG_WRITE_CURE], CONFIG_OUT_OF_SYNC_HEADER),\n];\n\n/**\n * One fault's FIX section, rendered from its `cures` array — literal commands only, never prose.\n *\n * This is the half that used to live in hand-written docs and drift. The three fields of L0Cure map\n * onto the three things a blocked reader needs and nothing else: WHAT to type (the call), WHETHER it is\n * the default (preferred), and WHEN to pick a sibling instead (discriminator). A cure with no\n * discriminator would render as a menu of equals, which is how an agent picks the wrong one.\n */\n// webpieces-disable no-function-outside-class -- pure string builder for renderGuardMatrixDoc below, beside the arrays it reads\nfunction renderFixSection(fault: L0Fault): string[] {\n const options = fault.cures.map((cure: L0Cure, i: number): string => {\n // A Bash cure is the command verbatim; a tool-shaped one is the file it edits (allowlist entry 2).\n const literal = cure.isCommand() ? `\\`${cure.call.command}\\`` : `edit \\`${cure.mention}\\` yourself`;\n const label = cure.preferred ? `Option ${i + 1} (preferred)` : `Option ${i + 1}`;\n return `- **${label}**: ${literal} ← pick this when ${cure.discriminator}`;\n });\n return [`### \\`${fault.code}\\` — ${fault.name}`, '', ...options, ''];\n}\n\n/**\n * Render webpieces.guard-matrix.md from L0_FAULTS + L0_ALLOWLIST.\n *\n * A unit test locks the committed template byte-identical to this output, the same way\n * templates/ai-hook.sh is locked to renderShim(). That is what makes the doc assertable instead of\n * aspirational: the table in the doc IS the array the guard consults.\n */\n// webpieces-disable no-function-outside-class -- pure string builder over the two exported arrays, beside them in this module\nexport function renderGuardMatrixDoc(): string {\n return [\n '# webpieces guard matrix — L0 (tooling integrity)',\n '',\n 'GENERATED from `L0_FAULTS` + `L0_ALLOWLIST` in `@webpieces/agent-workflow-rules`. Do not hand-edit —',\n 'a unit test locks this file byte-identical to `renderGuardMatrixDoc()`, so the table below is',\n 'the array the guard actually consults, not a description of it.',\n '',\n 'L0 is the OUTERMOST guard layer. It blocks work while `node_modules`, the committed shim, or',\n '`webpieces.config.json` are in a state that makes every other guard untrustworthy. If you are',\n 'reading this, one of the faults below fired and named this file.',\n '',\n '## The faults',\n '',\n 'THE JOIN KEYS ARE `guard`, `fault=` and `row=`. Every L0 deny opens',\n '`[<guard>] (layer=L0 fault=<code> row=3, …)`, and every audit line — from BOTH halves of L0, the',\n '`sh` shim and the guard bin — carries `layer=L0 row=<n> fault=<code>`. So one grep lands you in',\n 'the deny, the log line and the row below. The guard names come from `L0_FAULT_NAMES` and the row',\n 'numbers from `L0_ROW_*`, both spelled in exactly one place (`core/l0-fault-codes.ts`).',\n '',\n '| code | guard | fault | detected by | enforced in |',\n '|---|---|---|---|---|',\n ...L0_FAULTS.map((f: L0Fault): string =>\n `| \\`${f.code}\\` | \\`${L0_FAULT_NAMES[f.code]}\\` | ${f.name} | ${f.detectedBy} | ${f.enforcedIn} |`),\n '',\n 'First match wins. `D`/`X`/`U`/`K` are decided in POSIX `sh` inside the committed shim, BEFORE the',\n 'guard bin runs — a stale, missing or broken validator cannot be trusted to validate itself.',\n '',\n '## The fix, per fault',\n '',\n 'Every command below is rendered from that fault\\'s `cures` array and is asserted, by unit test,',\n 'to be accepted by `isAllowed()` — so nothing here can be a command the guard then rejects. Type',\n 'the option you pick EXACTLY as written and run nothing else on that line.',\n '',\n ...L0_FAULTS.flatMap(renderFixSection),\n ...renderMatrixAndAllowlist(),\n ].join('\\n');\n}\n\n/**\n * The second half of the doc: the three-row matrix and the ONE allowlist. Split out of\n * renderGuardMatrixDoc solely to keep it inside the method-line budget — the join order is what makes\n * the two halves one file, so keep them adjacent and keep the byte-lock test as the arbiter.\n */\n// webpieces-disable no-function-outside-class -- second half of renderGuardMatrixDoc's string, beside it in this module\nfunction renderMatrixAndAllowlist(): string[] {\n return [\n '## The matrix',\n '',\n 'L0 has NO genuine second dimension. Every branch reduces to one question:',\n '',\n '| # | fault | on the allowlist? | outcome |',\n '|---|---|---|---|',\n '| 1 | none | — | hand down to the next guard layer |',\n `| ${L0_ROW_ALLOWLISTED} | any | yes | PASS or ALLOW (see the entry) |`,\n `| ${L0_ROW_BLOCKED} | any | no | BLOCK — **only the message varies by fault** |`,\n '',\n `Row ${L0_ROW_BLOCKED} is the only row that blocks, so every L0 deny cites it — \\`row=${L0_ROW_BLOCKED}\\` in the`,\n 'deny header, `row=' + L0_ROW_BLOCKED + '` on the audit line, and this row here. Same numbers as L1 uses for',\n 'its own rows (see `L1_ROWS`), and for the same reason: a row number is IDENTITY, so it is never reused.',\n '',\n 'The tool is not a dimension either: \"any Read\" is an allowlist ENTRY, not a tool check.',\n '',\n '## The allowlist',\n '',\n 'ONE list, consulted identically by every fault. A cure that cannot help a given fault also',\n 'cannot hurt it, and gating each entry on a fault is what produced four real defects (a stale',\n 'shim that denied `pnpm install` and every git sync; faults that denied every Read; a config fault',\n 'that denied `rm -rf node_modules && pnpm install` while allowing a bare `pnpm install`).',\n '',\n '| # | allowed | outcome |',\n '|---|---|---|',\n ...L0_ALLOWLIST.map((e: L0AllowEntry, i: number): string => `| ${i + 1} | ${e.label} | ${e.kind.toUpperCase()} |`),\n '',\n '- **PASS** — L0 has no objection; the call falls THROUGH so the downstream guards still judge it.',\n '- **ALLOW** — terminal; bypasses everything, because a cure must stay reachable even when a',\n ' downstream guard would block it.',\n '',\n 'Every Bash entry is anchored to the WHOLE command. Appending `&& git status` makes it a DIFFERENT',\n 'command and it is rejected again — that is not the guard refusing its own cure.',\n '',\n 'On an UNGATED entry a leading `cd <dir> &&`, a trailing `2>&1` and a pipe into `tail`/`head` are',\n 'tolerated; nothing else is. **The harness-gated read row tolerates NONE of the three** — not the',\n '`cd` prefix, not the redirect, not the pipe — so `cat f 2>&1` and `cat f | head -20` are both',\n 'rejected. That is deliberate, not an oversight: the row means exactly what',\n '`core/shell-read-parity.ts` means by \"this is a read\", and that module treats a pipe or a redirect',\n 'as proof the command is more than one. Type the bare command.',\n '',\n '`git merge` is deliberately NOT on this list. Main is merged ONLY through the 3-point fork merge',\n '(`pnpm wp-start-update`, or `pnpm wp-start-upsert-pr` when a PR is already open).',\n '',\n '## Known asymmetry',\n '',\n 'Under `S`/`C`/`Y` the guard bin IS running, so a PASS really does fall through to the downstream',\n 'guards. Under `D`/`X`/`U`/`K` the bin is never executed, so there is nothing to fall through to and a',\n 'PASS degenerates into a terminal allow — reads are unguarded during those three faults.',\n '',\n '## Widening L0',\n '',\n 'Add an entry to `L0_ALLOWLIST` in `packages/tooling/agent-workflow-rules/src/bin/shim.ts`. That array is',\n 'the single source for the JS allowlist, the `grep -E` inside the rendered shim, and this file.',\n '',\n ];\n}\n\n/**\n * Drop the matrix doc where the AI can read it, and return its absolute path ('' if it could not be\n * written). Called from the L0 BLOCK path so the deny can say `READ <path>`.\n *\n * Best-effort by design: this runs while the tree is already known-broken, and a missing template (an\n * @webpieces/rules-config older than this package) must degrade the deny message, never replace it\n * with a crash.\n */\n// webpieces-disable no-function-outside-class -- sibling of renderGuardMatrixDoc in this module\n\n"]}
1
+ {"version":3,"file":"l0-matrix.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/core/l0-matrix.ts"],"names":[],"mappings":";;;AAyQA,oDAqCC;AA9SD,0DAA2F;AAC3F,0DAAyE;AAEzE,sCAAmN;AACnN,0DAA6D;AAE7D,gEAA2H;AAC3H,8DAA8D;AAC9D,0DAAsS;AAGtS,8EAA8E;AAC9E,6CAA6C;AAC7C,EAAE;AACF,uFAAuF;AACvF,kGAAkG;AAClG,qGAAqG;AACrG,EAAE;AACF,gFAAgF;AAChF,EAAE;AACF,gGAAgG;AAChG,qGAAqG;AACrG,+FAA+F;AAC/F,8EAA8E;AAE9E;;;;;;;;;GASG;AACH,wDAAoG;AAA3F,gHAAA,gBAAgB,OAAA;AAAE,mHAAA,mBAAmB,OAAA;AAAE,kHAAA,kBAAkB,OAAA;AAGlE;;;;;;;GAOG;AACH,MAAa,MAAM;IAGF;IACA;I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AAK,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,KAAK,MAAM,CAAC,CAAC,IAAI,CAAC,WAAW,EAAE,IAAI,CAAC;QAClH,EAAE;QACF,mGAAmG;QACnG,6FAA6F;QAC7F,oCAAoC;QACpC,EAAE;QACF,mGAAmG;QACnG,iFAAiF;QACjF,EAAE;QACF,kGAAkG;QAClG,kGAAkG;QAClG,+FAA+F;QAC/F,4EAA4E;QAC5E,oGAAoG;QACpG,+DAA+D;QAC/D,EAAE;QACF,kGAAkG;QAClG,mFAAmF;QACnF,EAAE;QACF,oBAAoB;QACpB,EAAE;QACF,kGAAkG;QAClG,uGAAuG;QACvG,yFAAyF;QACzF,EAAE;QACF,gBAAgB;QAChB,EAAE;QACF,0GAA0G;QAC1G,gGAAgG;QAChG,EAAE;KACL,CAAC;AACN,CAAC;AAED;;;;;;;GAOG;AACH,gGAAgG","sourcesContent":["import { CONFIG_MISSING_REPORT, CONFIG_OUT_OF_SYNC_HEADER } from '@webpieces/rules-config';\nimport { CONFIG_FILENAME, writeTemplate } from '@webpieces/rules-config';\n\nimport { ADD_HOOK_PKG_CMD, CHECKOUT_MAIN_PULL_CMD, HOOK_PKG, INSTALL_HOOKS_CMD, L0AllowEntry, L0Call, L0_ALLOWLIST, RECOVERY_CMD, RESTORE_SHIM_CMD, SHIM_MARKER, UPGRADE_SHIM_CMD, renderShim } from '../bin/shim';\nimport { WORKSPACE_MANIFEST } from '@webpieces/rules-config';\nimport { CODEX_READ_STILL_ALLOWED } from '@webpieces/rules-config';\nimport { ENV_SURFACE, HARNESS_REGISTRATIONS, HarnessRegistration, REVIEWER_AGENT_SURFACE } from '../bin/hook-registration';\nimport { shimStaleDenyReason } from '../bin/shim-deny-reason';\nimport { L0_FAULT_BIN_BROKEN, L0_FAULT_BIN_MISSING, L0_FAULT_CONFIG_MISSING, L0_FAULT_CONFIG_OUT_OF_SYNC, L0_FAULT_DRIFT, L0_FAULT_NAMES, L0_FAULT_SHIM_STALE, L0_FAULT_UNDECLARED, L0FaultCode, L0_ROW_ALLOWLISTED, L0_ROW_BLOCKED, l0GuardHeader, l0MatrixCitation } from '@webpieces/rules-config';\nimport { toError } from '@webpieces/tooling-common/to-error';\n\n// ---------------------------------------------------------------------------\n// L0 — the TOOLING-INTEGRITY layer, as data.\n//\n// L0 is the outermost guard: it blocks work while node_modules, the committed shim, or\n// webpieces.config.json are in a state that makes every OTHER guard untrustworthy. Its faults are\n// enumerated in L0_FAULTS below and — drawn as a decision matrix — have NO genuine second dimension:\n//\n// fault present AND call not on the allowlist -> BLOCK(messageFor(fault))\n//\n// so the only thing that varies per fault is the MESSAGE. This module holds the fault table and\n// renders it, together with L0_ALLOWLIST (../bin/shim), into webpieces.guard-matrix.md — the doc the\n// deny messages point the AI at. Doc and code come from the SAME arrays, so they cannot drift.\n// ---------------------------------------------------------------------------\n\n/**\n * The doc L0's deny messages point at. Lives in @webpieces/rules-config/templates alongside the others,\n * and is written to <root>/.webpieces/instruct-ai/ lazily, only on an L0 BLOCK.\n *\n * That generated doc is the AUTHORITY for the fault table and the allowlist (same arrays, cannot\n * drift). guards/L0-tooling.md is the hand-written companion: it adds L0's evaluation\n * ORDER, the use cases and the known gaps, and it documents L1, none of which are rendered from code.\n * Change L0_FAULTS or L0_ALLOWLIST and the generated doc follows automatically — guards/L0-tooling.md does\n * not, so update it in the same PR.\n */\nexport { GUARD_MATRIX_DOC, writeGuardMatrixDoc, guardMatrixPointer } from '@webpieces/rules-config';\nimport { GUARD_MATRIX_DOC } from '@webpieces/rules-config';\n\n/**\n * One CURE for a fault: the exact call, plus the `mention` that must appear in that fault's deny text.\n *\n * Both halves are asserted (l0-matrix.spec.ts): the call must be accepted by isAllowed(), and the deny\n * message must actually name it. That pairing is the anti-deadlock invariant — a message that\n * prescribes a command the allowlist rejects is exactly the shape of the three deadlocks\n * `.claude/rules/*.md` records, and it is how the dead `wp-setup-ai-hooks` bin in the config-missing text was caught.\n */\nexport class L0Cure {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n readonly mention: string,\n readonly call: L0Call,\n /**\n * The one to reach for first when a fault has several. Exactly one cure per fault carries it,\n * so the rendered Fix section never asks the reader to choose between equals.\n */\n readonly preferred: boolean,\n /**\n * WHEN to pick this cure over its siblings — the sentence that makes a list of commands\n * actionable instead of a menu (\"when the PIN is the stale side\", not \"an alternative\").\n */\n readonly discriminator: string,\n ) {}\n\n /** A Bash cure renders as a literal command; a tool-shaped one renders as the edit it stands for. */\n isCommand(): boolean {\n return this.call.toolName === 'Bash';\n }\n}\n\n/** One L0 fault. Data-only → a class, per CLAUDE.md. */\nexport class L0Fault {\n constructor(\n /**\n * The codebook's letter — typed as the UNION of every declared code, not `string`, so\n * `L0_FAULT_NAMES[code]` is total and neither this module nor the deny builders need a\n * `?? 'unknown'` fallback. A fault added without a name fails to compile.\n */\n readonly code: L0FaultCode,\n readonly name: string,\n readonly detectedBy: string,\n readonly enforcedIn: string,\n readonly cures: readonly L0Cure[],\n /**\n * The artifact carrying this fault's deny text. For S/C/Y that is the deny string itself; for\n * D/X/U/K the text is built in POSIX sh inside the rendered shim, so it is the rendered shim —\n * the same bytes the consumer runs, which is what the mention assertion needs to search.\n */\n readonly denyText: string,\n ) {}\n}\n\n// The deny for fault C, and the ONLY message L0 has for a repo with no webpieces.config.json at all.\n// Moved here from runner.ts so the fault table and the runner cannot state different cures.\n//\n// It used to name `./node_modules/.bin/wp-setup-ai-hooks` — a bin that HAS NOT EXISTED since it was\n// renamed to wp-install-ai-hooks. So the one command this deny prescribed was (a) not installable and\n// (b) not on the L0 allowlist in that spelling, i.e. the AI was handed a cure it could neither run nor\n// get past the guard. Now it names the installer that actually seeds the config AND is entry 8 of the\n// allowlist, and it says out loud that writing the config yourself is allowed through.\n//\n// ORDERING (2026-08-02): writing the file yourself now LEADS. The bare installer used to be OPTION 1,\n// but it seeds the config and then PROMPTS twice for a hook target, which hangs a non-interactive\n// agent. Writing the file is the one cure that always works, and it is the same cure every other config\n// problem has (see the config-validation invariant in guards/L0-tooling.md): the validator reports every\n// error at once, so the write/validate loop converges in a couple of passes.\n// Writing/repairing the file yourself. PREFERRED for both config faults, per the config-validation\n// invariant in guards/L0-tooling.md: every config problem cures to \"make the file right\", the validator\n// reports all errors at once so the loop converges in a couple of passes, and allowlist entry 2 permits\n// this edit unconditionally. (That section is the authority — do not restate its reasoning here.)\nconst CONFIG_WRITE_CURE = new L0Cure(\n CONFIG_FILENAME, new L0Call('Edit', '', `/repo/${CONFIG_FILENAME}`), true,\n 'this fault fires at all — it is the only cure that needs no other tool, and it is never denied',\n);\n\n// Cure calls are spelled exactly as the deny messages spell them, so the mention assertion is a real\n// string search rather than a paraphrase.\n// webpieces-disable no-function-outside-class -- pure constructor helper for the L0_FAULTS literal below, in this data module\nfunction bashCure(command: string, preferred: boolean, discriminator: string): L0Cure {\n return new L0Cure(command, new L0Call('Bash', command, ''), preferred, discriminator);\n}\n\n/**\n * THE L0 faults, in first-match-wins order. D/X/U/K are decided in POSIX sh BEFORE the bin runs (a\n * stale, missing or broken validator cannot be trusted to validate itself); S/C/Y are decided inside\n * the bin, in JS. One model, two enforcement points.\n */\nexport const L0_FAULTS: readonly L0Fault[] = [\n new L0Fault(L0_FAULT_DRIFT, 'version drift — root package.json pin != installed version',\n 'sh, before the bin runs', 'sh',\n [\n // `pnpm install` clears D in BOTH directions — it makes installed == pin by definition — so\n // it is always the preferred cure. The direction only decides whether the PIN is the version\n // you WANT, which is what the second cure is for.\n bashCure('pnpm install', true,\n 'node_modules is OLDER than the pin, OR you are on a feature branch and want YOUR '\n + 'branch pin (usually the case) — it always clears the drift'),\n // The on-main sync is spelled `git checkout main && git pull origin main` and NOT `git pull`:\n // a raw pull on a FEATURE branch merges main into it and destroys the fork point, so it is\n // no longer on the L0 allowlist at all (see CHECKOUT_MAIN_PULL_BODY_ERE). This spelling ends\n // ON main, which is why it is safe from any branch — and it is a no-op checkout when you are\n // already there.\n //\n // And it is RAW GIT on purpose, where the workflow guards now say `pnpm wp-sync-main`\n // instead. The fault being cured here is `node_modules` disagreeing with the pin, so\n // `node_modules` is the untrustworthy thing — and every `pnpm wp-*` bin resolves through it.\n // An L0 cure may never be a command that has to load the package it is repairing. See the\n // long note on CHECKOUT_MAIN_PULL_BODY_ERE in bin/l0-allowlist.ts.\n bashCure(CHECKOUT_MAIN_PULL_CMD, false,\n 'node_modules is NEWER than the pin AND you are on main — the PIN is the stale side, so '\n + 'sync first and install second; a bare install would downgrade you'),\n ], renderShim()),\n new L0Fault(L0_FAULT_BIN_MISSING, 'guard bin missing (fresh clone / new worktree / package removed)',\n 'sh, before the bin runs', 'sh',\n [bashCure('pnpm install', true,\n 'this fault fires at all — nothing is installed in THIS tree, and a new git worktree '\n + 'copies no node_modules')],\n renderShim()),\n // U is X with the ONE input that inverts X's cure, which is why it is a separate fault and not a\n // sentence inside X's message: a BARE `pnpm install` is not a weaker fix here, it is a PROVABLE\n // no-op, and an agent that trusts the X text will run it until it gives up. See the ADD_HOOK_PKG\n // entry in l0-allowlist.ts for the incident.\n //\n // The ORDER of these three is the correction bought by a second incident. `pnpm add` used to be the\n // preferred cure, and it is the one cure that CANNOT be committed: a direct root dependency on\n // HOOK_PKG violates the umbrella rule (the root manifest depends on the umbrella ALONE), and the\n // message never said to revert it — so it was followed, and the workaround landed in a real\n // package.json. The package normally arrives WITH the umbrella, so a tree that is merely BEHIND is\n // the common cause and syncing is the cure that leaves a committable tree. The add stays last,\n // reachable, and explicitly labelled as a session unblock rather than a fix.\n new L0Fault(L0_FAULT_UNDECLARED, `guard bin missing AND ${HOOK_PKG} is not declared in package.json`,\n 'sh, before the bin runs', 'sh',\n [\n bashCure(CHECKOUT_MAIN_PULL_CMD, true,\n `${HOOK_PKG} arrives WITH the umbrella, so a tree that is behind explains this without `\n + 'anything being mis-declared — sync first, then install'),\n bashCure('pnpm install', false,\n 'the sync (or a raised catalog pin in ' + WORKSPACE_MANIFEST + ', which is editable '\n + 'while the block is up) gave the installer something new to do — a BARE install with '\n + 'nothing changed reports \"Lockfile is up to date\" and leaves the tree as broken as it '\n + 'found it'),\n bashCure(ADD_HOOK_PKG_CMD, false,\n 'nothing else worked and you need this session back — it is a session unblock, NOT a '\n + `fix: revert it with 'pnpm remove ${HOOK_PKG}' before committing, because a direct `\n + 'root dependency on it violates the umbrella rule'),\n ],\n renderShim()),\n new L0Fault(L0_FAULT_BIN_BROKEN, 'guard bin present but CRASHED (exit code not 0 or 2 — corrupt node_modules)',\n 'sh, before the bin runs', 'sh',\n [bashCure(RECOVERY_CMD, true,\n 'this fault fires at all — a BARE pnpm install SKIPS the corrupt package, because pnpm sees '\n + 'the right version on disk and considers it installed; only the delete forces a rewrite')],\n renderShim()),\n // S covers the WHOLE managed hook surface, not just the shim: the committed ai-hook.sh, the\n // .claude/settings.json entries that register them AND the managed `env` entry that pins the Bash\n // cwd so the hooks resolve identically for every subagent. They only work as a set — a settings file left\n // on a superseded form silently changes who governs, re-pinning every tree to the\n // primary's release — and nothing validated the registration at all before it joined this fault.\n new L0Fault(L0_FAULT_SHIM_STALE, 'a webpieces-managed hook file, one of the harness hook registrations (.claude/settings.json, .codex/hooks.json) or the managed env entry does not match this release',\n 'the guard bin', 'JS',\n [\n // wp-upgrade-shim leads because it is the ONLY cure that repairs EVERY managed surface, and\n // it is still surgical: it rewrites ai-hook.sh, each harness's registration and the env entry\n // and touches no config, and it imports only fs/path so it runs on a tree too broken to load\n // the rule engine. The INSTALLER is deliberately NOT a cure here: it also migrates the config\n // and prompts for a target twice, which hangs a non-interactive agent.\n bashCure(UPGRADE_SHIM_CMD, true,\n 'this fault fires at all — it is the only cure that repairs EVERY managed surface '\n + '(ai-hook.sh, each harness hook registration, the anchoring of the neighbour hook '\n + 'commands registered beside ours, and the Claude settings env entry), and it '\n + 'touches no config; needs installed @webpieces/agent-workflow-rules 0.4.408 or newer'),\n // 2026-07-21: the version gap below caused a real \"command not found\" deadlock.\n bashCure(RESTORE_SHIM_CMD, false,\n 'the installed @webpieces/agent-workflow-rules is OLDER than 0.4.408, so wp-upgrade-shim does '\n + 'not exist yet — it is PARTIAL (it repairs ai-hook.sh and NOTHING else), so upgrade '\n + '@webpieces afterwards and run Option 1 to finish'),\n ],\n // The SAMPLE deny renders EVERY managed surface, built from HARNESS_REGISTRATIONS rather than\n // a hand-written trio — a doc that shows a three-surface deny while the guard can report four\n // is exactly the drift this generated-doc arrangement exists to make impossible.\n shimStaleDenyReason('', '', [\n SHIM_MARKER,\n ...HARNESS_REGISTRATIONS.flatMap((h: HarnessRegistration): readonly string[] => [h.registrationSurface, h.neighbourSurface]),\n ENV_SURFACE,\n REVIEWER_AGENT_SURFACE,\n ], false)),\n new L0Fault(L0_FAULT_CONFIG_MISSING, `${CONFIG_FILENAME} missing`,\n 'the guard bin', 'JS',\n [\n CONFIG_WRITE_CURE,\n // Kept, but demoted: it seeds the file and then PROMPTS twice for a hook target.\n bashCure(INSTALL_HOOKS_CMD, false,\n 'you are at an INTERACTIVE terminal and can answer its two hook-target prompts'),\n ], CONFIG_MISSING_REPORT),\n new L0Fault(L0_FAULT_CONFIG_OUT_OF_SYNC, `a loaded rule has no ${CONFIG_FILENAME} key`,\n 'the guard bin', 'JS',\n [CONFIG_WRITE_CURE], CONFIG_OUT_OF_SYNC_HEADER),\n];\n\n/**\n * One fault's FIX section, rendered from its `cures` array — literal commands only, never prose.\n *\n * This is the half that used to live in hand-written docs and drift. The three fields of L0Cure map\n * onto the three things a blocked reader needs and nothing else: WHAT to type (the call), WHETHER it is\n * the default (preferred), and WHEN to pick a sibling instead (discriminator). A cure with no\n * discriminator would render as a menu of equals, which is how an agent picks the wrong one.\n */\n// webpieces-disable no-function-outside-class -- pure string builder for renderGuardMatrixDoc below, beside the arrays it reads\nfunction renderFixSection(fault: L0Fault): string[] {\n const options = fault.cures.map((cure: L0Cure, i: number): string => {\n // A Bash cure is the command verbatim; a tool-shaped one is the file it edits (allowlist entry 2).\n const literal = cure.isCommand() ? `\\`${cure.call.command}\\`` : `edit \\`${cure.mention}\\` yourself`;\n const label = cure.preferred ? `Option ${i + 1} (preferred)` : `Option ${i + 1}`;\n return `- **${label}**: ${literal} ← pick this when ${cure.discriminator}`;\n });\n return [`### \\`${fault.code}\\` — ${fault.name}`, '', ...options, ''];\n}\n\n/**\n * Render webpieces.guard-matrix.md from L0_FAULTS + L0_ALLOWLIST.\n *\n * A unit test locks the committed template byte-identical to this output, the same way\n * templates/ai-hook.sh is locked to renderShim(). That is what makes the doc assertable instead of\n * aspirational: the table in the doc IS the array the guard consults.\n */\n// webpieces-disable no-function-outside-class -- pure string builder over the two exported arrays, beside them in this module\nexport function renderGuardMatrixDoc(): string {\n return [\n '# webpieces guard matrix — L0 (tooling integrity)',\n '',\n 'GENERATED from `L0_FAULTS` + `L0_ALLOWLIST` in `@webpieces/agent-workflow-rules`. Do not hand-edit —',\n 'a unit test locks this file byte-identical to `renderGuardMatrixDoc()`, so the table below is',\n 'the array the guard actually consults, not a description of it.',\n '',\n 'L0 is the OUTERMOST guard layer. It blocks work while `node_modules`, the committed shim, or',\n '`webpieces.config.json` are in a state that makes every other guard untrustworthy. If you are',\n 'reading this, one of the faults below fired and named this file.',\n '',\n '## The faults',\n '',\n 'THE JOIN KEYS ARE `guard`, `fault=` and `row=`. Every L0 deny opens',\n '`[<guard>] (layer=L0 fault=<code> row=3, …)`, and every audit line — from BOTH halves of L0, the',\n '`sh` shim and the guard bin — carries `layer=L0 row=<n> fault=<code>`. So one grep lands you in',\n 'the deny, the log line and the row below. The guard names come from `L0_FAULT_NAMES` and the row',\n 'numbers from `L0_ROW_*`, both spelled in exactly one place (`core/l0-fault-codes.ts`).',\n '',\n '| code | guard | fault | detected by | enforced in |',\n '|---|---|---|---|---|',\n ...L0_FAULTS.map((f: L0Fault): string =>\n `| \\`${f.code}\\` | \\`${L0_FAULT_NAMES[f.code]}\\` | ${f.name} | ${f.detectedBy} | ${f.enforcedIn} |`),\n '',\n 'First match wins. `D`/`X`/`U`/`K` are decided in POSIX `sh` inside the committed shim, BEFORE the',\n 'guard bin runs — a stale, missing or broken validator cannot be trusted to validate itself.',\n '',\n '## The fix, per fault',\n '',\n 'Every command below is rendered from that fault\\'s `cures` array and is asserted, by unit test,',\n 'to be accepted by `isAllowed()` — so nothing here can be a command the guard then rejects. Type',\n 'the option you pick EXACTLY as written and run nothing else on that line.',\n '',\n ...L0_FAULTS.flatMap(renderFixSection),\n ...renderMatrixAndAllowlist(),\n ].join('\\n');\n}\n\n/**\n * The second half of the doc: the three-row matrix and the ONE allowlist. Split out of\n * renderGuardMatrixDoc solely to keep it inside the method-line budget — the join order is what makes\n * the two halves one file, so keep them adjacent and keep the byte-lock test as the arbiter.\n */\n// webpieces-disable no-function-outside-class -- second half of renderGuardMatrixDoc's string, beside it in this module\nfunction renderMatrixAndAllowlist(): string[] {\n return [\n '## The matrix',\n '',\n 'L0 has NO genuine second dimension. Every branch reduces to one question:',\n '',\n '| # | fault | on the allowlist? | outcome |',\n '|---|---|---|---|',\n '| 1 | none | — | hand down to the next guard layer |',\n `| ${L0_ROW_ALLOWLISTED} | any | yes | PASS or ALLOW (see the entry) |`,\n `| ${L0_ROW_BLOCKED} | any | no | BLOCK — **only the message varies by fault** |`,\n '',\n `Row ${L0_ROW_BLOCKED} is the only row that blocks, so every L0 deny cites it — \\`row=${L0_ROW_BLOCKED}\\` in the`,\n 'deny header, `row=' + L0_ROW_BLOCKED + '` on the audit line, and this row here. Same numbers as L1 uses for',\n 'its own rows (see `L1_ROWS`), and for the same reason: a row number is IDENTITY, so it is never reused.',\n '',\n 'The tool is not a dimension either: \"any Read\" is an allowlist ENTRY, not a tool check.',\n '',\n '## The allowlist',\n '',\n 'ONE list, consulted identically by every fault. A cure that cannot help a given fault also',\n 'cannot hurt it, and gating each entry on a fault is what produced four real defects (a stale',\n 'shim that denied `pnpm install` and every git sync; faults that denied every Read; a config fault',\n 'that denied `rm -rf node_modules && pnpm install` while allowing a bare `pnpm install`).',\n '',\n '| # | allowed | outcome |',\n '|---|---|---|',\n ...L0_ALLOWLIST.map((e: L0AllowEntry, i: number): string => `| ${i + 1} | ${e.label} | ${e.kind.toUpperCase()} |`),\n '',\n '- **PASS** — L0 has no objection; the call falls THROUGH so the downstream guards still judge it.',\n '- **ALLOW** — terminal; bypasses everything, because a cure must stay reachable even when a',\n ' downstream guard would block it.',\n '',\n 'Every Bash entry is anchored to the WHOLE command. Appending `&& git status` makes it a DIFFERENT',\n 'command and it is rejected again — that is not the guard refusing its own cure.',\n '',\n 'On an UNGATED entry a leading `cd <dir> &&`, a trailing `2>&1` and a pipe into `tail`/`head` are',\n 'tolerated; nothing else is. **The harness-gated read row tolerates NONE of the three** — not the',\n '`cd` prefix, not the redirect, not the pipe — so `cat f 2>&1` and `cat f | head -20` are both',\n 'rejected. That is deliberate, not an oversight: the row means exactly what',\n '`core/shell-read-parity.ts` means by \"this is a read\", and that module treats a pipe or a redirect',\n 'as proof the command is more than one. Type the bare command.',\n '',\n '`git merge` is deliberately NOT on this list. Main is merged ONLY through the 3-point fork merge',\n '(`pnpm wp-start-update`, or `pnpm wp-start-upsert-pr` when a PR is already open).',\n '',\n '## Known asymmetry',\n '',\n 'Under `S`/`C`/`Y` the guard bin IS running, so a PASS really does fall through to the downstream',\n 'guards. Under `D`/`X`/`U`/`K` the bin is never executed, so there is nothing to fall through to and a',\n 'PASS degenerates into a terminal allow — reads are unguarded during those three faults.',\n '',\n '## Widening L0',\n '',\n 'Add an entry to `L0_ALLOWLIST` in `packages/tooling/agent-workflow-rules/src/bin/shim.ts`. That array is',\n 'the single source for the JS allowlist, the `grep -E` inside the rendered shim, and this file.',\n '',\n ];\n}\n\n/**\n * Drop the matrix doc where the AI can read it, and return its absolute path ('' if it could not be\n * written). Called from the L0 BLOCK path so the deny can say `READ <path>`.\n *\n * Best-effort by design: this runs while the tree is already known-broken, and a missing template (an\n * @webpieces/rules-config older than this package) must degrade the deny message, never replace it\n * with a crash.\n */\n// webpieces-disable no-function-outside-class -- sibling of renderGuardMatrixDoc in this module\n\n"]}
@@ -1,5 +1,5 @@
1
1
  {
2
- "_comment": "The webpieces PreToolUse hook wiring, plus the managed env entry. Install with `wp-install-ai-hooks` (which lets you pick a location per hook); this file just shows the shape. THREE managed surfaces are enforced together and `wp-upgrade-shim` repairs all three: (1) the committed .claude/webpieces/ai-hook.sh, (2) these registration entries, (3) the env entry below. The Rules hook validates code-style on Write/Edit/MultiEdit; the Guards hook protects git/PR/branch and matches Write|Edit|MultiEdit|Bash|Read - Read carries no guard but the guards hook owns the per-invocation audit log, and a Read is never blocked. BOTH hooks are registered ABSOLUTE via $CLAUDE_PROJECT_DIR, so the MAIN tree governs every tree. This replaced a three-hook RELATIVE form whose third hook (guarantee-root.sh, L-1) existed only to keep the relative path resolvable, and paid for it by denying every `cd` into a subdirectory; an absolute path resolves from any cwd, so that hook is deleted and `wp-upgrade-shim` removes any stale entry and the file. A linked worktree never had its own release anyway - it has no node_modules, so the shim's upward walk already ran the main tree's binary. When a worktree PINS a different @webpieces, L1 row 8 (trinary-version-skew) blocks and names the fix. CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR pins the Bash cwd to the project root so a verdict never depends on where an earlier cd left the shell; settings env is inherited, so every subagent gets the same cwd and the same verdict.",
2
+ "_comment": "The webpieces PreToolUse hook wiring, plus the managed env entry. Install with `wp-install-ai-hooks` (which lets you pick a location per hook); this file just shows the shape. THREE managed surfaces are enforced together and `wp-upgrade-shim` repairs all three: (1) the committed .claude/webpieces/ai-hook.sh, (2) these registration entries, (3) the env entry below. The Rules hook validates code-style on Write/Edit/MultiEdit; the Guards hook protects git/PR/branch and matches Write|Edit|MultiEdit|Bash|Read - Read carries no guard but the guards hook owns the per-invocation audit log, and a Read is never blocked. BOTH hooks are registered ABSOLUTE via $CLAUDE_PROJECT_DIR, so the MAIN tree governs every tree. This replaced a three-hook RELATIVE form whose third hook (guarantee-root.sh, L-1) existed only to keep the relative path resolvable, and paid for it by denying every `cd` into a subdirectory; an absolute path resolves from any cwd, so that hook is deleted. A linked worktree never had its own release anyway - it has no node_modules, so the shim's upward walk already ran the main tree's binary. When a worktree PINS a different @webpieces, L1 row 8 (trinary-version-skew) blocks and names the fix. CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR pins the Bash cwd to the project root so a verdict never depends on where an earlier cd left the shell; settings env is inherited, so every subagent gets the same cwd and the same verdict.",
3
3
  "env": {
4
4
  "CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR": "1"
5
5
  },