@webpieces/ai-hook-rules 0.4.594 → 0.4.596
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 +2 -2
- package/src/adapters/claude-code-response.d.ts +1 -1
- package/src/adapters/claude-code-response.js +7 -2
- package/src/adapters/claude-code-response.js.map +1 -1
- package/src/adapters/hook-core.js +18 -8
- package/src/adapters/hook-core.js.map +1 -1
- package/src/bin/shim-audit-log.d.ts +5 -3
- package/src/bin/shim-audit-log.js +7 -4
- package/src/bin/shim-audit-log.js.map +1 -1
- package/src/bin/shim.js +5 -4
- package/src/bin/shim.js.map +1 -1
- package/src/core/decision-log.d.ts +12 -4
- package/src/core/decision-log.js +25 -6
- package/src/core/decision-log.js.map +1 -1
- package/src/core/l0-fault-codes.d.ts +33 -0
- package/src/core/l0-fault-codes.js +61 -0
- package/src/core/l0-fault-codes.js.map +1 -0
- package/src/core/l0-matrix.js +8 -7
- package/src/core/l0-matrix.js.map +1 -1
- package/src/core/l1-doc.d.ts +7 -0
- package/src/core/l1-doc.js +259 -0
- package/src/core/l1-doc.js.map +1 -0
- package/src/core/l1-rows.d.ts +141 -0
- package/src/core/l1-rows.js +229 -0
- package/src/core/l1-rows.js.map +1 -0
- package/src/core/rejection-log.js +5 -1
- package/src/core/rejection-log.js.map +1 -1
- package/src/core/runner.js +45 -8
- package/src/core/runner.js.map +1 -1
- package/src/core/types.d.ts +11 -1
- package/src/core/types.js +13 -1
- package/src/core/types.js.map +1 -1
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// ---------------------------------------------------------------------------
|
|
3
|
+
// THE L0 FAULT CODEBOOK — one letter per fault, declared HERE and nowhere else.
|
|
4
|
+
//
|
|
5
|
+
// Both halves of L0 stamp `fault=<code>` onto their audit lines: the POSIX `sh` shim writes D/X/U/K
|
|
6
|
+
// (shim-audit-log.ts), and the guard bin writes S/C/Y in JS (decision-log.ts, via runner.ts and
|
|
7
|
+
// hook-core.ts). The whole value of that field is that ONE grep — `grep 'fault=S'` — spans the entire
|
|
8
|
+
// trail, and that the faults actually observed can be diffed against `L0_FAULTS`. Both properties hold
|
|
9
|
+
// only while every emitter spells the letters the SAME way, and a hand-retyped 'S' in one emitter is
|
|
10
|
+
// exactly the drift this module exists to make impossible.
|
|
11
|
+
//
|
|
12
|
+
// It used to be retyped: the shim assigned `WP_FAULT=X` as a literal, SHIM_LOG_FAULTS listed the four
|
|
13
|
+
// sh-side letters again, and L0_FAULTS listed all seven a third time. Three spellings of one
|
|
14
|
+
// vocabulary, held together by a unit test that could only notice AFTER they diverged.
|
|
15
|
+
//
|
|
16
|
+
// This module is a LEAF — no imports at all — on purpose. `l0-matrix.ts` (core) builds `L0_FAULTS`
|
|
17
|
+
// from these constants and `shim-audit-log.ts` / `shim.ts` (bin) render them into the shim; parking the
|
|
18
|
+
// constants in either of those two would make the other one a core↔bin import cycle. It also keeps the
|
|
19
|
+
// shim renderer dependency-light, which it must be: it has to work on a tree too broken to load the
|
|
20
|
+
// rule engine.
|
|
21
|
+
// ---------------------------------------------------------------------------
|
|
22
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
23
|
+
exports.L0_JS_FAULT_CODES = exports.L0_SH_FAULT_CODES = exports.L0_FAULT_NONE = exports.L0_FAULT_CONFIG_OUT_OF_SYNC = exports.L0_FAULT_CONFIG_MISSING = exports.L0_FAULT_SHIM_STALE = exports.L0_FAULT_BIN_BROKEN = exports.L0_FAULT_UNDECLARED = exports.L0_FAULT_BIN_MISSING = exports.L0_FAULT_DRIFT = void 0;
|
|
24
|
+
/** `D` — version drift: the root package.json pin != the installed version. Decided in `sh`. */
|
|
25
|
+
exports.L0_FAULT_DRIFT = 'D';
|
|
26
|
+
/** `X` — the guard bin is missing (fresh clone, new worktree, package removed). Decided in `sh`. */
|
|
27
|
+
exports.L0_FAULT_BIN_MISSING = 'X';
|
|
28
|
+
/** `U` — the bin is missing AND nothing declares the package, so an install is a no-op. `sh`. */
|
|
29
|
+
exports.L0_FAULT_UNDECLARED = 'U';
|
|
30
|
+
/** `K` — the bin is present but CRASHED (corrupt node_modules). Decided in `sh`. */
|
|
31
|
+
exports.L0_FAULT_BIN_BROKEN = 'K';
|
|
32
|
+
/** `S` — the committed `.claude/webpieces/ai-hook.sh` != `renderShim()`. Decided in the bin, in JS. */
|
|
33
|
+
exports.L0_FAULT_SHIM_STALE = 'S';
|
|
34
|
+
/** `C` — `webpieces.config.json` is missing. Decided in the bin, in JS. */
|
|
35
|
+
exports.L0_FAULT_CONFIG_MISSING = 'C';
|
|
36
|
+
/** `Y` — a loaded rule has no `webpieces.config.json` key. Decided in the bin, in JS. */
|
|
37
|
+
exports.L0_FAULT_CONFIG_OUT_OF_SYNC = 'Y';
|
|
38
|
+
/**
|
|
39
|
+
* No fault AT THIS LAYER — the value every audit line carries when nothing fired.
|
|
40
|
+
*
|
|
41
|
+
* Never a claim that nothing was wrong: a `fault=-` line from the `sh` shim only says the sh half found
|
|
42
|
+
* nothing, and the bin it then exec'd may still have blocked on S/C/Y and stamped its own line.
|
|
43
|
+
*/
|
|
44
|
+
exports.L0_FAULT_NONE = '-';
|
|
45
|
+
/**
|
|
46
|
+
* The faults decided in POSIX `sh`, BEFORE the bin runs — a stale, missing or broken validator cannot
|
|
47
|
+
* be trusted to validate itself. In first-match-wins order.
|
|
48
|
+
*/
|
|
49
|
+
exports.L0_SH_FAULT_CODES = [
|
|
50
|
+
exports.L0_FAULT_DRIFT, exports.L0_FAULT_BIN_MISSING, exports.L0_FAULT_UNDECLARED, exports.L0_FAULT_BIN_BROKEN,
|
|
51
|
+
];
|
|
52
|
+
/**
|
|
53
|
+
* The faults decided INSIDE the guard bin, in JS. These reached the audit trail with no fault label at
|
|
54
|
+
* all until the JS emitters started stamping them: an `S` storm that blocked an agent for ~20 tool
|
|
55
|
+
* calls left two lines in hook-rejection.log, both attributed to a downstream rule, and nothing
|
|
56
|
+
* anywhere identifying L0.
|
|
57
|
+
*/
|
|
58
|
+
exports.L0_JS_FAULT_CODES = [
|
|
59
|
+
exports.L0_FAULT_SHIM_STALE, exports.L0_FAULT_CONFIG_MISSING, exports.L0_FAULT_CONFIG_OUT_OF_SYNC,
|
|
60
|
+
];
|
|
61
|
+
//# sourceMappingURL=l0-fault-codes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"l0-fault-codes.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/core/l0-fault-codes.ts"],"names":[],"mappings":";AAAA,8EAA8E;AAC9E,gFAAgF;AAChF,EAAE;AACF,oGAAoG;AACpG,gGAAgG;AAChG,sGAAsG;AACtG,uGAAuG;AACvG,qGAAqG;AACrG,2DAA2D;AAC3D,EAAE;AACF,sGAAsG;AACtG,6FAA6F;AAC7F,uFAAuF;AACvF,EAAE;AACF,mGAAmG;AACnG,wGAAwG;AACxG,uGAAuG;AACvG,oGAAoG;AACpG,eAAe;AACf,8EAA8E;;;AAE9E,gGAAgG;AACnF,QAAA,cAAc,GAAG,GAAG,CAAC;AAElC,oGAAoG;AACvF,QAAA,oBAAoB,GAAG,GAAG,CAAC;AAExC,iGAAiG;AACpF,QAAA,mBAAmB,GAAG,GAAG,CAAC;AAEvC,oFAAoF;AACvE,QAAA,mBAAmB,GAAG,GAAG,CAAC;AAEvC,uGAAuG;AAC1F,QAAA,mBAAmB,GAAG,GAAG,CAAC;AAEvC,2EAA2E;AAC9D,QAAA,uBAAuB,GAAG,GAAG,CAAC;AAE3C,yFAAyF;AAC5E,QAAA,2BAA2B,GAAG,GAAG,CAAC;AAE/C;;;;;GAKG;AACU,QAAA,aAAa,GAAG,GAAG,CAAC;AAEjC;;;GAGG;AACU,QAAA,iBAAiB,GAAG;IAC7B,sBAAc,EAAE,4BAAoB,EAAE,2BAAmB,EAAE,2BAAmB;CACxE,CAAC;AAEX;;;;;GAKG;AACU,QAAA,iBAAiB,GAAG;IAC7B,2BAAmB,EAAE,+BAAuB,EAAE,mCAA2B;CACnE,CAAC","sourcesContent":["// ---------------------------------------------------------------------------\n// THE L0 FAULT CODEBOOK — one letter per fault, declared HERE and nowhere else.\n//\n// Both halves of L0 stamp `fault=<code>` onto their audit lines: the POSIX `sh` shim writes D/X/U/K\n// (shim-audit-log.ts), and the guard bin writes S/C/Y in JS (decision-log.ts, via runner.ts and\n// hook-core.ts). The whole value of that field is that ONE grep — `grep 'fault=S'` — spans the entire\n// trail, and that the faults actually observed can be diffed against `L0_FAULTS`. Both properties hold\n// only while every emitter spells the letters the SAME way, and a hand-retyped 'S' in one emitter is\n// exactly the drift this module exists to make impossible.\n//\n// It used to be retyped: the shim assigned `WP_FAULT=X` as a literal, SHIM_LOG_FAULTS listed the four\n// sh-side letters again, and L0_FAULTS listed all seven a third time. Three spellings of one\n// vocabulary, held together by a unit test that could only notice AFTER they diverged.\n//\n// This module is a LEAF — no imports at all — on purpose. `l0-matrix.ts` (core) builds `L0_FAULTS`\n// from these constants and `shim-audit-log.ts` / `shim.ts` (bin) render them into the shim; parking the\n// constants in either of those two would make the other one a core↔bin import cycle. It also keeps the\n// shim renderer dependency-light, which it must be: it has to work on a tree too broken to load the\n// rule engine.\n// ---------------------------------------------------------------------------\n\n/** `D` — version drift: the root package.json pin != the installed version. Decided in `sh`. */\nexport const L0_FAULT_DRIFT = 'D';\n\n/** `X` — the guard bin is missing (fresh clone, new worktree, package removed). Decided in `sh`. */\nexport const L0_FAULT_BIN_MISSING = 'X';\n\n/** `U` — the bin is missing AND nothing declares the package, so an install is a no-op. `sh`. */\nexport const L0_FAULT_UNDECLARED = 'U';\n\n/** `K` — the bin is present but CRASHED (corrupt node_modules). Decided in `sh`. */\nexport const L0_FAULT_BIN_BROKEN = 'K';\n\n/** `S` — the committed `.claude/webpieces/ai-hook.sh` != `renderShim()`. Decided in the bin, in JS. */\nexport const L0_FAULT_SHIM_STALE = 'S';\n\n/** `C` — `webpieces.config.json` is missing. Decided in the bin, in JS. */\nexport const L0_FAULT_CONFIG_MISSING = 'C';\n\n/** `Y` — a loaded rule has no `webpieces.config.json` key. Decided in the bin, in JS. */\nexport const L0_FAULT_CONFIG_OUT_OF_SYNC = 'Y';\n\n/**\n * No fault AT THIS LAYER — the value every audit line carries when nothing fired.\n *\n * Never a claim that nothing was wrong: a `fault=-` line from the `sh` shim only says the sh half found\n * nothing, and the bin it then exec'd may still have blocked on S/C/Y and stamped its own line.\n */\nexport const L0_FAULT_NONE = '-';\n\n/**\n * The faults decided in POSIX `sh`, BEFORE the bin runs — a stale, missing or broken validator cannot\n * be trusted to validate itself. In first-match-wins order.\n */\nexport const L0_SH_FAULT_CODES = [\n L0_FAULT_DRIFT, L0_FAULT_BIN_MISSING, L0_FAULT_UNDECLARED, L0_FAULT_BIN_BROKEN,\n] as const;\n\n/**\n * The faults decided INSIDE the guard bin, in JS. These reached the audit trail with no fault label at\n * all until the JS emitters started stamping them: an `S` storm that blocked an agent for ~20 tool\n * calls left two lines in hook-rejection.log, both attributed to a downstream rule, and nothing\n * anywhere identifying L0.\n */\nexport const L0_JS_FAULT_CODES = [\n L0_FAULT_SHIM_STALE, L0_FAULT_CONFIG_MISSING, L0_FAULT_CONFIG_OUT_OF_SYNC,\n] as const;\n"]}
|
package/src/core/l0-matrix.js
CHANGED
|
@@ -8,6 +8,7 @@ const rules_config_1 = require("@webpieces/rules-config");
|
|
|
8
8
|
const shim_1 = require("../bin/shim");
|
|
9
9
|
const guarantee_root_1 = require("../bin/guarantee-root");
|
|
10
10
|
const hook_registration_1 = require("../bin/hook-registration");
|
|
11
|
+
const l0_fault_codes_1 = require("./l0-fault-codes");
|
|
11
12
|
const to_error_1 = require("./to-error");
|
|
12
13
|
// ---------------------------------------------------------------------------
|
|
13
14
|
// L0 — the TOOLING-INTEGRITY layer, as data.
|
|
@@ -137,7 +138,7 @@ function bashCure(command, preferred, discriminator) {
|
|
|
137
138
|
* the bin, in JS. One model, two enforcement points.
|
|
138
139
|
*/
|
|
139
140
|
exports.L0_FAULTS = [
|
|
140
|
-
new L0Fault(
|
|
141
|
+
new L0Fault(l0_fault_codes_1.L0_FAULT_DRIFT, 'version drift — root package.json pin != installed version', 'sh, before the bin runs', 'sh', [
|
|
141
142
|
// `pnpm install` clears D in BOTH directions — it makes installed == pin by definition — so
|
|
142
143
|
// it is always the preferred cure. The direction only decides whether the PIN is the version
|
|
143
144
|
// you WANT, which is what the second cure is for.
|
|
@@ -146,21 +147,21 @@ exports.L0_FAULTS = [
|
|
|
146
147
|
bashCure('git pull', false, 'node_modules is NEWER than the pin AND you are on main — the PIN is the stale side, so '
|
|
147
148
|
+ 'pull first and install second; a bare install would downgrade you'),
|
|
148
149
|
], (0, shim_1.renderShim)()),
|
|
149
|
-
new L0Fault(
|
|
150
|
+
new L0Fault(l0_fault_codes_1.L0_FAULT_BIN_MISSING, 'guard bin missing (fresh clone / new worktree / package removed)', 'sh, before the bin runs', 'sh', [bashCure('pnpm install', true, 'this fault fires at all — nothing is installed in THIS tree, and a new git worktree '
|
|
150
151
|
+ 'copies no node_modules')], (0, shim_1.renderShim)()),
|
|
151
152
|
// U is X with the ONE input that inverts X's cure, which is why it is a separate fault and not a
|
|
152
153
|
// sentence inside X's message: when nothing declares the package, `pnpm install` is not a weaker fix,
|
|
153
154
|
// it is a PROVABLE no-op, and an agent that trusts the X text will run it until it gives up. See the
|
|
154
155
|
// ADD_HOOK_PKG entry in l0-allowlist.ts for the incident.
|
|
155
|
-
new L0Fault(
|
|
156
|
+
new L0Fault(l0_fault_codes_1.L0_FAULT_UNDECLARED, `guard bin missing AND ${shim_1.HOOK_PKG} is not declared in package.json`, 'sh, before the bin runs', 'sh', [bashCure(shim_1.ADD_HOOK_PKG_CMD, true, 'this fault fires at all — package.json asks for nothing, so pnpm install reports '
|
|
156
157
|
+ '"Lockfile is up to date" and leaves the tree exactly as broken as it found it')], (0, shim_1.renderShim)()),
|
|
157
|
-
new L0Fault(
|
|
158
|
+
new L0Fault(l0_fault_codes_1.L0_FAULT_BIN_BROKEN, 'guard bin present but CRASHED (exit code not 0 or 2 — corrupt node_modules)', 'sh, before the bin runs', 'sh', [bashCure(shim_1.RECOVERY_CMD, true, 'this fault fires at all — a BARE pnpm install SKIPS the corrupt package, because pnpm sees '
|
|
158
159
|
+ 'the right version on disk and considers it installed; only the delete forces a rewrite')], (0, shim_1.renderShim)()),
|
|
159
160
|
// S covers the WHOLE managed hook surface, not just the shim: the two committed .sh files AND the
|
|
160
161
|
// .claude/settings.json entries that register them. They only work as a set — a settings file left
|
|
161
162
|
// on the old two-absolute-hook form disables the L-1 hook and re-pins every worktree to the
|
|
162
163
|
// primary's release — and nothing validated the registration at all before it joined this fault.
|
|
163
|
-
new L0Fault(
|
|
164
|
+
new L0Fault(l0_fault_codes_1.L0_FAULT_SHIM_STALE, 'a webpieces-managed hook file or the .claude/settings.json registration does not match this release', 'the guard bin', 'JS', [
|
|
164
165
|
// wp-upgrade-shim leads because it is now the ONLY cure that repairs all three, and it is
|
|
165
166
|
// still surgical: it rewrites the two .sh files and the registration and touches no config,
|
|
166
167
|
// and it imports only fs/path so it runs on a tree too broken to load the rule engine. The
|
|
@@ -174,12 +175,12 @@ exports.L0_FAULTS = [
|
|
|
174
175
|
+ 'not exist yet — it is PARTIAL (it repairs ai-hook.sh and NOTHING else), so upgrade '
|
|
175
176
|
+ '@webpieces afterwards and run Option 1 to finish'),
|
|
176
177
|
], (0, shim_1.shimStaleDenyReason)('', '', [shim_1.SHIM_MARKER, guarantee_root_1.GUARANTEE_ROOT_MARKER, hook_registration_1.REGISTRATION_SURFACE])),
|
|
177
|
-
new L0Fault(
|
|
178
|
+
new L0Fault(l0_fault_codes_1.L0_FAULT_CONFIG_MISSING, `${rules_config_1.CONFIG_FILENAME} missing`, 'the guard bin', 'JS', [
|
|
178
179
|
CONFIG_WRITE_CURE,
|
|
179
180
|
// Kept, but demoted: it seeds the file and then PROMPTS twice for a hook target.
|
|
180
181
|
bashCure(shim_1.INSTALL_HOOKS_CMD, false, 'you are at an INTERACTIVE terminal and can answer its two hook-target prompts'),
|
|
181
182
|
], exports.CONFIG_MISSING_REPORT),
|
|
182
|
-
new L0Fault(
|
|
183
|
+
new L0Fault(l0_fault_codes_1.L0_FAULT_CONFIG_OUT_OF_SYNC, `a loaded rule has no ${rules_config_1.CONFIG_FILENAME} key`, 'the guard bin', 'JS', [CONFIG_WRITE_CURE], exports.CONFIG_OUT_OF_SYNC_HEADER),
|
|
183
184
|
];
|
|
184
185
|
/**
|
|
185
186
|
* One fault's FIX section, rendered from its `cures` array — literal commands only, never prose.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"l0-matrix.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/core/l0-matrix.ts"],"names":[],"mappings":";;;AA2OA,oDA8BC;AAmED,kDASC;AAID,gDAGC;AA5VD,0DAAyE;AAEzE,sCAGqB;AACrB,0DAA8D;AAC9D,gEAAgE;AAChE,yCAAqC;AAErC,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;AACU,QAAA,gBAAgB,GAAG,2BAA2B,CAAC;AAE5D;;;;;;;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,wDA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AAE;QACF,2BAA2B;QAC3B,eAAe;QACf,GAAG,mBAAY,CAAC,GAAG,CAAC,CAAC,CAAe,EAAE,CAAS,EAAU,EAAE,CAAC,KAAK,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,+FAA+F;QAC/F,kGAAkG;QAClG,6FAA6F;QAC7F,EAAE;QACF,kGAAkG;QAClG,mFAAmF;QACnF,EAAE;QACF,oBAAoB;QACpB,EAAE;QACF,kGAAkG;QAClG,uGAAuG;QACvG,yFAAyF;QACzF,EAAE;QACF,gBAAgB;QAChB,EAAE;QACF,mGAAmG;QACnG,gGAAgG;QAChG,EAAE;KACL,CAAC;AACN,CAAC;AAED;;;;;;;GAOG;AACH,gGAAgG;AAChG,SAAgB,mBAAmB,CAAC,aAAqB;IACrD,8DAA8D;IAC9D,IAAI,CAAC;QACD,OAAO,IAAA,4BAAa,EAAC,aAAa,EAAE,wBAAgB,CAAC,CAAC;IAC1D,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,KAAK,KAAK,CAAC,CAAC,0DAA0D;QACtE,OAAO,EAAE,CAAC;IACd,CAAC;AACL,CAAC;AAED,iGAAiG;AACjG,+FAA+F;AAC/F,SAAgB,kBAAkB,CAAC,OAAe;IAC9C,IAAI,OAAO,KAAK,EAAE;QAAE,OAAO,EAAE,CAAC;IAC9B,OAAO,0FAA0F,OAAO,wDAAwD,CAAC;AACrK,CAAC","sourcesContent":["import { CONFIG_FILENAME, writeTemplate } from '@webpieces/rules-config';\n\nimport {\n ADD_HOOK_PKG_CMD, HOOK_PKG, INSTALL_HOOKS_CMD, L0AllowEntry, L0Call, L0_ALLOWLIST, RECOVERY_CMD,\n RESTORE_SHIM_CMD, SHIM_MARKER, UPGRADE_SHIM_CMD, renderShim, shimStaleDenyReason,\n} from '../bin/shim';\nimport { GUARANTEE_ROOT_MARKER } from '../bin/guarantee-root';\nimport { REGISTRATION_SURFACE } from '../bin/hook-registration';\nimport { toError } from './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 const GUARD_MATRIX_DOC = 'webpieces.guard-matrix.md';\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 CLAUDE.md\n * 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 readonly code: string,\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.\nexport const CONFIG_MISSING_REPORT =\n `${CONFIG_FILENAME} not found — the webpieces guards cannot run without it, so every other tool call is blocked.\\n` +\n 'THIS IS NOT A DEADLOCK: both options below are explicitly allowed through while this guard is up.\\n' +\n `OPTION 1 (preferred — it needs no other tool and it never prompts) - create ${CONFIG_FILENAME}\\n` +\n 'yourself: any Read, and any Write/Edit whose target is that file, is always allowed through, so\\n' +\n 'you can inspect the repo and write it. The validator reports EVERY missing/invalid entry at once\\n' +\n '(each with the snippet to paste), so a minimal first draft converges in about two passes.\\n' +\n 'OPTION 2 (pick this ONLY at an interactive terminal where you can answer its two prompts) - run\\n' +\n 'EXACTLY this command to seed the config: `pnpm exec wp-install-ai-hooks`. It goes on to wire the\\n' +\n 'Claude Code hooks and asks for a target twice, which hangs a non-interactive session.\\n' +\n 'Do not append anything to the option you pick — the allowlist is anchored to the whole command.';\n\n// The first line of the fault-Y deny (built out in runner.checkConfigSync, which appends the per-rule\n// detail). Kept here so the fault table quotes the same text the runner emits.\nexport const CONFIG_OUT_OF_SYNC_HEADER =\n `${CONFIG_FILENAME} is out of sync — new built-in rules are present that have no entry in ${CONFIG_FILENAME}.`;\n\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('D', '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 bashCure('git pull', false,\n 'node_modules is NEWER than the pin AND you are on main — the PIN is the stale side, so '\n + 'pull first and install second; a bare install would downgrade you'),\n ], renderShim()),\n new L0Fault('X', '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: when nothing declares the package, `pnpm install` is not a weaker fix,\n // it is a PROVABLE no-op, and an agent that trusts the X text will run it until it gives up. See the\n // ADD_HOOK_PKG entry in l0-allowlist.ts for the incident.\n new L0Fault('U', `guard bin missing AND ${HOOK_PKG} is not declared in package.json`,\n 'sh, before the bin runs', 'sh',\n [bashCure(ADD_HOOK_PKG_CMD, true,\n 'this fault fires at all — package.json asks for nothing, so pnpm install reports '\n + '\"Lockfile is up to date\" and leaves the tree exactly as broken as it found it')],\n renderShim()),\n new L0Fault('K', '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 two committed .sh files AND the\n // .claude/settings.json entries that register them. They only work as a set — a settings file left\n // on the old two-absolute-hook form disables the L-1 hook and re-pins every worktree to the\n // primary's release — and nothing validated the registration at all before it joined this fault.\n new L0Fault('S', 'a webpieces-managed hook file or the .claude/settings.json registration does not match this release',\n 'the guard bin', 'JS',\n [\n // wp-upgrade-shim leads because it is now the ONLY cure that repairs all three, and it is\n // still surgical: it rewrites the two .sh files and the registration and touches no config,\n // and it imports only fs/path so it runs on a tree too broken to load the rule engine. The\n // INSTALLER is deliberately NOT a cure here: it also migrates the config and prompts for a\n // 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 all three managed things '\n + '(both .sh files and the settings.json registration) and it touches no config; needs '\n + 'installed @webpieces/ai-hook-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/ai-hook-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 shimStaleDenyReason('', '', [SHIM_MARKER, GUARANTEE_ROOT_MARKER, REGISTRATION_SURFACE])),\n new L0Fault('C', `${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('Y', `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/ai-hook-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 '| code | fault | detected by | enforced in |',\n '|---|---|---|---|',\n ...L0_FAULTS.map((f: L0Fault): string => `| \\`${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 '| 2 | any | yes | PASS or ALLOW (see the entry) |',\n '| 3 | any | no | BLOCK — **only the message varies by fault** |',\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 `git pull`; 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. A leading `cd <dir> &&`, a trailing `2>&1`',\n 'and a pipe into `tail`/`head` are tolerated; nothing else is. Appending `&& git status` makes it',\n 'a DIFFERENT command and it is rejected again — that is not the guard refusing its own cure.',\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/ai-hook-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\nexport function writeGuardMatrixDoc(workspaceRoot: string): string {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return writeTemplate(workspaceRoot, GUARD_MATRIX_DOC);\n } catch (err: unknown) {\n const error = toError(err);\n void error; // best-effort: no doc → the deny simply omits the pointer\n return '';\n }\n}\n\n/** The `READ <path>` pointer appended to an L0 deny, or '' when the doc could not be written. */\n// webpieces-disable no-function-outside-class -- sibling of writeGuardMatrixDoc in this module\nexport function guardMatrixPointer(docPath: string): string {\n if (docPath === '') return '';\n return ` The full L0 guard matrix - every fault and everything that is allowed through - is at ${docPath}; READ it if you are unsure why this call was blocked.`;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"l0-matrix.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/core/l0-matrix.ts"],"names":[],"mappings":";;;AA+O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AAuG;QACvG,yFAAyF;QACzF,EAAE;QACF,gBAAgB;QAChB,EAAE;QACF,mGAAmG;QACnG,gGAAgG;QAChG,EAAE;KACL,CAAC;AACN,CAAC;AAED;;;;;;;GAOG;AACH,gGAAgG;AAChG,SAAgB,mBAAmB,CAAC,aAAqB;IACrD,8DAA8D;IAC9D,IAAI,CAAC;QACD,OAAO,IAAA,4BAAa,EAAC,aAAa,EAAE,wBAAgB,CAAC,CAAC;IAC1D,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,KAAK,KAAK,CAAC,CAAC,0DAA0D;QACtE,OAAO,EAAE,CAAC;IACd,CAAC;AACL,CAAC;AAED,iGAAiG;AACjG,+FAA+F;AAC/F,SAAgB,kBAAkB,CAAC,OAAe;IAC9C,IAAI,OAAO,KAAK,EAAE;QAAE,OAAO,EAAE,CAAC;IAC9B,OAAO,0FAA0F,OAAO,wDAAwD,CAAC;AACrK,CAAC","sourcesContent":["import { CONFIG_FILENAME, writeTemplate } from '@webpieces/rules-config';\n\nimport {\n ADD_HOOK_PKG_CMD, HOOK_PKG, INSTALL_HOOKS_CMD, L0AllowEntry, L0Call, L0_ALLOWLIST, RECOVERY_CMD,\n RESTORE_SHIM_CMD, SHIM_MARKER, UPGRADE_SHIM_CMD, renderShim, shimStaleDenyReason,\n} from '../bin/shim';\nimport { GUARANTEE_ROOT_MARKER } from '../bin/guarantee-root';\nimport { REGISTRATION_SURFACE } from '../bin/hook-registration';\nimport {\n L0_FAULT_BIN_BROKEN, L0_FAULT_BIN_MISSING, L0_FAULT_CONFIG_MISSING, L0_FAULT_CONFIG_OUT_OF_SYNC,\n L0_FAULT_DRIFT, L0_FAULT_SHIM_STALE, L0_FAULT_UNDECLARED,\n} from './l0-fault-codes';\nimport { toError } from './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 const GUARD_MATRIX_DOC = 'webpieces.guard-matrix.md';\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 CLAUDE.md\n * 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 readonly code: string,\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.\nexport const CONFIG_MISSING_REPORT =\n `${CONFIG_FILENAME} not found — the webpieces guards cannot run without it, so every other tool call is blocked.\\n` +\n 'THIS IS NOT A DEADLOCK: both options below are explicitly allowed through while this guard is up.\\n' +\n `OPTION 1 (preferred — it needs no other tool and it never prompts) - create ${CONFIG_FILENAME}\\n` +\n 'yourself: any Read, and any Write/Edit whose target is that file, is always allowed through, so\\n' +\n 'you can inspect the repo and write it. The validator reports EVERY missing/invalid entry at once\\n' +\n '(each with the snippet to paste), so a minimal first draft converges in about two passes.\\n' +\n 'OPTION 2 (pick this ONLY at an interactive terminal where you can answer its two prompts) - run\\n' +\n 'EXACTLY this command to seed the config: `pnpm exec wp-install-ai-hooks`. It goes on to wire the\\n' +\n 'Claude Code hooks and asks for a target twice, which hangs a non-interactive session.\\n' +\n 'Do not append anything to the option you pick — the allowlist is anchored to the whole command.';\n\n// The first line of the fault-Y deny (built out in runner.checkConfigSync, which appends the per-rule\n// detail). Kept here so the fault table quotes the same text the runner emits.\nexport const CONFIG_OUT_OF_SYNC_HEADER =\n `${CONFIG_FILENAME} is out of sync — new built-in rules are present that have no entry in ${CONFIG_FILENAME}.`;\n\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 bashCure('git pull', false,\n 'node_modules is NEWER than the pin AND you are on main — the PIN is the stale side, so '\n + 'pull 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: when nothing declares the package, `pnpm install` is not a weaker fix,\n // it is a PROVABLE no-op, and an agent that trusts the X text will run it until it gives up. See the\n // ADD_HOOK_PKG entry in l0-allowlist.ts for the incident.\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 [bashCure(ADD_HOOK_PKG_CMD, true,\n 'this fault fires at all — package.json asks for nothing, so pnpm install reports '\n + '\"Lockfile is up to date\" and leaves the tree exactly as broken as it found it')],\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 two committed .sh files AND the\n // .claude/settings.json entries that register them. They only work as a set — a settings file left\n // on the old two-absolute-hook form disables the L-1 hook and re-pins every worktree 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 or the .claude/settings.json registration does not match this release',\n 'the guard bin', 'JS',\n [\n // wp-upgrade-shim leads because it is now the ONLY cure that repairs all three, and it is\n // still surgical: it rewrites the two .sh files and the registration and touches no config,\n // and it imports only fs/path so it runs on a tree too broken to load the rule engine. The\n // INSTALLER is deliberately NOT a cure here: it also migrates the config and prompts for a\n // 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 all three managed things '\n + '(both .sh files and the settings.json registration) and it touches no config; needs '\n + 'installed @webpieces/ai-hook-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/ai-hook-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 shimStaleDenyReason('', '', [SHIM_MARKER, GUARANTEE_ROOT_MARKER, REGISTRATION_SURFACE])),\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/ai-hook-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 '| code | fault | detected by | enforced in |',\n '|---|---|---|---|',\n ...L0_FAULTS.map((f: L0Fault): string => `| \\`${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 '| 2 | any | yes | PASS or ALLOW (see the entry) |',\n '| 3 | any | no | BLOCK — **only the message varies by fault** |',\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 `git pull`; 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. A leading `cd <dir> &&`, a trailing `2>&1`',\n 'and a pipe into `tail`/`head` are tolerated; nothing else is. Appending `&& git status` makes it',\n 'a DIFFERENT command and it is rejected again — that is not the guard refusing its own cure.',\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/ai-hook-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\nexport function writeGuardMatrixDoc(workspaceRoot: string): string {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return writeTemplate(workspaceRoot, GUARD_MATRIX_DOC);\n } catch (err: unknown) {\n const error = toError(err);\n void error; // best-effort: no doc → the deny simply omits the pointer\n return '';\n }\n}\n\n/** The `READ <path>` pointer appended to an L0 deny, or '' when the doc could not be written. */\n// webpieces-disable no-function-outside-class -- sibling of writeGuardMatrixDoc in this module\nexport function guardMatrixPointer(docPath: string): string {\n if (docPath === '') return '';\n return ` The full L0 guard matrix - every fault and everything that is allowed through - is at ${docPath}; READ it if you are unsure why this call was blocked.`;\n}\n"]}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Render guards/L1-location.md.
|
|
3
|
+
*
|
|
4
|
+
* Split into three consecutive halves purely to stay inside the method-line budget — the join order is
|
|
5
|
+
* what makes them one file, so keep them adjacent and keep the byte-lock test as the arbiter.
|
|
6
|
+
*/
|
|
7
|
+
export declare function renderL1Doc(): string;
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.renderL1Doc = renderL1Doc;
|
|
4
|
+
const l1_rows_1 = require("./l1-rows");
|
|
5
|
+
// ---------------------------------------------------------------------------
|
|
6
|
+
// guards/L1-location.md, rendered from L1_ROWS.
|
|
7
|
+
//
|
|
8
|
+
// Same arrangement as l0-matrix.renderGuardMatrixDoc(): one join('\n') of literal markdown lines with
|
|
9
|
+
// the ROW DATA interpolated from the array the guard consults. Everything that is not row data — every
|
|
10
|
+
// prose section — is a literal line here, because that is the half a generator cannot own.
|
|
11
|
+
//
|
|
12
|
+
// A unit test (l1-matrix.spec.ts) locks guards/L1-location.md byte-identical to renderL1Doc(), and
|
|
13
|
+
// `pnpm guards:generate` rewrites the file. So the table in the doc IS the array, not a description of
|
|
14
|
+
// it. This module, like l1-rows.ts, has no runtime imports outside this pair so the generator can load
|
|
15
|
+
// it without the package's transitive dependencies.
|
|
16
|
+
// ---------------------------------------------------------------------------
|
|
17
|
+
/** A dimension cell: the wildcard renders bare, every value renders as code. */
|
|
18
|
+
// webpieces-disable no-function-outside-class -- pure cell formatter for renderL1Doc below, in this render module
|
|
19
|
+
function cell(value) {
|
|
20
|
+
return value === '-' ? '-' : `\`${value}\``;
|
|
21
|
+
}
|
|
22
|
+
// webpieces-disable no-function-outside-class -- pure row formatter for renderL1Doc below, in this render module
|
|
23
|
+
function tableRow(row) {
|
|
24
|
+
const dims = [row.k, row.a, row.r, row.g, row.p].map(cell).join(' | ');
|
|
25
|
+
// Row 6 has no `why` — an EMPTY cell is `| |`, not `| |`. Two spaces would render the same in a
|
|
26
|
+
// browser and fail the byte-lock, which is the whole point of locking bytes rather than markdown.
|
|
27
|
+
const why = row.why === '' ? ' ' : ` ${row.why} `;
|
|
28
|
+
return `| ${row.num} | ${dims} | ${row.action.label} |${why}|`;
|
|
29
|
+
}
|
|
30
|
+
// webpieces-disable no-function-outside-class -- pure row formatter for renderL1Doc below, in this render module
|
|
31
|
+
function useCaseRow(useCase) {
|
|
32
|
+
return `| ${useCase.num} | ${useCase.symptom} | ${useCase.state} | ${useCase.verdict} | ${useCase.fix} |`;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Render guards/L1-location.md.
|
|
36
|
+
*
|
|
37
|
+
* Split into three consecutive halves purely to stay inside the method-line budget — the join order is
|
|
38
|
+
* what makes them one file, so keep them adjacent and keep the byte-lock test as the arbiter.
|
|
39
|
+
*/
|
|
40
|
+
// webpieces-disable no-function-outside-class -- pure string builder over L1_ROWS, beside the array it reads
|
|
41
|
+
function renderL1Doc() {
|
|
42
|
+
return [
|
|
43
|
+
...renderHead(),
|
|
44
|
+
...renderTable(),
|
|
45
|
+
...renderUseCases(),
|
|
46
|
+
...renderTail(),
|
|
47
|
+
].join('\n');
|
|
48
|
+
}
|
|
49
|
+
// Why L-1's guarantee-root and L1's force-to-root are NOT the same rule. Its own function because
|
|
50
|
+
// renderHead is at the 80-line method cap, and because this section is one self-contained argument.
|
|
51
|
+
// webpieces-disable no-function-outside-class -- prose section of renderL1Doc's string, beside it in this module
|
|
52
|
+
function renderTwoLayerForceToRoot() {
|
|
53
|
+
return [
|
|
54
|
+
'## Force-to-root is TWO rules, in two layers — do not collapse them',
|
|
55
|
+
'',
|
|
56
|
+
'Collapsing them is how the `shellAtRoot` bug happened the first time, and the two now live in different',
|
|
57
|
+
'layers, so it is worth stating plainly:',
|
|
58
|
+
'',
|
|
59
|
+
'| | judged by | what it judges | for | verdict |',
|
|
60
|
+
'|---|---|---|---|---|',
|
|
61
|
+
'| **L-1** | `.claude/webpieces/guarantee-root.sh` (POSIX sh, before any binary) | the `cd` **destination** of the command | **Bash** | ALLOW unless the destination is inside `$CLAUDE_PROJECT_DIR` and holds no `.git` — i.e. **sticky AND unguarded** |',
|
|
62
|
+
'| **L1** | `gitFromSubdirBlock` (`runner.ts`) | the post-`cd` `effectiveCwd` | **git / gh only** | BLOCK unless it is THE root |',
|
|
63
|
+
'',
|
|
64
|
+
'They ask different questions. L-1 asks *"can the relative guard hooks launch there?"* — because the',
|
|
65
|
+
'guard hooks are registered relative, and a hook that cannot resolve exits 127, which the harness treats',
|
|
66
|
+
'as a non-blocking error and lets the call proceed UNGUARDED. It therefore ALLOWS a `cd` into a foreign',
|
|
67
|
+
'nested clone (its own `.git`) and a `cd` outside the project (the harness resets the cwd next call),',
|
|
68
|
+
'neither of which L1 would tolerate for a `git` command. L1 asks *"is this git command being run from the',
|
|
69
|
+
'one root it is meant to run from?"*, which is a narrower question about a narrower set of commands.',
|
|
70
|
+
'',
|
|
71
|
+
'A denied `cd` never executes — PreToolUse denies the whole tool call before the shell moves — so there',
|
|
72
|
+
'is no bad state to recover from and L-1 needs no cure command on any allowlist.',
|
|
73
|
+
'',
|
|
74
|
+
];
|
|
75
|
+
}
|
|
76
|
+
// The three questions L1 answers, the preamble and the filter — all prose, none of it row data.
|
|
77
|
+
// webpieces-disable no-function-outside-class -- first section of renderL1Doc's string, beside it in this module
|
|
78
|
+
function renderHead() {
|
|
79
|
+
return [
|
|
80
|
+
'# L1 — location',
|
|
81
|
+
'',
|
|
82
|
+
'**Goal: is this call ours to judge, is the right AGENT making it, and is git being run from the root?**',
|
|
83
|
+
'',
|
|
84
|
+
'**Config key: `location-guard` (proposed).** Force-to-root and coordinator-in-worktree both have **no',
|
|
85
|
+
'config key today** and cannot be disabled; `excludePaths` is a top-level block, not a `hookGuards`',
|
|
86
|
+
'entry.',
|
|
87
|
+
'',
|
|
88
|
+
'',
|
|
89
|
+
'**Code:** `packages/tooling/ai-hook-rules/src/core/effective-tree.ts` (`EffectiveTreeResolver`,',
|
|
90
|
+
'`TreeKind`) · `packages/tooling/ai-hook-rules/src/core/runner.ts` (`l1LocationBlock`,',
|
|
91
|
+
'`gitFromSubdirBlock`, `filterByExcludedPaths`, the `foreign` check) ·',
|
|
92
|
+
'`packages/tooling/ai-hook-rules/src/core/coordinator-worktree.ts` (`CoordinatorWorktreeGuard`,',
|
|
93
|
+
'`AgentIdentity`).',
|
|
94
|
+
'',
|
|
95
|
+
'L1 answers three questions, and they are genuinely separate:',
|
|
96
|
+
'',
|
|
97
|
+
'1. **Do we govern this at all?** — the escape hatches, for other repos and non-governed paths.',
|
|
98
|
+
'2. **Is the WRONG AGENT standing here?** — the coordinator must not work inside a linked worktree.',
|
|
99
|
+
' Its governance is anchored to `$CLAUDE_PROJECT_DIR`, fixed at session start, which does NOT follow',
|
|
100
|
+
' a `cd`; a coordinator in a worktree therefore has its filesystem in one tree and its guards in',
|
|
101
|
+
' another, and every fault it is shown is measured against a tree it is not standing in. Work in a',
|
|
102
|
+
' worktree belongs to a **subagent bound to it**, which has both in one place.',
|
|
103
|
+
'3. **Is the agent stranded away from the root?** — force-to-root, git/gh only. Agents forget where',
|
|
104
|
+
' they are constantly, and `cd` gives them two different ways to be wrong: a `cd` that stays INSIDE',
|
|
105
|
+
' the workspace PERSISTS to later calls (so the shell can be parked in a subdirectory left by an',
|
|
106
|
+
' unrelated command turns earlier), while a `cd` that LEAVES it is reset by the harness, which says',
|
|
107
|
+
' so — `Shell cwd was reset to <root>`. Neither can be assumed, which is why every remedy names the',
|
|
108
|
+
' root explicitly instead of telling the agent to `cd` first.',
|
|
109
|
+
'',
|
|
110
|
+
...renderTwoLayerForceToRoot(),
|
|
111
|
+
'## Preamble — resolve the target first (Bash only)',
|
|
112
|
+
'',
|
|
113
|
+
'`EffectiveTreeResolver.resolve()` computes `effectiveCwd`: the directory the command actually runs in,',
|
|
114
|
+
'which is the shell\'s cwd unless the command leads with `cd <dir> &&`. **K is classified from',
|
|
115
|
+
'`effectiveCwd`, not from the shell\'s cwd** — so "a foreign repo that `cd`s into ours" is not a cell,',
|
|
116
|
+
'it is simply `pw` after resolution.',
|
|
117
|
+
'',
|
|
118
|
+
'Only a LEADING run of `cd`/`pushd` counts. A *trailing* `… && cd <exempt-tree>` must never',
|
|
119
|
+
'retroactively pull a command out of scope — that would smuggle a root-level `git push` past the',
|
|
120
|
+
'guards. Quoting is handled by `ShellSegmentScan`, so `echo "cd sub && git push"` is one opaque',
|
|
121
|
+
'segment and its quoted `cd` is never picked up.',
|
|
122
|
+
'',
|
|
123
|
+
'## Filter — not a dimension (all tools)',
|
|
124
|
+
'',
|
|
125
|
+
'`filterByExcludedPaths` drops every rule excluded for this path: the **target path** for',
|
|
126
|
+
'Read/Write/Edit, `effectiveCwd` for Bash. An empty rule list means allow. This is a filter, not a row:',
|
|
127
|
+
'"exempt" is what emerges when the list empties.',
|
|
128
|
+
'',
|
|
129
|
+
'`excludePaths` is **ONE glob list** (canonical: `"excludePaths": ["repositories/**"]`). The',
|
|
130
|
+
'`{ rules: [...], guards: [...] }` object is **retired and rejected**, with the union it must become',
|
|
131
|
+
'named in the error. `wp-install-ai-hooks` migrates it in place.',
|
|
132
|
+
'',
|
|
133
|
+
'This used to be a tolerated fallback, justified here by "rejecting it would block every Bash/Edit',
|
|
134
|
+
'including the edit that would fix it." **That was never true**, and the fallback it licensed is why',
|
|
135
|
+
'consumer configs — this repo\'s own included — sat on the dead shape for releases. A Write/Edit whose',
|
|
136
|
+
'target is `webpieces.config.json` is an unconditional **PASS** (see the L0 table above), and',
|
|
137
|
+
'`pnpm install` has an installer bypass, so an invalid config can always be repaired from inside the',
|
|
138
|
+
'block. Config rejection is self-recoverable by construction; see `retired-config-keys.ts` for the',
|
|
139
|
+
'policy and the reasoning.',
|
|
140
|
+
'',
|
|
141
|
+
];
|
|
142
|
+
}
|
|
143
|
+
// The legend, the table itself (ROW DATA), and the note on the two structural blocks.
|
|
144
|
+
// webpieces-disable no-function-outside-class -- second section of renderL1Doc's string, beside it in this module
|
|
145
|
+
function renderTable() {
|
|
146
|
+
return [
|
|
147
|
+
'## Legend',
|
|
148
|
+
'',
|
|
149
|
+
'| col | dimension | values |',
|
|
150
|
+
'|---|---|---|',
|
|
151
|
+
'| **K** | tree kind of the resolved target | `f` foreign repo · `o` outside any repo · `w` a LINKED worktree of ours · `pw` ours (primary **or** worktree) |',
|
|
152
|
+
'| **A** | who is calling | `c` the coordinator · `s` a subagent (or a caller that cannot tell) |',
|
|
153
|
+
'| **R** | command is provably read-only inspection | `n` · `y` |',
|
|
154
|
+
'| **G** | command invokes git/gh | `n` · `y` |',
|
|
155
|
+
'| **P** | position of the resolved target | `root` · `sub` |',
|
|
156
|
+
'',
|
|
157
|
+
'All of them are **Bash only**. Read/Write/Edit resolve their own target (`input.filePath`) and have no',
|
|
158
|
+
'dimensions — the filter is all that applies to them. **The Read tool is never blocked by L1.**',
|
|
159
|
+
'',
|
|
160
|
+
'A linked worktree is deliberately **not** foreign: it is the same project, so the guards run against',
|
|
161
|
+
'THAT tree\'s branch and cache. Every rule-scoped guard treats `p` and `w` alike, hence `pw`; row 3 below',
|
|
162
|
+
'is the ONE place they separate, and it turns on **A**, not on the tree.',
|
|
163
|
+
'',
|
|
164
|
+
'`A` comes from `agent_id`/`agent_type` in the PreToolUse payload, which Claude Code sends **only inside',
|
|
165
|
+
'a subagent**. Absent = the coordinator. A caller that cannot read the payload (the openclaw adapter,',
|
|
166
|
+
'library consumers) resolves to `s` — fail open, never guess someone into a block.',
|
|
167
|
+
'',
|
|
168
|
+
'`R` is `ReadOnlyInspectionScan` — the same paranoid "provably inert" test the unloadable-config escape',
|
|
169
|
+
'hatch uses (allowlisted viewers/searchers only, no redirects, no `sed -i`).',
|
|
170
|
+
'',
|
|
171
|
+
'## Table',
|
|
172
|
+
'',
|
|
173
|
+
'| # | K | A | R | G | P | act | why |',
|
|
174
|
+
'|---|---|---|---|---|---|---|---|',
|
|
175
|
+
...l1_rows_1.L1_ROWS.map(tableRow),
|
|
176
|
+
'',
|
|
177
|
+
'Rows 3 and 5 are the two structural blocks, and they run as ONE step (`l1LocationBlock` in `runner.ts`)',
|
|
178
|
+
'so they can never be reordered by accident — row 3 first, then force-to-root. Both sit after the L0',
|
|
179
|
+
'allowlist, after the `f` check, and after the `excludePaths` filter and the config-sync check. So a',
|
|
180
|
+
'cure (`cd <worktree> && pnpm install`) still reaches any tree: that is L0\'s invariant, and row 3 does',
|
|
181
|
+
'not weaken it.',
|
|
182
|
+
'',
|
|
183
|
+
];
|
|
184
|
+
}
|
|
185
|
+
// The use-case table (ROW DATA, in the doc's own numbering) and the two notes that follow it.
|
|
186
|
+
// webpieces-disable no-function-outside-class -- third section of renderL1Doc's string, beside it in this module
|
|
187
|
+
function renderUseCases() {
|
|
188
|
+
return [
|
|
189
|
+
'## L1 use cases',
|
|
190
|
+
'',
|
|
191
|
+
'Same row shape as L0: the **Fix** is literal or it is not a fix. `<root>` is the absolute workspace',
|
|
192
|
+
'root — the messages name it explicitly rather than telling you to `cd` first, for the reason in the',
|
|
193
|
+
'section head (neither the shell\'s cwd nor a `cd`\'s persistence can be assumed).',
|
|
194
|
+
'',
|
|
195
|
+
'| # | what you SEE (exact symptom) | state | verdict | Fix |',
|
|
196
|
+
'|---|---|---|---|---|',
|
|
197
|
+
...(0, l1_rows_1.allL1UseCases)().map(useCaseRow),
|
|
198
|
+
'',
|
|
199
|
+
'Row 8 is the one that changed. It used to be ALLOWED, because the predicate was',
|
|
200
|
+
'`shellAtRoot || cdsToRoot` — two variables OR\'d, so the same destination got opposite verdicts',
|
|
201
|
+
'depending on where the shell happened to start. It is now one variable, `effectiveCwd === root`.',
|
|
202
|
+
'',
|
|
203
|
+
'Row 12 is the incident that produced table row 3. The coordinator ran `git worktree add`, `cd`\'d in,',
|
|
204
|
+
'and worked there. An L0 version-drift fault then fired against the PRIMARY (pin `0.4.545` vs',
|
|
205
|
+
'`node_modules` `0.4.526`) and prescribed `pnpm install` — which ran in the WORKTREE, internally',
|
|
206
|
+
'consistent at `0.4.526`/`0.4.526`, so it succeeded, changed nothing in the measured tree, and the guard',
|
|
207
|
+
're-denied. Five identical installs later the agent had invented a theory about the harness stripping',
|
|
208
|
+
'its `cd` and handed the problem to the human. Note what row 15 says: the fix is NOT to deny that',
|
|
209
|
+
'install. It is to make the split state unreachable, so the wrong-tree install is never plausible.',
|
|
210
|
+
'',
|
|
211
|
+
];
|
|
212
|
+
}
|
|
213
|
+
// The known gap and the code anchors — prose, and the one section that must never be summarised away:
|
|
214
|
+
// three code comments point at it.
|
|
215
|
+
// webpieces-disable no-function-outside-class -- last section of renderL1Doc's string, beside it in this module
|
|
216
|
+
function renderTail() {
|
|
217
|
+
return [
|
|
218
|
+
'## Not done — `o` is not exempt yet',
|
|
219
|
+
'',
|
|
220
|
+
'Row 2 hands `\'outside\'` down to L2 rather than exempting it. `\'outside\'` is produced at',
|
|
221
|
+
'`effective-tree.ts` (`gitRoot === null`) carrying `governedRoot`, and **no code branches on it**, so a',
|
|
222
|
+
'command in no git repo is judged against the governed repo\'s branch and staleness state. That is a',
|
|
223
|
+
'wrong verdict, and `exempt` is the right action.',
|
|
224
|
+
'',
|
|
225
|
+
'**It must not ship alone.** Jurisdiction comes from the shell cwd, not from what the command touches,',
|
|
226
|
+
'so exempting `o` opens a bypass an agent reaches by typing `cd /tmp &&`:',
|
|
227
|
+
'',
|
|
228
|
+
'| command | today | with `o → exempt` alone |',
|
|
229
|
+
'|---|---|---|',
|
|
230
|
+
'| `cd /tmp && ls` | judged against the repo | exempt — **correct** |',
|
|
231
|
+
'| `cd /tmp && git -C $REPO commit` | L2 guards fire | exempt — **every L2 guard bypassed** |',
|
|
232
|
+
'| `cd /tmp && rm -rf $REPO/packages/http/src` | judged | exempt — **unguarded** |',
|
|
233
|
+
'',
|
|
234
|
+
'The two cases only separate once jurisdiction is judged on **what the command touches** (explicit',
|
|
235
|
+
'`git -C` / `--work-tree`, then path arguments, then the `cd`, then the shell cwd), with the fail-safe',
|
|
236
|
+
'rule that **any** resolved target inside `governedRoot` means `pw`. Ship the two together, or neither.',
|
|
237
|
+
'',
|
|
238
|
+
'Tracked in `backlog/bug-bash-guards-judge-the-shell-cwd-not-the-paths-the-command-touches.md` and',
|
|
239
|
+
'`backlog/bug-outside-tree-kind-is-never-consumed-so-a-non-git-dir-is-judged-against-the-governed-repo.md`.',
|
|
240
|
+
'That resolver has three consumers — L1\'s K, L2\'s scope dimension, and `excludePaths` on the Bash path',
|
|
241
|
+
'— which is why the backlog says **fix once**.',
|
|
242
|
+
'',
|
|
243
|
+
'---',
|
|
244
|
+
'',
|
|
245
|
+
'',
|
|
246
|
+
'## Code anchors',
|
|
247
|
+
'',
|
|
248
|
+
'| section | file | symbol |',
|
|
249
|
+
'|---|---|---|',
|
|
250
|
+
'| resolver, K | `ai-hook-rules/src/core/effective-tree.ts` | `EffectiveTreeResolver`, `TreeKind` |',
|
|
251
|
+
'| the two structural blocks, in order | `ai-hook-rules/src/core/runner.ts` | `l1LocationBlock` |',
|
|
252
|
+
'| coordinator-in-worktree (row 3), A, R | `ai-hook-rules/src/core/coordinator-worktree.ts` | `CoordinatorWorktreeGuard`, `AgentIdentity` |',
|
|
253
|
+
'| force-to-root (row 5) | `ai-hook-rules/src/core/runner.ts` | `gitFromSubdirBlock` |',
|
|
254
|
+
'| the filter | `ai-hook-rules/src/core/runner.ts` | `filterByExcludedPaths` |',
|
|
255
|
+
'| `excludePaths` shape | `rules-config/src/exclude-hook-paths.ts`, `validate-config.ts`, `retired-config-keys.ts` | `ExcludePaths`, `validateExcludePaths` |',
|
|
256
|
+
'',
|
|
257
|
+
];
|
|
258
|
+
}
|
|
259
|
+
//# sourceMappingURL=l1-doc.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"l1-doc.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/core/l1-doc.ts"],"names":[],"mappings":";;AA0CA,kCAOC;AAjDD,uCAAqE;AAErE,8EAA8E;AAC9E,gDAAgD;AAChD,EAAE;AACF,sGAAsG;AACtG,uGAAuG;AACvG,2FAA2F;AAC3F,EAAE;AACF,mGAAmG;AACnG,uGAAuG;AACvG,uGAAuG;AACvG,oDAAoD;AACpD,8EAA8E;AAE9E,gFAAgF;AAChF,kHAAkH;AAClH,SAAS,IAAI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GAAmG;QACnG,uGAAuG;QACvG,wGAAwG;QACxG,EAAE;QACF,mGAAmG;QACnG,4GAA4G;QAC5G,yGAAyG;QACzG,+CAA+C;QAC/C,EAAE;QACF,KAAK;QACL,EAAE;QACF,EAAE;QACF,iBAAiB;QACjB,EAAE;QACF,6BAA6B;QAC7B,eAAe;QACf,oGAAoG;QACpG,kGAAkG;QAClG,4IAA4I;QAC5I,uFAAuF;QACvF,+EAA+E;QAC/E,8JAA8J;QAC9J,EAAE;KACL,CAAC;AACN,CAAC","sourcesContent":["import { L1Row, L1UseCase, L1_ROWS, allL1UseCases } from './l1-rows';\n\n// ---------------------------------------------------------------------------\n// guards/L1-location.md, rendered from L1_ROWS.\n//\n// Same arrangement as l0-matrix.renderGuardMatrixDoc(): one join('\\n') of literal markdown lines with\n// the ROW DATA interpolated from the array the guard consults. Everything that is not row data — every\n// prose section — is a literal line here, because that is the half a generator cannot own.\n//\n// A unit test (l1-matrix.spec.ts) locks guards/L1-location.md byte-identical to renderL1Doc(), and\n// `pnpm guards:generate` rewrites the file. So the table in the doc IS the array, not a description of\n// it. This module, like l1-rows.ts, has no runtime imports outside this pair so the generator can load\n// it without the package's transitive dependencies.\n// ---------------------------------------------------------------------------\n\n/** A dimension cell: the wildcard renders bare, every value renders as code. */\n// webpieces-disable no-function-outside-class -- pure cell formatter for renderL1Doc below, in this render module\nfunction cell(value: string): string {\n return value === '-' ? '-' : `\\`${value}\\``;\n}\n\n// webpieces-disable no-function-outside-class -- pure row formatter for renderL1Doc below, in this render module\nfunction tableRow(row: L1Row): string {\n const dims = [row.k, row.a, row.r, row.g, row.p].map(cell).join(' | ');\n // Row 6 has no `why` — an EMPTY cell is `| |`, not `| |`. Two spaces would render the same in a\n // browser and fail the byte-lock, which is the whole point of locking bytes rather than markdown.\n const why = row.why === '' ? ' ' : ` ${row.why} `;\n return `| ${row.num} | ${dims} | ${row.action.label} |${why}|`;\n}\n\n// webpieces-disable no-function-outside-class -- pure row formatter for renderL1Doc below, in this render module\nfunction useCaseRow(useCase: L1UseCase): string {\n return `| ${useCase.num} | ${useCase.symptom} | ${useCase.state} | ${useCase.verdict} | ${useCase.fix} |`;\n}\n\n/**\n * Render guards/L1-location.md.\n *\n * Split into three consecutive halves purely to stay inside the method-line budget — the join order is\n * what makes them one file, so keep them adjacent and keep the byte-lock test as the arbiter.\n */\n// webpieces-disable no-function-outside-class -- pure string builder over L1_ROWS, beside the array it reads\nexport function renderL1Doc(): string {\n return [\n ...renderHead(),\n ...renderTable(),\n ...renderUseCases(),\n ...renderTail(),\n ].join('\\n');\n}\n\n// Why L-1's guarantee-root and L1's force-to-root are NOT the same rule. Its own function because\n// renderHead is at the 80-line method cap, and because this section is one self-contained argument.\n// webpieces-disable no-function-outside-class -- prose section of renderL1Doc's string, beside it in this module\nfunction renderTwoLayerForceToRoot(): string[] {\n return [\n '## Force-to-root is TWO rules, in two layers — do not collapse them',\n '',\n 'Collapsing them is how the `shellAtRoot` bug happened the first time, and the two now live in different',\n 'layers, so it is worth stating plainly:',\n '',\n '| | judged by | what it judges | for | verdict |',\n '|---|---|---|---|---|',\n '| **L-1** | `.claude/webpieces/guarantee-root.sh` (POSIX sh, before any binary) | the `cd` **destination** of the command | **Bash** | ALLOW unless the destination is inside `$CLAUDE_PROJECT_DIR` and holds no `.git` — i.e. **sticky AND unguarded** |',\n '| **L1** | `gitFromSubdirBlock` (`runner.ts`) | the post-`cd` `effectiveCwd` | **git / gh only** | BLOCK unless it is THE root |',\n '',\n 'They ask different questions. L-1 asks *\"can the relative guard hooks launch there?\"* — because the',\n 'guard hooks are registered relative, and a hook that cannot resolve exits 127, which the harness treats',\n 'as a non-blocking error and lets the call proceed UNGUARDED. It therefore ALLOWS a `cd` into a foreign',\n 'nested clone (its own `.git`) and a `cd` outside the project (the harness resets the cwd next call),',\n 'neither of which L1 would tolerate for a `git` command. L1 asks *\"is this git command being run from the',\n 'one root it is meant to run from?\"*, which is a narrower question about a narrower set of commands.',\n '',\n 'A denied `cd` never executes — PreToolUse denies the whole tool call before the shell moves — so there',\n 'is no bad state to recover from and L-1 needs no cure command on any allowlist.',\n '',\n ];\n}\n\n// The three questions L1 answers, the preamble and the filter — all prose, none of it row data.\n// webpieces-disable no-function-outside-class -- first section of renderL1Doc's string, beside it in this module\nfunction renderHead(): string[] {\n return [\n '# L1 — location',\n '',\n '**Goal: is this call ours to judge, is the right AGENT making it, and is git being run from the root?**',\n '',\n '**Config key: `location-guard` (proposed).** Force-to-root and coordinator-in-worktree both have **no',\n 'config key today** and cannot be disabled; `excludePaths` is a top-level block, not a `hookGuards`',\n 'entry.',\n '',\n '',\n '**Code:** `packages/tooling/ai-hook-rules/src/core/effective-tree.ts` (`EffectiveTreeResolver`,',\n '`TreeKind`) · `packages/tooling/ai-hook-rules/src/core/runner.ts` (`l1LocationBlock`,',\n '`gitFromSubdirBlock`, `filterByExcludedPaths`, the `foreign` check) ·',\n '`packages/tooling/ai-hook-rules/src/core/coordinator-worktree.ts` (`CoordinatorWorktreeGuard`,',\n '`AgentIdentity`).',\n '',\n 'L1 answers three questions, and they are genuinely separate:',\n '',\n '1. **Do we govern this at all?** — the escape hatches, for other repos and non-governed paths.',\n '2. **Is the WRONG AGENT standing here?** — the coordinator must not work inside a linked worktree.',\n ' Its governance is anchored to `$CLAUDE_PROJECT_DIR`, fixed at session start, which does NOT follow',\n ' a `cd`; a coordinator in a worktree therefore has its filesystem in one tree and its guards in',\n ' another, and every fault it is shown is measured against a tree it is not standing in. Work in a',\n ' worktree belongs to a **subagent bound to it**, which has both in one place.',\n '3. **Is the agent stranded away from the root?** — force-to-root, git/gh only. Agents forget where',\n ' they are constantly, and `cd` gives them two different ways to be wrong: a `cd` that stays INSIDE',\n ' the workspace PERSISTS to later calls (so the shell can be parked in a subdirectory left by an',\n ' unrelated command turns earlier), while a `cd` that LEAVES it is reset by the harness, which says',\n ' so — `Shell cwd was reset to <root>`. Neither can be assumed, which is why every remedy names the',\n ' root explicitly instead of telling the agent to `cd` first.',\n '',\n ...renderTwoLayerForceToRoot(),\n '## Preamble — resolve the target first (Bash only)',\n '',\n '`EffectiveTreeResolver.resolve()` computes `effectiveCwd`: the directory the command actually runs in,',\n 'which is the shell\\'s cwd unless the command leads with `cd <dir> &&`. **K is classified from',\n '`effectiveCwd`, not from the shell\\'s cwd** — so \"a foreign repo that `cd`s into ours\" is not a cell,',\n 'it is simply `pw` after resolution.',\n '',\n 'Only a LEADING run of `cd`/`pushd` counts. A *trailing* `… && cd <exempt-tree>` must never',\n 'retroactively pull a command out of scope — that would smuggle a root-level `git push` past the',\n 'guards. Quoting is handled by `ShellSegmentScan`, so `echo \"cd sub && git push\"` is one opaque',\n 'segment and its quoted `cd` is never picked up.',\n '',\n '## Filter — not a dimension (all tools)',\n '',\n '`filterByExcludedPaths` drops every rule excluded for this path: the **target path** for',\n 'Read/Write/Edit, `effectiveCwd` for Bash. An empty rule list means allow. This is a filter, not a row:',\n '\"exempt\" is what emerges when the list empties.',\n '',\n '`excludePaths` is **ONE glob list** (canonical: `\"excludePaths\": [\"repositories/**\"]`). The',\n '`{ rules: [...], guards: [...] }` object is **retired and rejected**, with the union it must become',\n 'named in the error. `wp-install-ai-hooks` migrates it in place.',\n '',\n 'This used to be a tolerated fallback, justified here by \"rejecting it would block every Bash/Edit',\n 'including the edit that would fix it.\" **That was never true**, and the fallback it licensed is why',\n 'consumer configs — this repo\\'s own included — sat on the dead shape for releases. A Write/Edit whose',\n 'target is `webpieces.config.json` is an unconditional **PASS** (see the L0 table above), and',\n '`pnpm install` has an installer bypass, so an invalid config can always be repaired from inside the',\n 'block. Config rejection is self-recoverable by construction; see `retired-config-keys.ts` for the',\n 'policy and the reasoning.',\n '',\n ];\n}\n\n// The legend, the table itself (ROW DATA), and the note on the two structural blocks.\n// webpieces-disable no-function-outside-class -- second section of renderL1Doc's string, beside it in this module\nfunction renderTable(): string[] {\n return [\n '## Legend',\n '',\n '| col | dimension | values |',\n '|---|---|---|',\n '| **K** | tree kind of the resolved target | `f` foreign repo · `o` outside any repo · `w` a LINKED worktree of ours · `pw` ours (primary **or** worktree) |',\n '| **A** | who is calling | `c` the coordinator · `s` a subagent (or a caller that cannot tell) |',\n '| **R** | command is provably read-only inspection | `n` · `y` |',\n '| **G** | command invokes git/gh | `n` · `y` |',\n '| **P** | position of the resolved target | `root` · `sub` |',\n '',\n 'All of them are **Bash only**. Read/Write/Edit resolve their own target (`input.filePath`) and have no',\n 'dimensions — the filter is all that applies to them. **The Read tool is never blocked by L1.**',\n '',\n 'A linked worktree is deliberately **not** foreign: it is the same project, so the guards run against',\n 'THAT tree\\'s branch and cache. Every rule-scoped guard treats `p` and `w` alike, hence `pw`; row 3 below',\n 'is the ONE place they separate, and it turns on **A**, not on the tree.',\n '',\n '`A` comes from `agent_id`/`agent_type` in the PreToolUse payload, which Claude Code sends **only inside',\n 'a subagent**. Absent = the coordinator. A caller that cannot read the payload (the openclaw adapter,',\n 'library consumers) resolves to `s` — fail open, never guess someone into a block.',\n '',\n '`R` is `ReadOnlyInspectionScan` — the same paranoid \"provably inert\" test the unloadable-config escape',\n 'hatch uses (allowlisted viewers/searchers only, no redirects, no `sed -i`).',\n '',\n '## Table',\n '',\n '| # | K | A | R | G | P | act | why |',\n '|---|---|---|---|---|---|---|---|',\n ...L1_ROWS.map(tableRow),\n '',\n 'Rows 3 and 5 are the two structural blocks, and they run as ONE step (`l1LocationBlock` in `runner.ts`)',\n 'so they can never be reordered by accident — row 3 first, then force-to-root. Both sit after the L0',\n 'allowlist, after the `f` check, and after the `excludePaths` filter and the config-sync check. So a',\n 'cure (`cd <worktree> && pnpm install`) still reaches any tree: that is L0\\'s invariant, and row 3 does',\n 'not weaken it.',\n '',\n ];\n}\n\n// The use-case table (ROW DATA, in the doc's own numbering) and the two notes that follow it.\n// webpieces-disable no-function-outside-class -- third section of renderL1Doc's string, beside it in this module\nfunction renderUseCases(): string[] {\n return [\n '## L1 use cases',\n '',\n 'Same row shape as L0: the **Fix** is literal or it is not a fix. `<root>` is the absolute workspace',\n 'root — the messages name it explicitly rather than telling you to `cd` first, for the reason in the',\n 'section head (neither the shell\\'s cwd nor a `cd`\\'s persistence can be assumed).',\n '',\n '| # | what you SEE (exact symptom) | state | verdict | Fix |',\n '|---|---|---|---|---|',\n ...allL1UseCases().map(useCaseRow),\n '',\n 'Row 8 is the one that changed. It used to be ALLOWED, because the predicate was',\n '`shellAtRoot || cdsToRoot` — two variables OR\\'d, so the same destination got opposite verdicts',\n 'depending on where the shell happened to start. It is now one variable, `effectiveCwd === root`.',\n '',\n 'Row 12 is the incident that produced table row 3. The coordinator ran `git worktree add`, `cd`\\'d in,',\n 'and worked there. An L0 version-drift fault then fired against the PRIMARY (pin `0.4.545` vs',\n '`node_modules` `0.4.526`) and prescribed `pnpm install` — which ran in the WORKTREE, internally',\n 'consistent at `0.4.526`/`0.4.526`, so it succeeded, changed nothing in the measured tree, and the guard',\n 're-denied. Five identical installs later the agent had invented a theory about the harness stripping',\n 'its `cd` and handed the problem to the human. Note what row 15 says: the fix is NOT to deny that',\n 'install. It is to make the split state unreachable, so the wrong-tree install is never plausible.',\n '',\n ];\n}\n\n// The known gap and the code anchors — prose, and the one section that must never be summarised away:\n// three code comments point at it.\n// webpieces-disable no-function-outside-class -- last section of renderL1Doc's string, beside it in this module\nfunction renderTail(): string[] {\n return [\n '## Not done — `o` is not exempt yet',\n '',\n 'Row 2 hands `\\'outside\\'` down to L2 rather than exempting it. `\\'outside\\'` is produced at',\n '`effective-tree.ts` (`gitRoot === null`) carrying `governedRoot`, and **no code branches on it**, so a',\n 'command in no git repo is judged against the governed repo\\'s branch and staleness state. That is a',\n 'wrong verdict, and `exempt` is the right action.',\n '',\n '**It must not ship alone.** Jurisdiction comes from the shell cwd, not from what the command touches,',\n 'so exempting `o` opens a bypass an agent reaches by typing `cd /tmp &&`:',\n '',\n '| command | today | with `o → exempt` alone |',\n '|---|---|---|',\n '| `cd /tmp && ls` | judged against the repo | exempt — **correct** |',\n '| `cd /tmp && git -C $REPO commit` | L2 guards fire | exempt — **every L2 guard bypassed** |',\n '| `cd /tmp && rm -rf $REPO/packages/http/src` | judged | exempt — **unguarded** |',\n '',\n 'The two cases only separate once jurisdiction is judged on **what the command touches** (explicit',\n '`git -C` / `--work-tree`, then path arguments, then the `cd`, then the shell cwd), with the fail-safe',\n 'rule that **any** resolved target inside `governedRoot` means `pw`. Ship the two together, or neither.',\n '',\n 'Tracked in `backlog/bug-bash-guards-judge-the-shell-cwd-not-the-paths-the-command-touches.md` and',\n '`backlog/bug-outside-tree-kind-is-never-consumed-so-a-non-git-dir-is-judged-against-the-governed-repo.md`.',\n 'That resolver has three consumers — L1\\'s K, L2\\'s scope dimension, and `excludePaths` on the Bash path',\n '— which is why the backlog says **fix once**.',\n '',\n '---',\n '',\n '',\n '## Code anchors',\n '',\n '| section | file | symbol |',\n '|---|---|---|',\n '| resolver, K | `ai-hook-rules/src/core/effective-tree.ts` | `EffectiveTreeResolver`, `TreeKind` |',\n '| the two structural blocks, in order | `ai-hook-rules/src/core/runner.ts` | `l1LocationBlock` |',\n '| coordinator-in-worktree (row 3), A, R | `ai-hook-rules/src/core/coordinator-worktree.ts` | `CoordinatorWorktreeGuard`, `AgentIdentity` |',\n '| force-to-root (row 5) | `ai-hook-rules/src/core/runner.ts` | `gitFromSubdirBlock` |',\n '| the filter | `ai-hook-rules/src/core/runner.ts` | `filterByExcludedPaths` |',\n '| `excludePaths` shape | `rules-config/src/exclude-hook-paths.ts`, `validate-config.ts`, `retired-config-keys.ts` | `ExcludePaths`, `validateExcludePaths` |',\n '',\n ];\n}\n"]}
|