@webpieces/ai-hook-rules 0.4.676 → 0.4.677
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/bin/l0-allowlist.d.ts +22 -0
- package/src/bin/l0-allowlist.js +58 -1
- package/src/bin/l0-allowlist.js.map +1 -1
- package/src/bin/shim-audit-log.js +1 -0
- package/src/bin/shim-audit-log.js.map +1 -1
- package/src/bin/shim-drift-fix.d.ts +1 -1
- package/src/bin/shim-drift-fix.js +33 -28
- package/src/bin/shim-drift-fix.js.map +1 -1
- package/src/bin/shim-version-drift.d.ts +1 -0
- package/src/bin/shim-version-drift.js +164 -0
- package/src/bin/shim-version-drift.js.map +1 -0
- package/src/bin/shim.js +19 -97
- package/src/bin/shim.js.map +1 -1
- package/src/core/l1-rows.js +2 -2
- package/src/core/l1-rows.js.map +1 -1
- package/src/core/runner.js +7 -7
- package/src/core/runner.js.map +1 -1
- package/src/core/version-sync.d.ts +79 -0
- package/src/core/version-sync.js +236 -29
- package/src/core/version-sync.js.map +1 -1
- package/templates/ai-hook.sh +90 -18
package/src/bin/shim.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shim.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/bin/shim.ts"],"names":[],"mappings":";;;AAgDA,4BAEC;AAqaD,gCAgDC;AAYD,oCAWC;AAcD,4BAcC;AAmDD,8CAiBC;AAWD,gDAUC;AAOD,8CAGC;AAWD,8DAUC;;AAlrBD,+CAAyB;AACzB,mDAA6B;AAE7B,0DAAqE;AAErE,2DAGgC;AAChC,+CAA2C;AAC3C,iDAIwB;AACxB,qDAA6C;AAC7C,qDAAwD;AAGxD,wGAAwG;AACxG,mGAAmG;AACnG,yDAA+B;AAC/B,4FAA4F;AAC5F,2DAAiC;AAEjC,8EAA8E;AAC9E,qGAAqG;AACrG,oGAAoG;AACpG,mGAAmG;AACnG,mGAAmG;AAC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\n\nimport {\n L0_FAULT_BIN_BROKEN, L0_FAULT_BIN_MISSING, L0_FAULT_DRIFT, L0_FAULT_UNDECLARED,\n l0GuardHeader, l0MatrixCitation,\n} from '../core/l0-fault-codes';\nimport { toError } from '../core/to-error';\nimport {\n L0_ALLOW_ERE_SH, RECOVERY_CMD, INSTALL_HOOKS_CMD, UPGRADE_SHIM_CMD, RESTORE_SHIM_CMD,\n INSTALL_HOOKS_ALLOW_JS, UPGRADE_SHIM_ALLOW_JS, RESTORE_SHIM_ALLOW_JS,\n ADD_HOOK_PKG_CMD, HOOK_PKG,\n} from './l0-allowlist';\nimport { WP_LOG_SH } from './shim-audit-log';\nimport { DRIFT_INVERSE_FIX_SH } from './shim-drift-fix';\nimport { BASH_CWD_ENV_KEY, BASH_CWD_ENV_VALUE } from './managed-env';\n\n// The allowlist moved to ./l0-allowlist (this module was over the file-size limit); re-exported here so\n// every existing `from './shim'` import keeps working and there is still ONE name to import L0 by.\nexport * from './l0-allowlist';\n// Same treatment for the audit-log fragment: one name to import the whole rendered shim by.\nexport * from './shim-audit-log';\n\n// ---------------------------------------------------------------------------\n// The single checked-in shim (.claude/webpieces/ai-hook.sh). Both project hooks point at it, passing\n// their bin name as the first arg. settings.json points here (not at the bare bin) so a missing bin\n// (fresh clone, package removed) yields a friendly message instead of the raw `sh: No such file or\n// directory` on every Write/Edit/Bash tool call. `.claude` is committed, so the shim survives even\n// when node_modules does not.\n//\n// This module is the SINGLE SOURCE OF TRUTH for the shim body + the installer allowlist. The\n// installer (setup.ts) renders it on install; the running guards binary re-renders and self-heals it\n// (healShim) so the committed .sh can never go stale — no human ever hand-edits it.\n// ---------------------------------------------------------------------------\nexport const SHIM_MARKER = '.claude/webpieces/ai-hook.sh';\n\n// NO VERSION STAMP (removed 2026-07-24). The shim used to carry a per-release `# webpieces shim\n// version: <v> (<sha>)` on line 2, rewritten by scripts/set-version.sh at publish. It was a pure\n// human-eyeball diagnostic — nothing reads it (the deny's version note comes from the installed\n// package.json) — but it made the committed shim go byte-different on EVERY release even when the\n// logic was identical, so the committed-shim self-guard tripped on every upgrade over a comment (the\n// DENY-SHIM-STALE churn). It also carried its own hazard: stamp one of the two lockstep artifacts and\n// not the other and every consumer fail-closes forever on a phantom edit. Deleting it makes the shim\n// byte-STABLE across releases, so the self-guard (now in the binary) fires only on a genuine logic\n// change or a real tamper — which is what lets `pnpm install` be the fix for almost everything.\n\nexport function shimPath(projectRoot: string): string {\n return path.join(projectRoot, '.claude', 'webpieces', 'ai-hook.sh');\n}\n\n\n// ---------------------------------------------------------------------------\n// HOW EVERY DENY MUST SPELL ITS CURE (added 2026-07-23, from a live audit-log post-mortem).\n//\n// The guards were right, the message was right, and the assistant STILL handed the block back to the\n// human — because of one appended clause. From .webpieces/logs/L0-shim/<writer>.log in a consumer repo:\n//\n// DENY-SHIM-STALE cp node_modules/@webpieces/ai-hook-rules/templates/ai-hook.sh .claude/webpieces/ai-hook.sh && git status --short\n//\n// That is the prescribed cure, verbatim, plus `&& git status --short`. Every allowlist here is anchored\n// to `$`, so the trailing `&&` made it a different command and it was denied — and the assistant read\n// its own denial as proof that \"the guard blocks the very command that fixes it\" and stopped.\n//\n// Widening the allowlist to accept `&& <anything>` is NOT the fix: these are fail-CLOSED escape hatches\n// whose entire security property is that no shell operator can ride along (`cp … && rm -rf /`). The fix\n// is to stop the assistant appending in the first place — so every deny that prescribes a command now\n// (a) numbers its cures as OPTIONs, (b) quotes each one so the exact bytes are unambiguous, and\n// (c) carries this rule, which says in plain words that adding `&&` gets it rejected again.\n//\n// CONSTRAINT on every string that reaches a deny REASON: no double quotes and no backslashes. The\n// reason is interpolated into a `REASON=\"…\"` shell assignment and then printf'd into a JSON string, so\n// a `\"` would break BOTH. Hence single quotes around the commands here — do not \"improve\" them.\n// ---------------------------------------------------------------------------\n// LENGTH IS PART OF THE FIX (2026-08-03). This block used to run ~153 words and was repeated verbatim\n// in D, X and K — in X it was ~85% of the whole message, which buries the one sentence that matters.\n// It now states the rule and the three tolerated additions, and nothing else: the tolerated set is\n// exactly what CD_PREFIX_ERE + CAPTURE_TAIL_ERE accept (the single-quoted path branch of CD_PREFIX_ERE\n// is why \"single-quote a path containing spaces\" is named), so this text cannot promise more or less\n// than the allowlist grants.\nexport const NO_CHAINING_RULE =\n 'Run it EXACTLY as written - the allowlist matches the whole command, so appending anything ' +\n '(even && git status) makes it a different command and it is rejected; that is not the guard ' +\n 'blocking its own cure. Only these may be added: a leading cd <dir> && (single-quote a path ' +\n 'containing spaces), a trailing 2>&1, and | tail -N.';\n\n// Shell fragment: resolve the guard BIN by WALKING UP from ROOT, and remember WHERE it came from.\n//\n// THE BUG THIS CLOSES (it would have landed the day the hooks went relative). `ai-hook.sh` used to set\n// `BIN=\"$ROOT/node_modules/.bin/$BIN_NAME\"` — a LITERAL path with no upward walk, while Node's own\n// resolver walks up. That was correct only while the hooks were registered ABSOLUTE, because then ROOT\n// was always the primary clone and the bin was always there. The moment H2/H3 became relative, ROOT\n// became the tree the call is in — and a nested worktree at `<primary>/.claude/worktrees/<name>` has NO\n// node_modules of its own. Every subagent would have hard-blocked on fault X at its first tool call,\n// fleet-wide, on the day of the flip. Walking up finds the primary's install, exactly as a `require()`\n// from the same directory would; a SIBLING worktree finds nothing and correctly still faults X.\n//\n// BIN_ROOT is not a curiosity: walking up ALONE re-creates the version straddle documented above\n// committedShimStale(), where the shim of one tree is paired with the binary of another and the cure\n// can never converge. So the walk is paired with a check — DECLARED comes from `$ROOT/package.json`\n// (the tree being judged) and INSTALLED comes from `$BIN_ROOT/node_modules` (the binary actually\n// running). Equal → no fault, keep reusing the inherited bin, which is the common case and stays free.\n// Different → fault D, cured by an install in THIS tree, which materialises its own node_modules.\nconst RESOLVE_BIN_SH = `BIN_ROOT=\"\\$ROOT\"\nBIN=\"\\$ROOT/node_modules/.bin/\\$BIN_NAME\"\nWP_WALK=\"\\$ROOT\"\nwhile [ ! -x \"\\$WP_WALK/node_modules/.bin/\\$BIN_NAME\" ]; do\n WP_UP=\"\\$(dirname -- \"\\$WP_WALK\")\"\n [ \"\\$WP_UP\" != \"\\$WP_WALK\" ] || break\n WP_WALK=\"\\$WP_UP\"\ndone\nif [ -x \"\\$WP_WALK/node_modules/.bin/\\$BIN_NAME\" ]; then\n BIN_ROOT=\"\\$WP_WALK\"\n BIN=\"\\$WP_WALK/node_modules/.bin/\\$BIN_NAME\"\nfi`;\n\n// Normal template literal (not String.raw): it carries #235's shell escapes verbatim (\\${BIN_NAME},\n// \\$REASON, \\\\n for the deny JSON) AND my sed backslashes (doubled: \\\\(, \\\\), \\\\1, [^\"\\\\\\\\]). The\n// grep pattern is interpolated from INSTALLER_ALLOW_ERE (its value has no backslashes).\n// Shell fragment: the two JSON escapes the deny text is built from, plus the one shared \"what is still\n// allowed\" block. Hoisted to the TOP of the shim (it used to sit inside DENY_EMIT_SH's Bash branch,\n// i.e. AFTER every REASON was already assembled) because the deny text now needs the newline escape\n// while it is being BUILT, not only while it is being printed.\n//\n// THE MECHANISM IS THE ONE THE COLOUR ALREADY USED. `REASON` is interpolated into a `REASON=\"…\"` shell\n// assignment and then printf'd into a JSON string literal, so it may contain no RAW double-quote and no\n// RAW backslash — and a RAW newline would be invalid JSON. That constraint is not \"no newlines\": it is\n// \"no raw backslash\", and `${BS}` produces the backslash at RUNTIME, so `${ESC}` (six chars: \\ u 0 0 1 b)\n// and `${NL}` (two chars: \\ n) both travel as legal JSON escapes that Claude Code's parser turns back\n// into a real ESC and a real newline. Verified end to end through /bin/sh in setup.spec.ts: the payload\n// still parses as JSON, the systemMessage still carries 31;1m, and the reason renders as many lines.\n//\n// WHY THE STRUCTURE MATTERS: every L1/L2 deny is rendered by formatReport() into a scannable shape —\n// header, `[guard-name] (N violations)`, indented offenders each with a one-line `→ why`, then numbered\n// `Fix Option N:` lines. L0 was the ONLY layer answering in one unbroken paragraph. It now uses the same\n// skeleton, which is what WP_STILL_ALLOWED exists for: one definition of that section for all four\n// sh-side faults, so they cannot drift into four different answers to the same question.\nconst ESCAPES_SH = `BS='\\\\' # one literal backslash, so no \\\\u001b / \\\\n escape sits in this source\nESC=\"\\${BS}u001b\" # the 6 chars: backslash u 0 0 1 b — Claude Code parses \\\\u001b → ESC\nNL=\"\\${BS}n\" # the 2 chars: backslash n — parsed as a real newline inside the JSON string\nWP_STILL_ALLOWED=\"Still allowed while this block is up:\\${NL} - any Read\\${NL} - any Write/Edit whose target is ${CONFIG_FILENAME}\\${NL} - every command on the L0 allowlist, including the Fix Options below\\${NL} THIS IS NOT A DEADLOCK - run one YOURSELF now; do not hand it back to the human.\"`;\n\n// Shell fragment: the version-drift guard (see its own block comment). Extracted to a module const so\n// renderShim() stays within the method-line budget; it is spliced back in verbatim, byte-for-byte.\nconst VERSION_DRIFT_GUARD_SH = `# --- webpieces version-drift guard (pure sh — runs even when the installed guard bin is stale) -----\n# The committed shim is version-agnostic, so it keeps working right after a git pull, BEFORE the\n# matching pnpm install. That is exactly when node_modules can be STALE: an OLDER @webpieces than\n# package.json now pins, whose outdated validator rejects the NEWER webpieces.config.json with baffling\n# \"unknown rule\" errors. Detect that drift HERE (before exec'ing the possibly-stale bin): compare every\n# EXACT-pinned @webpieces/* version in the root package.json against the version actually installed in\n# node_modules; the first mismatch wins. Range specs (^ ~ workspace:*) are skipped, so they never\n# false-positive; best-effort — a version we cannot read is skipped. On drift we fall through to the\n# SAME fail-closed path as a missing bin (allow only pnpm install, deny the rest).\n#\n# pnpm CATALOGS: a dep pinned via \"catalog:\" / \"catalog:<name>\" carries NO digit-version in package.json,\n# so the old scraper matched nothing and the guard was BLIND to it — DRIFT_PKG stayed empty and the\n# stale bin ran (the 2026-07 \"0.3.369 vs 0.4.405\" incident). Resolve those specs through the top-level\n# \\`catalogs:\\` block of pnpm-lock.yaml (catalog -> pkg -> resolved version) before comparing.\n#\n# THE SAME PASS ANSWERS FAULT U (2026-08-05). Scraping root package.json is also the only way to learn\n# whether @webpieces/ai-hook-rules is DECLARED at all, and that is the difference between \"not installed\n# yet\" (X, cured by pnpm install) and \"nothing asks for it\" (U, where pnpm install is a guaranteed\n# no-op). WP_PIN carries the first EXACT @webpieces pin found, so U's deny can prescribe the version the\n# rest of the repo is already on rather than an unpinned add. Both are set BEFORE the range/catalog\n# \\`continue\\`s, so a repo pinning the package by range still counts as having declared it.\nDRIFT_PKG=\"\"\nDRIFT_DECLARED=\"\"\nDRIFT_INSTALLED=\"\"\nWP_HOOK_PKG_DECLARED=\"\"\nWP_PIN=\"\"\nif [ -f \"$ROOT/package.json\" ]; then\n # Only when a @webpieces dep actually uses a \"catalog:\" spec do we scan the (possibly huge) lockfile —\n # a cheap grep keeps the common, catalog-free repo from paying that cost on every tool call. One awk\n # pass over pnpm-lock.yaml emits \"<catalog> <@webpieces/pkg> <version>\" lines for the sh lookup below;\n # \\\\047 is a single quote (so this awk program carries none and stays safely single-quotable in sh).\n WP_CATALOGS=\"\"\n if grep -Eq '\"@webpieces/[^\"]*\"[[:space:]]*:[[:space:]]*\"catalog:' \"$ROOT/package.json\" 2>/dev/null && [ -f \"$ROOT/pnpm-lock.yaml\" ]; then\n WP_CATALOGS=\"$(awk '\n { n=0; while (substr($0,n+1,1)==\" \") n++; c=substr($0,n+1) }\n c==\"\" { next }\n n==0 { incat=(c ~ /^catalogs: *$/)?1:0; cat=\"\"; pkg=\"\"; next }\n incat==0 { next }\n n==2 { cat=c; sub(/:.*/,\"\",cat); pkg=\"\"; next }\n n==4 { pkg=c; sub(/: *$/,\"\",pkg); gsub(/[\"\\\\047]/,\"\",pkg); next }\n n==6 && substr(pkg,1,11)==\"@webpieces/\" && c ~ /^version:/ {\n v=c; sub(/^version: */,\"\",v); gsub(/[\"\\\\047 ]/,\"\",v);\n if (cat!=\"\" && v!=\"\") print cat \" \" pkg \" \" v\n }\n ' \"$ROOT/pnpm-lock.yaml\" 2>/dev/null)\"\n fi\n while IFS=' ' read -r WP_NAME WP_DECL; do\n [ -n \"$WP_NAME\" ] || continue\n # Fault U's input: the package is DECLARED (in any spec shape, in any dependency block of the root\n # manifest). Recorded before every \\`continue\\` below, so a range or catalog spec still counts.\n [ \"$WP_NAME\" = \"ai-hook-rules\" ] && WP_HOOK_PKG_DECLARED=1\n # Resolve the declared spec to an EXACT version, or skip it: ranges (^ ~ workspace:*) never drift,\n # and a catalog spec we cannot resolve is best-effort skipped rather than guessed.\n case \"$WP_DECL\" in\n catalog:*)\n WP_CAT=\"\\${WP_DECL#catalog:}\"; [ -n \"$WP_CAT\" ] || WP_CAT=\"default\"\n WP_DECL=\"$(printf '%s\\\\n' \"$WP_CATALOGS\" | awk -v c=\"$WP_CAT\" -v p=\"@webpieces/$WP_NAME\" '$1==c && $2==p {print $3; exit}')\"\n [ -n \"$WP_DECL\" ] || continue ;;\n [0-9]*) : ;;\n *) continue ;;\n esac\n # The release the rest of this repo is on — what fault U's cure should pin to.\n [ -n \"$WP_PIN\" ] || WP_PIN=\"$WP_DECL\"\n WP_MANIFEST=\"$BIN_ROOT/node_modules/@webpieces/$WP_NAME/package.json\"\n [ -f \"$WP_MANIFEST\" ] || continue\n WP_INST=\"$(sed -n 's/.*\"version\"[[:space:]]*:[[:space:]]*\"\\\\([^\"]*\\\\)\".*/\\\\1/p' \"$WP_MANIFEST\" | head -n1)\"\n [ -n \"$WP_INST\" ] || continue\n if [ \"$WP_DECL\" != \"$WP_INST\" ]; then\n DRIFT_PKG=\"@webpieces/$WP_NAME\"\n DRIFT_DECLARED=\"$WP_DECL\"\n DRIFT_INSTALLED=\"$WP_INST\"\n break\n fi\n done <<WPEOF\n$(sed -n 's/.*\"@webpieces\\\\/\\\\([A-Za-z0-9._-]*\\\\)\"[[:space:]]*:[[:space:]]*\"\\\\([^\"]*\\\\)\".*/\\\\1 \\\\2/p' \"$ROOT/package.json\")\nWPEOF\nfi\n# THE CURE FOR A BORROWED node_modules RUNS IN THIS TREE, NOT WHEREVER THE BIN CAME FROM. A bare\n# 'pnpm install' typed while the shell sits in the primary clone installs into the primary, changes\n# nothing in the worktree being judged, and re-fires the identical fault — the four-cure straddle\n# recorded above committedShimStale(). When the bin was inherited, prescribe the cd and say why.\nWP_INSTALL_CMD=\"pnpm install\"\nWP_BORROW_NOTE=\"\"\nif [ \"$BIN_ROOT\" != \"$ROOT\" ]; then\n WP_INSTALL_CMD=\"cd $ROOT && pnpm install\"\n WP_BORROW_NOTE=\"\\${NL} NOTE: this tree ($ROOT) has NO node_modules of its own, so the guard binary was inherited from $BIN_ROOT by walking up. TWO cures are real and they fix DIFFERENT things: A makes THIS tree work now, B stops the two trees disagreeing. A - run the command above HERE. That is legitimate and it does work; a worktree NEEDS its own node_modules anyway (nx, vitest and the eslint plugin all execute in this tree and load from it). B - get $BIN_ROOT onto the same @webpieces version: put both trees on the same git hash (the pin is tracked) and run ONE 'pnpm install' there. If you are a SUBAGENT, B is the half you cannot do: it needs both trees on the same git hash, and CROSS-TREE GIT is refused to you here (a local 'cd' + install does run - it is git -C another tree that is blocked). So ESCALATE B: TELL THE MAIN AGENT in the MAIN git worktree ($BIN_ROOT) to run 'git pull && pnpm install' there so both trees are on the same @webpieces version, and to tell you when it is complete so you can continue. If you escalate instead of doing A, that forwarding IS the end of your turn: STOP WORKING NOW, make NO further tool calls and do NOT retry - RETRYING IS THE BUG, because every retry re-fires this identical deny and buries the ask. WAIT for that confirmation, then resume. The rule is NOT no-install-here: it is that this tree's @webpieces must EQUAL $BIN_ROOT's, because doing only A leaves two trees on two releases (the trinary-version-skew guard then BLOCKS rather than letting it pass unnoticed). Adding an ordinary third-party dependency here changes none of that - only a differing @webpieces version does. If this tree genuinely needs a DIFFERENT version, use a separate clone rather than a worktree.\"\nfi`;\n\n// Shell fragment: run the installed guard bin and INSPECT its outcome, instead of exec'ing it.\n//\n// THE BUG THIS FIXES (guards silently fail-OPEN): the shim used to `exec \"$BIN\"`. exec REPLACES this\n// shim process, so once the bin was executable the shim was GONE and could no longer make a decision.\n// That is fine when the bin runs — but the bin can be INSTALLED YET BROKEN: a corrupt/partially-written\n// node_modules makes node die at require() time with MODULE_NOT_FOUND, exiting 1. And in the PreToolUse\n// protocol ONLY exit 2 blocks: any other non-zero is a NON-BLOCKING error, so Claude Code prints\n// \"Failed with non-blocking status code\" and RUNS THE TOOL CALL ANYWAY — the guard is silently skipped.\n// Result: every Write/Edit/Bash went UNGUARDED, for as long as node_modules stayed corrupt. The shim\n// handled \"bin missing\" and \"bin stale\", but never \"bin present and CRASHES\" — the third failure mode.\n//\n// So: do not exec. Run the bin with the payload on stdin and branch on its exit code.\n// rc 0 | 2 → a REAL decision (allow / block). Relay stdout, stderr and the code byte-faithfully.\n// anything else → the guard CRASHED. Fall through to the fail-CLOSED path (BROKEN_BIN=1).\n// stdout/stderr go through temp FILES, not $(command substitution), so the bin's bytes reach Claude\n// Code exactly as written — command substitution strips trailing newlines and would corrupt the\n// decision JSON. Reading the payload up-front ($PAYLOAD) is what replaces exec's stdin passthrough.\nconst RUN_BIN_SH = `if [ -x \"\\$BIN\" ] && [ -z \"\\$DRIFT_PKG\" ]; then\n OUT_FILE=\"\\${TMPDIR:-/tmp}/wp-ai-hook-out.\\$\\$\"\n ERR_FILE=\"\\${TMPDIR:-/tmp}/wp-ai-hook-err.\\$\\$\"\n printf '%s' \"\\$PAYLOAD\" | \"\\$BIN\" \"\\$@\" >\"\\$OUT_FILE\" 2>\"\\$ERR_FILE\"\n RC=\\$?\n if [ \"\\$RC\" = 0 ] || [ \"\\$RC\" = 2 ]; then\n cat \"\\$OUT_FILE\" # the guard's real decision — verbatim\n cat \"\\$ERR_FILE\" >&2\n rm -f \"\\$OUT_FILE\" \"\\$ERR_FILE\" 2>/dev/null\n # THE HEALTHY CALL, which this log used to be silent about (see WP_LOG_SH's header). No sh-side\n # fault, the bin ran, and its own exit code says how it ended — 0 allow, 2 block. Logged AFTER the\n # decision bytes are already on stdout, so the audit trail never sits between the guard and Claude\n # Code. Without this line, \"no entry\" meant either healthy or never-ran, and those are the two\n # answers a reader most needs to tell apart.\n WP_VERDICT=PASS-BIN-ALLOW\n [ \"\\$RC\" = 2 ] && WP_VERDICT=PASS-BIN-BLOCK\n wp_log - \"\\$WP_VERDICT\"\n exit \"\\$RC\"\n fi\n # Crashed. Keep the most useful stderr line for the human. Strip \" and backslash so the text stays a\n # valid JSON string, and cap the length so a giant node stack cannot blow up the deny payload.\n CRASH_MSG=\"\\$(grep -m1 'Cannot find module' \"\\$ERR_FILE\" 2>/dev/null | tr -d '\"\\\\\\\\' | cut -c1-120)\"\n [ -n \"\\$CRASH_MSG\" ] || CRASH_MSG=\"\\$(head -n1 \"\\$ERR_FILE\" 2>/dev/null | tr -d '\"\\\\\\\\' | cut -c1-120)\"\n [ -n \"\\$CRASH_MSG\" ] || CRASH_MSG=\"exit code \\$RC, no stderr\"\n rm -f \"\\$OUT_FILE\" \"\\$ERR_FILE\" 2>/dev/null\n BROKEN_BIN=1\nfi`;\n\n// Shell fragment: pull the four fields the shim itself reasons about out of the tool payload.\n//\n// MOVED AHEAD OF THE BIN (it used to sit inside TRIAGE_SH, i.e. only on the fail-closed path) because\n// the audit log now covers the HEALTHY call too, and a log line needs the tool and the command whether\n// or not anything went wrong.\n//\n// `cwd` is Claude Code's documented \"current working directory when the hook is invoked\". It is used\n// for ONE thing: deciding which tree's log directory this line belongs in (see RESOLVE_LOG_DIR_SH).\n// It deliberately does NOT change what the drift guard MEASURES — that stays anchored to $ROOT, the\n// tree the shim FILE lives in. Where a call is logged and what a call is judged against are separate\n// questions and are kept separate here.\n// TWO command variables, and the split is a SECURITY boundary — do not collapse them.\n//\n// $CMD is the DECISION input (the L0 allowlist greps it). Its pattern requires the CLOSING quote, so a\n// JSON payload that escapes an embedded quote as \\\\\" yields the EMPTY STRING for the whole command.\n// That looks like a bug and is in fact the safe direction: an empty command matches no allowlist entry,\n// so a quoted command falls through to the deny. FAIL CLOSED. Keep it that way.\n//\n// $CMD_LOG is the AUDIT input and must never reach a decision. It drops the closing quote from the\n// pattern so it captures the command PREFIX instead of nothing.\n//\n// WHY THEY CANNOT BE ONE VARIABLE: every L0 allowlist ERE is anchored `^…[[:space:]]*$`, and trailing\n// whitespace is tolerated — so `pnpm install \"; rm -rf /\"` would prefix-capture to `pnpm install `,\n// which MATCHES, and the injection after the quote would ride through allowlisted. Measured 2026-08-06:\n// 3,908 of 4,917 shim audit lines (79.5%) recorded an empty command, i.e. four out of five audit\n// entries were blind. Fixing the LOG is worth doing; fixing the DECISION the same way is a hole.\nconst PARSE_PAYLOAD_SH = `CMD=\"\\$(printf '%s' \"\\$PAYLOAD\" | sed -n 's/.*\"command\"[[:space:]]*:[[:space:]]*\"\\\\([^\"\\\\\\\\]*\\\\)\".*/\\\\1/p')\"\nCMD_LOG=\"\\$(printf '%s' \"\\$PAYLOAD\" | sed -n 's/.*\"command\"[[:space:]]*:[[:space:]]*\"\\\\([^\"\\\\\\\\]*\\\\).*/\\\\1/p')\"\n[ -n \"\\$CMD_LOG\" ] || CMD_LOG=\"\\$CMD\"\nTOOL=\"\\$(printf '%s' \"\\$PAYLOAD\" | sed -n 's/.*\"tool_name\"[[:space:]]*:[[:space:]]*\"\\\\([^\"\\\\\\\\]*\\\\)\".*/\\\\1/p')\"\nWP_SID=\"\\$(printf '%s' \"\\$PAYLOAD\" | sed -n 's/.*\"session_id\"[[:space:]]*:[[:space:]]*\"\\\\([^\"\\\\\\\\]*\\\\)\".*/\\\\1/p')\"\nWP_AID=\"\\$(printf '%s' \"\\$PAYLOAD\" | sed -n 's/.*\"agent_id\"[[:space:]]*:[[:space:]]*\"\\\\([^\"\\\\\\\\]*\\\\)\".*/\\\\1/p')\"\nFILE=\"\\$(printf '%s' \"\\$PAYLOAD\" | sed -n 's/.*\"file_path\"[[:space:]]*:[[:space:]]*\"\\\\([^\"\\\\\\\\]*\\\\)\".*/\\\\1/p')\"\nWP_CWD=\"\\$(printf '%s' \"\\$PAYLOAD\" | sed -n 's/.*\"cwd\"[[:space:]]*:[[:space:]]*\"\\\\([^\"\\\\\\\\]*\\\\)\".*/\\\\1/p')\"\n[ -n \"\\$WP_CWD\" ] || WP_CWD=\"\\$ROOT\" # no cwd in the payload (older client, or a hand-run) → the shim's own tree`;\n\n// Shell fragment: the guards are DOWN (missing | stale | crashed). Classify the fault, then let THE L0\n// ALLOWLIST through — everything else falls to the deny below.\n//\n// This asks the identical question isAllowed() asks in JS, in the same order: Read, then the\n// webpieces.config.json target, then the one command union (L0_ALLOW_ERE). The sh and JS halves exist\n// because D/X/K are decided BEFORE the bin runs (a stale/missing/broken validator cannot validate\n// itself) while S/C/Y are decided inside it — one model, two enforcement points.\n//\n// NOTE the documented asymmetry: here the bin is never executed, so an allowed Read is TERMINAL and\n// read-stale-guard does not run. In JS the same entry falls through and it does. See isAllowed().\nconst TRIAGE_SH = `# WHICH of the guards/L0-tooling.md faults fired, in the doc's own letters. Only the four sh-side\n# codes can be decided here; S/C/Y live in the binary, which never got to run on this path.\nWP_FAULT=${L0_FAULT_BIN_MISSING} # X — bin missing (fresh clone, new worktree)\n[ -z \"\\$WP_HOOK_PKG_DECLARED\" ] && WP_FAULT=${L0_FAULT_UNDECLARED} # U — X, but nothing declares the package: install is a no-op\n[ -n \"\\$DRIFT_PKG\" ] && WP_FAULT=${L0_FAULT_DRIFT} # D — version drift; D and K are mutually exclusive\n[ -n \"\\$BROKEN_BIN\" ] && WP_FAULT=${L0_FAULT_BIN_BROKEN} # K — bin present but CRASHED (corrupt node_modules)\nDENY_LABEL=\"DENY\"\n[ -z \"\\$WP_HOOK_PKG_DECLARED\" ] && DENY_LABEL=\"DENY-UNDECLARED\" # nothing in package.json asks for the package\n[ -n \"\\$DRIFT_PKG\" ] && DENY_LABEL=\"DENY-STALE\" # version drift, not a missing bin\n[ -n \"\\$BROKEN_BIN\" ] && DENY_LABEL=\"DENY-BROKEN\" # bin present but CRASHED (corrupt node_modules)\n# THE L0 ALLOWLIST, entry order identical to isAllowed(). No fault is consulted: a cure that cannot\n# help a given fault also cannot hurt it, and gating each entry on a fault is what produced the four\n# defects recorded above L0_ALLOW_ERE.\nif [ \"\\$TOOL\" = \"Read\" ]; then\n wp_log \"\\$WP_FAULT\" ALLOW-READ # you must be able to read to work out how to fix this\n exit 0\nfi\ncase \"\\$FILE\" in\n */${CONFIG_FILENAME}|${CONFIG_FILENAME})\n wp_log \"\\$WP_FAULT\" ALLOW-CONFIG # the always-allowed recovery target — every guard is configured from it\n exit 0 ;;\nesac\nif printf '%s' \"\\$CMD\" | grep -Eq '${L0_ALLOW_ERE_SH}'; then\n wp_log \"\\$WP_FAULT\" ALLOW-CURE # record the self-heal we let through (re-enables the guards)\n exit 0 # allow the cure so the assistant can break the deadlock\nfi\nwp_log \"\\$WP_FAULT\" \"\\$DENY_LABEL\" # every fail-closed block, with the fault that caused it`;\n\n// Shell fragment: emit the deny. FAIL CLOSED via Claude Code's PreToolUse JSON protocol\n// (permissionDecision \"deny\" on stdout, then exit 0) rather than a bare \"exit 2\". BOTH block the call,\n// but the reason must be made VISIBLE, and HOW depends on the tool (verified by live tests; the docs\n// are wrong here):\n// - Bash deny: permissionDecisionReason is NOT shown to the human — ONLY a top-level systemMessage\n// is, and it honors ANSI. So for Bash we emit systemMessage wrapped in ANSI red so the\n// recovery command is visible (without it, on Bash, it is invisible).\n// - Write/Edit/MultiEdit deny: permissionDecisionReason renders as a RED \"Error:\" block natively —\n// no systemMessage needed (a second line would be redundant).\n// - NEVER exit 2 (stdout JSON ignored; stderr not reliably shown on a blocked Bash call).\n// The ESC and the newline escape are both built in ESCAPES_SH at the TOP of the shim (see its header):\n// ${ESC} is the literal 6-char JSON escape \\\\u001b and ${NL} the 2-char \\\\n, so no raw ESC byte, no raw\n// newline and no \\\\uXXXX sits in this source, and Claude Code's JSON parser turns both back. The reason\n// is a single JSON string with no RAW double-quotes/backslashes, so it stays valid JSON after the subs.\n//\n// ONLY THE HEADLINE IS RED, and that is deliberate — the same call redSystemMessage() makes on the JS\n// side. The reason is MULTI-LINE now, and a whole page in bold red is harder to read than the paragraph\n// it replaced: the indentation carrying the structure stops registering when every line shouts. So\n// \\$WP_HEAD (each branch's own first line, kept in its own variable for exactly this) is wrapped in\n// [31;1m … [0m, and \\${REASON#\"\\$WP_HEAD\"} — POSIX prefix removal with a QUOTED pattern, so the\n// headline is matched literally and not as a glob — supplies the plain body after it.\nconst DENY_EMIT_SH = `if [ \"\\$TOOL\" = \"Bash\" ]; then\n printf '{\"systemMessage\":\"%s🛑 %s%s%s\",\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"permissionDecision\":\"deny\",\"permissionDecisionReason\":\"%s\"}}\\\\n' \"\\${ESC}[31;1m\" \"\\$WP_HEAD\" \"\\${ESC}[0m\" \"\\${REASON#\"\\$WP_HEAD\"}\" \"\\$REASON\"\nelse\n printf '{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"permissionDecision\":\"deny\",\"permissionDecisionReason\":\"%s\"}}\\\\n' \"\\$REASON\"\nfi\nexit 0 # decision is carried by permissionDecision \"deny\", not the exit code`;\n\n// Shell fragment: pick the fail-closed deny REASON — a crashed-bin message (corrupt node_modules) vs a\n// version-drift message (bin present but stale) vs the missing-bin message. Extracted alongside\n// VERSION_DRIFT_GUARD_SH / RUN_BIN_SH to keep renderShim() within the method-line budget.\nconst DENY_REASON_SH = `if [ -n \"\\$BROKEN_BIN\" ]; then\n # Report (do NOT auto-clean) the orphaned pnpm staging dirs — a package pnpm was mid-way through\n # writing is left behind as <name>_<pid>_<hash>. Their presence is the fingerprint of an install that\n # was killed, which is what corrupts node_modules in the first place. Best-effort; never fatal.\n STAGING_N=\"\\$(ls \"\\$BIN_ROOT/node_modules\" 2>/dev/null | grep -Ec '_[0-9a-f]+_[0-9a-f]+\\$' || true)\"\n STAGING_NOTE=\"\"\n if [ \"\\${STAGING_N:-0}\" -gt 0 ] 2>/dev/null; then\n STAGING_NOTE=\"\\${NL} → also found \\$STAGING_N orphaned pnpm staging dirs (name_pid_hash) under node_modules - the fingerprint of an install that was killed mid-write.\" # only when N > 0\n fi\n # The HEADLINE, kept in its own variable so DENY_EMIT_SH can paint ONLY it red (see there).\n WP_HEAD=\"❌ webpieces ai-hooks blocked this call: the webpieces guards are DOWN.\"\n REASON=\"\\$WP_HEAD\\${NL}\\${NL}${l0GuardHeader(L0_FAULT_BIN_BROKEN, '1 violation')}\\${NL} \\${BIN_NAME} (\\$CRASH_MSG)\\${NL} → it is installed but CRASHED, so your node_modules is corrupt or partially written; the guards cannot run and they must not be silently skipped. Every OTHER tool call is BLOCKED until they can.\\${STAGING_NOTE}\\${NL} → ${l0MatrixCitation(L0_FAULT_BIN_BROKEN)}\\${NL}\\${NL}\\${WP_STILL_ALLOWED}\\${NL}\\${NL} Fix Option 1: (preferred) the only cure. A bare 'pnpm install' will NOT fix this, because pnpm sees the correct version on disk and skips the broken package\\${NL} run EXACTLY: '${RECOVERY_CMD}'\\${NL}\\${NL}${NO_CHAINING_RULE}\"\nelif [ -n \"\\$DRIFT_PKG\" ]; then\n # DECIDE THE DIRECTION, do not make the reader do it (2026-08-03). The detection is a plain !=, so it\n # fires BOTH ways, and the message used to carry OPTION 1/2/3 covering every direction at once — 3343\n # chars of which only about a third was the decision. A reader on the wrong branch of that menu was\n # one misread away from a downgrade. So compare the two versions HERE and emit only the relevant half.\n #\n # WITH AWK, not \\`sort -V\\`: -V is a GNU extension (absent/different on BSD sort), while the shim\n # already runs an awk pass to resolve catalog: specs, so awk adds no dependency. The program compares\n # the numeric cores component-by-component; a pre-release/build suffix (-rc.1, +sha) is stripped from\n # the core, and when the cores are EQUAL the side carrying a PRE-RELEASE suffix is the older one\n # (semver precedence). Build metadata (+sha) carries NO precedence, so two versions differing only\n # there come back undecidable rather than ordered. Anything it cannot parse prints NOTHING, and an\n # empty answer falls through to the ambiguous wording below rather than guessing a direction.\n #\n # WHAT WAS DELETED, so it does not creep back: the \"how to get main itself current\" paragraph and the\n # \"do NOT reach for git merge --ff-only / reset --hard / checkout -B main\" paragraph both belong to\n # redirect-how-to-merge-main, which fires on its own with its own message; and the sentence that named\n # wp-start-update / wp-start-upsert-pr ONLY to forbid them while the block is up — naming a command\n # purely to forbid it is pure cost, and the install that clears this fault comes first regardless.\n DRIFT_DIR=\"\\$(awk -v i=\"\\$DRIFT_INSTALLED\" -v d=\"\\$DRIFT_DECLARED\" 'BEGIN {\n iv = i; sub(/\\\\+.*/, \"\", iv); ic = iv; sub(/-.*/, \"\", ic); ip = substr(iv, length(ic) + 1)\n dv = d; sub(/\\\\+.*/, \"\", dv); dc = dv; sub(/-.*/, \"\", dc); dp = substr(dv, length(dc) + 1)\n if (ic !~ /^[0-9]+(\\\\.[0-9]+)*\\$/ || dc !~ /^[0-9]+(\\\\.[0-9]+)*\\$/) exit\n n = split(ic, ia, \".\"); m = split(dc, da, \".\"); k = (n > m) ? n : m\n for (x = 1; x <= k; x++) {\n av = (x <= n) ? ia[x] + 0 : 0; bv = (x <= m) ? da[x] + 0 : 0\n if (av < bv) { print \"older\"; exit }\n if (av > bv) { print \"newer\"; exit }\n }\n if (ip == dp) exit\n if (ip != \"\" && dp == \"\") print \"older\"\n if (ip == \"\" && dp != \"\") print \"newer\"\n }' 2>/dev/null)\"\n if [ \"\\$DRIFT_DIR\" = older ]; then\n # The HEADLINE, kept in its own variable so DENY_EMIT_SH can paint ONLY it red (see there).\n WP_HEAD=\"❌ webpieces ai-hooks blocked this call: webpieces version drift.\"\n REASON=\"\\$WP_HEAD\\${NL}\\${NL}${l0GuardHeader(L0_FAULT_DRIFT, '1 violation')}\\${NL} package.json pins \\$DRIFT_PKG@\\$DRIFT_DECLARED but node_modules has \\$DRIFT_INSTALLED\\${NL} → node_modules is OLDER, so the pin is what you want. Every OTHER tool call is BLOCKED until the two agree.\\${NL} → ${l0MatrixCitation(L0_FAULT_DRIFT)}\\${NL}\\${NL}\\${WP_STILL_ALLOWED}\\${NL}\\${NL} Fix Option 1: (preferred) the only cure - it makes node_modules match the pin\\${NL} run EXACTLY: '\\$WP_INSTALL_CMD'\\${WP_BORROW_NOTE}\\${NL}\\${NL}${NO_CHAINING_RULE}\"\n else\n # NEWER, or undecidable — the same choices apply either way, so the only thing the ambiguous\n # case changes is the claim about which side is stale.\n DRIFT_NOTE=\"node_modules is NEWER, so the PIN is the stale side and a bare 'pnpm install' DOWNGRADES you to \\$DRIFT_DECLARED\"\n [ \"\\$DRIFT_DIR\" = newer ] || DRIFT_NOTE=\"these two versions could not be ordered automatically - compare them yourself: if node_modules is the NEWER side then the PIN is the stale side and a bare 'pnpm install' DOWNGRADES you to \\$DRIFT_DECLARED\"\n ${DRIFT_INVERSE_FIX_SH}\n # The HEADLINE, kept in its own variable so DENY_EMIT_SH can paint ONLY it red (see there).\n WP_HEAD=\"❌ webpieces ai-hooks blocked this call: webpieces version drift.\"\n REASON=\"\\$WP_HEAD\\${NL}\\${NL}${l0GuardHeader(L0_FAULT_DRIFT, '1 violation')}\\${NL} package.json pins \\$DRIFT_PKG@\\$DRIFT_DECLARED but node_modules has \\$DRIFT_INSTALLED\\${NL} → \\$DRIFT_NOTE. That may be exactly what you want. Every OTHER tool call is BLOCKED until the two agree.\\${NL} → ${l0MatrixCitation(L0_FAULT_DRIFT)}\\${NL}\\${NL}\\${WP_STILL_ALLOWED}\\${NL}\\${NL}\\${WP_FIX}\\${WP_BORROW_NOTE}\\${NL}\\${NL}${NO_CHAINING_RULE}\"\n fi\nelse\n # A LINKED WORKTREE is the overwhelmingly common way to land here with a perfectly healthy repo:\n # git gives the new worktree a .git FILE (the primary clone has a .git directory) and copies no\n # node_modules, so the very first tool call in a brand-new worktree fail-closes on a missing bin.\n # Naming that explicitly turns a baffling \"not installed\" into a one-command fix, and the HERE is\n # load-bearing: installing in the primary clone does nothing for this tree.\n WORKTREE_NOTE=\"\"\n if [ -f \"\\$ROOT/.git\" ]; then\n WORKTREE_NOTE=\"\\${NL} → \\$ROOT is a LINKED WORKTREE - git does not copy node_modules into a new worktree, so this is expected on a fresh one. Run the Fix Option HERE, in this worktree, not in the primary clone.\"\n fi\n if [ -z \"\\$WP_HOOK_PKG_DECLARED\" ]; then\n # FAULT U — the one shape where the X message is not merely unhelpful but actively WRONG. It asserted\n # \"declared in package.json\" without ever checking, and prescribed the one command that provably\n # cannot help: with nothing asking for the package, \\`pnpm install\\` reports \"Lockfile is up to date\"\n # and converges to the identical broken tree, forever. So say what is actually true, say out loud\n # that the install is a no-op (an agent that has already run it needs to be told to STOP), and\n # prescribe the add — which is allowlist entry ADD_HOOK_PKG, so it is reachable while this block is up.\n WP_ADD_CMD=\"${ADD_HOOK_PKG_CMD}\"\n [ -n \"\\$WP_PIN\" ] && WP_ADD_CMD=\"\\${WP_ADD_CMD}@\\$WP_PIN\"\n # The HEADLINE, kept in its own variable so DENY_EMIT_SH can paint ONLY it red (see there).\n WP_HEAD=\"❌ webpieces ai-hooks blocked this call: the guard package is not declared anywhere.\"\n REASON=\"\\$WP_HEAD\\${NL}\\${NL}${l0GuardHeader(L0_FAULT_UNDECLARED, '1 violation')}\\${NL} ${HOOK_PKG} is NOT declared in package.json anywhere, and is not installed (\\${BIN_NAME} not found)\\${NL} → .claude/settings.json still runs its hooks, so every OTHER tool call is BLOCKED. Do NOT run 'pnpm install': nothing asks for this package, so it is a NO-OP and repeating it converges to this same state.\\${NL} → ${l0MatrixCitation(L0_FAULT_UNDECLARED)}\\${NL}\\${NL}\\${WP_STILL_ALLOWED}\\${NL}\\${NL} Fix Option 1: (preferred) declare it directly, to unblock yourself right now\\${NL} run EXACTLY: '\\$WP_ADD_CMD'\\${NL} Fix Option 2: the durable fix - ${HOOK_PKG} normally arrives with @webpieces/nx-webpieces-rules, the umbrella that bundles the whole toolchain, so upgrade that once you are unblocked.\\${NL} NOT an option: if you removed ${HOOK_PKG} on purpose, delete its hooks from .claude/settings.json instead.\\${NL}\\${NL}${NO_CHAINING_RULE}\"\n else\n # The HEADLINE, kept in its own variable so DENY_EMIT_SH can paint ONLY it red (see there).\n WP_HEAD=\"❌ webpieces ai-hooks blocked this call: the webpieces guard bin is not installed.\"\n REASON=\"\\$WP_HEAD\\${NL}\\${NL}${l0GuardHeader(L0_FAULT_BIN_MISSING, '1 violation')}\\${NL} ${HOOK_PKG} is declared in package.json but is not installed (\\${BIN_NAME} not found)\\${NL} → the guards cannot run, so every OTHER tool call is BLOCKED until they can.\\${WORKTREE_NOTE}\\${NL} → ${l0MatrixCitation(L0_FAULT_BIN_MISSING)}\\${NL}\\${NL}\\${WP_STILL_ALLOWED}\\${NL}\\${NL} Fix Option 1: (preferred) the only cure - it materializes what package.json already asks for\\${NL} run EXACTLY: 'pnpm install'\\${NL} NOT an option: if you removed ${HOOK_PKG} on purpose, delete its hooks from .claude/settings.json instead.\\${NL}\\${NL}${NO_CHAINING_RULE}\"\n fi\nfi`;\n\nexport function renderShim(): string {\n return `#!/bin/sh\n# Managed by @webpieces/ai-hook-rules (wp-install-ai-hooks) — do not edit. This file is GENERATED from\n# renderShim() and is intentionally VERSION-AGNOSTIC and byte-STABLE across releases: it carries no\n# version stamp, so it only changes when its own logic changes. The installed guards binary is what\n# checks that this committed copy still matches renderShim() (the committed-shim self-guard); if you\n# revert or hand-edit this file the binary fails closed and names the cure. Checked in on purpose so\n# the hook has a stable entry point even when node_modules is absent. Safe to delete along with the\n# matching .claude/settings.json entries if you remove @webpieces/ai-hook-rules.\n#\n# Usage (wired into .claude/settings.json, ABSOLUTE so the MAIN tree governs every tree):\n# sh \"$CLAUDE_PROJECT_DIR/.claude/webpieces/ai-hook.sh\" <bin-name>\nBIN_NAME=\"$1\"\nshift\n# Resolve the tree relative to THIS script (…/<root>/.claude/webpieces/ai-hook.sh → <root>), not the\n# caller's cwd — the hook can be invoked from any directory (a subdir, or a nested clone).\nROOT=\"$(CDPATH= cd -- \"$(dirname -- \"$0\")/../..\" && pwd)\"\n# The JSON escapes every deny message below is assembled from (ANSI red, and the newlines that give the\n# deny the same scannable shape formatReport() gives every L1/L2 deny). See ESCAPES_SH's header.\n${ESCAPES_SH}\n# The BIN is resolved by walking UP from ROOT (as Node does), and BIN_ROOT records which tree supplied\n# it — the version-drift guard below compares THIS tree's pin against THAT tree's installed version.\n${RESOLVE_BIN_SH}\n${VERSION_DRIFT_GUARD_SH}\n# Read the tool payload ONCE, up front. The shim no longer exec's the bin (see RUN_BIN_SH), so it must\n# forward stdin to the bin itself — and it needs the payload again on the fail-closed path below.\nPAYLOAD=\"$(cat)\"\n${PARSE_PAYLOAD_SH}\n# Best-effort AUDIT TRAIL of what L0 did with this call — every call, not just the broken ones. One\n# tab-separated line per invocation into this TREE's own\n# logs/L0-shim/<session>-<agent|coordinator>-<binName>.log (gitignored), so the\n# observed behaviour can be diffed against the matrix in guards/L0-tooling.md. NEVER breaks or blocks the\n# hook: every write is swallowed, and nothing ever goes to stdout (stdout is the PreToolUse decision\n# channel — a stray byte there would corrupt allow/deny).\n${WP_LOG_SH}\nBROKEN_BIN=\"\"\nCRASH_MSG=\"\"\n${RUN_BIN_SH}\n# Bin missing (fresh clone before install) OR a version drift (stale node_modules) OR the bin is\n# installed but CRASHED (corrupt node_modules). The webpieces guards CANNOT safely run.\n# Before failing closed, peek at the tool payload and let ONLY package-manager install/recovery commands\n# through: the assistant's own Bash tool routes through this hook too, so blocking everything would\n# deadlock the very commands (pnpm install / rm -rf node_modules && pnpm install) that re-enable the\n# guards. A silent exit 0 = \"allow\" in the PreToolUse protocol; the guards resume once the tree is sane.\n${TRIAGE_SH}\n${DENY_REASON_SH}\n${DENY_EMIT_SH}\n`;\n}\n\n// Find the repo root that owns the committed shim to heal: walk up from `cwd` (the invocation's\n// actual dir) to the nearest ancestor holding a shim, falling back to $CLAUDE_PROJECT_DIR (which\n// Claude Code exports to hooks) only if the walk finds nothing. cwd-first keeps this correct for a\n// nested clone and testable (a temp root is honoured over the ambient project env). Returns null when\n// no committed shim exists (e.g. a global / absolute install, which has none to heal).\n//\n// Exported for install-entry.ts: on a CORRUPT node_modules, healShim is the only installer step that\n// can still run, so the installer must be able to tell the human whether a committed shim was actually\n// there to re-arm. Pure existsSync walk — never throws, so it needs no try/catch of its own.\n// webpieces-disable no-function-outside-class -- pure fs+path helper in the dependency-free shim module; it must not depend on DI (install-entry.ts relies on this loading on a corrupt tree).\nexport function findShimRoot(cwd: string): string | null {\n let dir = cwd;\n for (;;) {\n if (fs.existsSync(shimPath(dir))) return dir;\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n const env = process.env['CLAUDE_PROJECT_DIR'];\n if (env && fs.existsSync(shimPath(env))) return env;\n return null;\n}\n\n// Best-effort: keep the committed shim identical to renderShim() so the fail-closed escape hatch and\n// allowlist never drift. Only rewrites an EXISTING shim (never creates one) so global installs are\n// untouched. NEVER throws — a self-heal must never block or crash a tool call.\n//\n// The overwrite itself is correct and deliberate — shim and binary are two halves of one L0 and MUST\n// come from the same release (see shimStaleRecoveryDecision's header in ../adapters/hook-core).\n//\n// It needs no backup and no notice: the shim is a TRACKED file, so whatever it replaced is already in\n// git — `git diff` shows the rewrite, and a tamper is a working-tree modification git surfaces on its\n// own. In a consistent repo this is a no-op (committed shim already equals renderShim()); it earns its\n// keep on the upgrade path, where bumping the pin and installing leaves the committed shim behind and\n// this quietly brings it forward to be committed.\nexport function healShim(cwd: string): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const root = findShimRoot(cwd);\n if (!root) return;\n const target = shimPath(root);\n const desired = renderShim();\n if (fs.readFileSync(target, 'utf8') === desired) return;\n fs.writeFileSync(target, desired, { mode: 0o755 });\n fs.chmodSync(target, 0o755);\n } catch (err: unknown) {\n //const error = toError(err);\n // Ignore: healing is a convenience, not part of the guard decision.\n }\n}\n\n// ---------------------------------------------------------------------------\n// COMMITTED-SHIM SELF-GUARD — now enforced by the guards BINARY, not the shim (moved 2026-07-24).\n//\n// It used to live in the rendered shim (`cmp -s \"$0\" \"$WP_TEMPLATE\"` → fail closed). That was a\n// double-edged fix trap: the shim-matching logic lived IN the committed shim, so a bug in it could\n// only be fixed by regenerating the committed shim — which required passing the buggy shim's own gate\n// (via wp-upgrade-shim). The fix was locked behind the gate it needed to open.\n//\n// The drift guard MUST stay pre-binary (a stale validator can't be trusted to guard itself), but this\n// check's rationale — \"don't run possibly-stale shim logic\" — evaporates once the check is in the\n// binary: at that point the deciding code is the CURRENT binary from node_modules, not the reverted\n// shim. So the shim now only checks drift + bin-presence and always hands off; the binary (hook-core)\n// calls committedShimStale() and, on a mismatch, fails closed with shimStaleDenyReason() — the SAME\n// OPTION 1/2/3 message — while isShimCureCommand() lets the three cures through so the AI self-heals.\n// We deny + tell the AI; we do NOT silently rewrite the file under it. With the version stamp gone the\n// shim is byte-stable across releases, so this fires only on a genuine logic change or a real tamper.\n// ---------------------------------------------------------------------------\n\n// The root whose committed shim this BINARY governs — resolved from the RUNNING MODULE's own location,\n// never from process.cwd() and never from $CLAUDE_PROJECT_DIR. Same premise as installedShimRulesVersion()\n// below: the binary IS this package, so it can point at its OWN install.\n//\n// WHY IT MUST BE THE MODULE AND NOT THE CWD (the two-tree straddle, fixed 2026-08-03).\n// committedShimStale used to resolve its root by walking up from the invocation cwd, then compare that\n// tree's shim FILE against renderShim() — which is compiled into whichever binary is actually running.\n//\n// Which tree supplies the binary? settings.json runs $CLAUDE_PROJECT_DIR/.claude/webpieces/ai-hook.sh,\n// and that shim derives ROOT (hence BIN) from its own $0 — so the SESSION ROOT's tree supplies BOTH the\n// shim and the binary, and that pair is self-consistent by construction. A session rooted in a linked\n// worktree runs the worktree's shim and the worktree's binary; that is fine and is NOT the bug.\n//\n// The straddle appears when an agent's SESSION ROOT and its CWD are different trees — CLAUDE_PROJECT_DIR\n// is fixed at session start, so an agent that `cd`s into another checkout keeps running the session-root\n// tree's binary while findShimRoot(cwd) walks up into the OTHER tree. Each tree carries its own\n// node_modules at its own @webpieces version (seen in the wild: 0.4.545, 0.4.560 and 0.4.526 side by\n// side, every tree internally consistent). The comparison then straddles the two and can NEVER converge:\n// curing in the cwd tree renders with THAT tree's renderShim(), which the running binary's renderShim()\n// still rejects, so the cure re-fires the deny forever (observed: an agent gave up after four cures).\n//\n// Anchoring on __dirname makes the straddle UNCONSTRUCTIBLE rather than merely discouraged. It does not\n// pick a tree and privileges none: whichever tree the running binary came from is the tree whose shim it\n// compares, so the two halves of the comparison provably come from the same install either way.\n//\n// OUTERMOST node_modules wins, not innermost: under pnpm's linked layout __dirname realpaths to\n// <root>/node_modules/.pnpm/@webpieces+ai-hook-rules@X/node_modules/@webpieces/ai-hook-rules/src/bin —\n// the outermost segment lands on <root>, an innermost/first-ancestor rule lands inside the store.\n// With no node_modules segment at all we are running from a SOURCE checkout (vitest via tsconfig paths),\n// so walk up to the nearest ancestor that owns a shim. null = no committed shim to guard.\n// webpieces-disable no-function-outside-class -- pure fs+path helper in the dependency-free shim module, beside findShimRoot/healShim.\nexport function governingShimRoot(moduleDir: string = __dirname): string | null {\n const segments = moduleDir.split(path.sep);\n const outermost = segments.indexOf('node_modules');\n if (outermost > 0) {\n const root = segments.slice(0, outermost).join(path.sep);\n return fs.existsSync(shimPath(root)) ? root : null;\n }\n // A moduleDir that STARTS with node_modules is relative, so the root before it would be '' — i.e.\n // cwd-relative, the exact input this function exists to refuse. Nothing to govern.\n if (outermost === 0) return null;\n let dir = moduleDir;\n for (;;) {\n if (fs.existsSync(shimPath(dir))) return dir;\n const parent = path.dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\n// True when a committed shim EXISTS but no longer equals renderShim() (reverted, hand-edited, or a shim\n// whose LOGIC predates the installed binary). Missing shim → false: a fresh clone / global install has\n// nothing to guard, matching the old shim's `[ -f \"$WP_TEMPLATE\" ]` skip. Same comparison healShim\n// makes; never throws (an unreadable tree is treated as \"not stale\" so it can't wedge a tool call).\n//\n// The root defaults to governingShimRoot() — the decision's input is the MODULE's tree, never the cwd\n// (see governingShimRoot for the straddle this closes). The parameter exists ONLY so unit tests can\n// stage a temp root; nothing in production should pass one.\n// webpieces-disable no-function-outside-class -- pure fs+path helper in the shim module, beside healShim/renderShim.\nexport function committedShimStale(root: string | null = governingShimRoot()): boolean {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n if (root === null) return false;\n return fs.readFileSync(shimPath(root), 'utf8') !== renderShim();\n } catch (err: unknown) {\n const error = toError(err);\n void error; // best-effort: an unreadable tree counts as \"not stale\" so this never wedges a tool call\n return false;\n }\n}\n\n// True when `command` re-arms the committed shim — the two prescribed cures plus the installer, which\n// also heals the shim as its first step. These are the only commands allowed through while a stale\n// committed shim blocks everything else, so the AI can re-arm it. Each JS twin already tolerates\n// a trailing `2>&1 | tail -N` and rejects any `&&`-chained tail (see CAPTURE_TAIL_JS_SRC).\n// webpieces-disable no-function-outside-class -- pure predicate over the exported allowlist twins; belongs beside them in the shim module.\nexport function isShimCureCommand(command: string): boolean {\n const cmd = command.trim();\n return INSTALL_HOOKS_ALLOW_JS.test(cmd) || UPGRADE_SHIM_ALLOW_JS.test(cmd) || RESTORE_SHIM_ALLOW_JS.test(cmd);\n}\n\n// The shape of the fields we read out of this package's package.json.\ninterface ShimPackageManifest {\n readonly version?: string;\n}\n\n// The installed @webpieces/ai-hook-rules version, for shimStaleDenyReason's note. The binary IS this\n// package, so it reads its OWN package.json (two dirs up from src/bin). Best-effort: '' on any failure,\n// which shimStaleDenyReason renders as no note rather than a broken one.\n// webpieces-disable no-function-outside-class -- pure fs helper beside the shim module's other version plumbing.\nexport function installedShimRulesVersion(): string {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'package.json'), 'utf8')) as ShimPackageManifest;\n return pkg.version ?? '';\n } catch (err: unknown) {\n const error = toError(err);\n void error; // best-effort: no readable version → shimStaleDenyReason prints no note\n return '';\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"shim.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/bin/shim.ts"],"names":[],"mappings":";;;AAiDA,4BAEC;AAqVD,gCAgDC;AAYD,oCAWC;AAcD,4BAcC;AAmDD,8CAiBC;AAWD,gDAUC;AAOD,8CAGC;AAWD,8DAUC;;AAnmBD,+CAAyB;AACzB,mDAA6B;AAE7B,0DAAqE;AAErE,2DAGgC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AAG,CAAC,CAAC;QAC3B,KAAK,KAAK,CAAC,CAAC,wEAAwE;QACpF,OAAO,EAAE,CAAC;IACd,CAAC;AACL,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\n\nimport { CONFIG_FILENAME, claudeEnv } from '@webpieces/rules-config';\n\nimport {\n L0_FAULT_BIN_BROKEN, L0_FAULT_BIN_MISSING, L0_FAULT_DRIFT, L0_FAULT_UNDECLARED,\n l0GuardHeader, l0MatrixCitation,\n} from '../core/l0-fault-codes';\nimport { toError } from '../core/to-error';\nimport {\n L0_ALLOW_ERE_SH, RECOVERY_CMD, INSTALL_HOOKS_CMD, UPGRADE_SHIM_CMD, RESTORE_SHIM_CMD,\n INSTALL_HOOKS_ALLOW_JS, UPGRADE_SHIM_ALLOW_JS, RESTORE_SHIM_ALLOW_JS,\n ADD_HOOK_PKG_CMD, HOOK_PKG, WORKSPACE_MANIFEST, PACKAGE_MANIFEST,\n} from './l0-allowlist';\nimport { WP_LOG_SH } from './shim-audit-log';\nimport { DRIFT_INVERSE_FIX_SH } from './shim-drift-fix';\nimport { VERSION_DRIFT_GUARD_SH } from './shim-version-drift';\nimport { BASH_CWD_ENV_KEY, BASH_CWD_ENV_VALUE } from './managed-env';\n\n// The allowlist moved to ./l0-allowlist (this module was over the file-size limit); re-exported here so\n// every existing `from './shim'` import keeps working and there is still ONE name to import L0 by.\nexport * from './l0-allowlist';\n// Same treatment for the audit-log fragment: one name to import the whole rendered shim by.\nexport * from './shim-audit-log';\n\n// ---------------------------------------------------------------------------\n// The single checked-in shim (.claude/webpieces/ai-hook.sh). Both project hooks point at it, passing\n// their bin name as the first arg. settings.json points here (not at the bare bin) so a missing bin\n// (fresh clone, package removed) yields a friendly message instead of the raw `sh: No such file or\n// directory` on every Write/Edit/Bash tool call. `.claude` is committed, so the shim survives even\n// when node_modules does not.\n//\n// This module is the SINGLE SOURCE OF TRUTH for the shim body + the installer allowlist. The\n// installer (setup.ts) renders it on install; the running guards binary re-renders and self-heals it\n// (healShim) so the committed .sh can never go stale — no human ever hand-edits it.\n// ---------------------------------------------------------------------------\nexport const SHIM_MARKER = '.claude/webpieces/ai-hook.sh';\n\n// NO VERSION STAMP (removed 2026-07-24). The shim used to carry a per-release `# webpieces shim\n// version: <v> (<sha>)` on line 2, rewritten by scripts/set-version.sh at publish. It was a pure\n// human-eyeball diagnostic — nothing reads it (the deny's version note comes from the installed\n// package.json) — but it made the committed shim go byte-different on EVERY release even when the\n// logic was identical, so the committed-shim self-guard tripped on every upgrade over a comment (the\n// DENY-SHIM-STALE churn). It also carried its own hazard: stamp one of the two lockstep artifacts and\n// not the other and every consumer fail-closes forever on a phantom edit. Deleting it makes the shim\n// byte-STABLE across releases, so the self-guard (now in the binary) fires only on a genuine logic\n// change or a real tamper — which is what lets `pnpm install` be the fix for almost everything.\n\nexport function shimPath(projectRoot: string): string {\n return path.join(projectRoot, '.claude', 'webpieces', 'ai-hook.sh');\n}\n\n\n// ---------------------------------------------------------------------------\n// HOW EVERY DENY MUST SPELL ITS CURE (added 2026-07-23, from a live audit-log post-mortem).\n//\n// The guards were right, the message was right, and the assistant STILL handed the block back to the\n// human — because of one appended clause. From .webpieces/logs/L0-shim/<writer>.log in a consumer repo:\n//\n// DENY-SHIM-STALE cp node_modules/@webpieces/ai-hook-rules/templates/ai-hook.sh .claude/webpieces/ai-hook.sh && git status --short\n//\n// That is the prescribed cure, verbatim, plus `&& git status --short`. Every allowlist here is anchored\n// to `$`, so the trailing `&&` made it a different command and it was denied — and the assistant read\n// its own denial as proof that \"the guard blocks the very command that fixes it\" and stopped.\n//\n// Widening the allowlist to accept `&& <anything>` is NOT the fix: these are fail-CLOSED escape hatches\n// whose entire security property is that no shell operator can ride along (`cp … && rm -rf /`). The fix\n// is to stop the assistant appending in the first place — so every deny that prescribes a command now\n// (a) numbers its cures as OPTIONs, (b) quotes each one so the exact bytes are unambiguous, and\n// (c) carries this rule, which says in plain words that adding `&&` gets it rejected again.\n//\n// CONSTRAINT on every string that reaches a deny REASON: no double quotes and no backslashes. The\n// reason is interpolated into a `REASON=\"…\"` shell assignment and then printf'd into a JSON string, so\n// a `\"` would break BOTH. Hence single quotes around the commands here — do not \"improve\" them.\n// ---------------------------------------------------------------------------\n// LENGTH IS PART OF THE FIX (2026-08-03). This block used to run ~153 words and was repeated verbatim\n// in D, X and K — in X it was ~85% of the whole message, which buries the one sentence that matters.\n// It now states the rule and the three tolerated additions, and nothing else: the tolerated set is\n// exactly what CD_PREFIX_ERE + CAPTURE_TAIL_ERE accept (the single-quoted path branch of CD_PREFIX_ERE\n// is why \"single-quote a path containing spaces\" is named), so this text cannot promise more or less\n// than the allowlist grants.\nexport const NO_CHAINING_RULE =\n 'Run it EXACTLY as written - the allowlist matches the whole command, so appending anything ' +\n '(even && git status) makes it a different command and it is rejected; that is not the guard ' +\n 'blocking its own cure. Only these may be added: a leading cd <dir> && (single-quote a path ' +\n 'containing spaces), a trailing 2>&1, and | tail -N.';\n\n// Shell fragment: resolve the guard BIN by WALKING UP from ROOT, and remember WHERE it came from.\n//\n// THE BUG THIS CLOSES (it would have landed the day the hooks went relative). `ai-hook.sh` used to set\n// `BIN=\"$ROOT/node_modules/.bin/$BIN_NAME\"` — a LITERAL path with no upward walk, while Node's own\n// resolver walks up. That was correct only while the hooks were registered ABSOLUTE, because then ROOT\n// was always the primary clone and the bin was always there. The moment H2/H3 became relative, ROOT\n// became the tree the call is in — and a nested worktree at `<primary>/.claude/worktrees/<name>` has NO\n// node_modules of its own. Every subagent would have hard-blocked on fault X at its first tool call,\n// fleet-wide, on the day of the flip. Walking up finds the primary's install, exactly as a `require()`\n// from the same directory would; a SIBLING worktree finds nothing and correctly still faults X.\n//\n// BIN_ROOT is not a curiosity: walking up ALONE re-creates the version straddle documented above\n// committedShimStale(), where the shim of one tree is paired with the binary of another and the cure\n// can never converge. So BIN_ROOT is RECORDED, and the drift scan below uses it to decide WHOSE\n// question this is: when BIN_ROOT == ROOT the pin and the install belong to one tree and fault D\n// answers; when they differ the disagreement is CROSS-TREE and L0 stays silent so L1 row 8\n// (VersionSyncGuard), which reads all four versions, answers instead. See VERSION_DRIFT_GUARD_SH.\nconst RESOLVE_BIN_SH = `BIN_ROOT=\"\\$ROOT\"\nBIN=\"\\$ROOT/node_modules/.bin/\\$BIN_NAME\"\nWP_WALK=\"\\$ROOT\"\nwhile [ ! -x \"\\$WP_WALK/node_modules/.bin/\\$BIN_NAME\" ]; do\n WP_UP=\"\\$(dirname -- \"\\$WP_WALK\")\"\n [ \"\\$WP_UP\" != \"\\$WP_WALK\" ] || break\n WP_WALK=\"\\$WP_UP\"\ndone\nif [ -x \"\\$WP_WALK/node_modules/.bin/\\$BIN_NAME\" ]; then\n BIN_ROOT=\"\\$WP_WALK\"\n BIN=\"\\$WP_WALK/node_modules/.bin/\\$BIN_NAME\"\nfi`;\n\n// Normal template literal (not String.raw): it carries #235's shell escapes verbatim (\\${BIN_NAME},\n// \\$REASON, \\\\n for the deny JSON) AND my sed backslashes (doubled: \\\\(, \\\\), \\\\1, [^\"\\\\\\\\]). The\n// grep pattern is interpolated from INSTALLER_ALLOW_ERE (its value has no backslashes).\n// Shell fragment: the two JSON escapes the deny text is built from, plus the one shared \"what is still\n// allowed\" block. Hoisted to the TOP of the shim (it used to sit inside DENY_EMIT_SH's Bash branch,\n// i.e. AFTER every REASON was already assembled) because the deny text now needs the newline escape\n// while it is being BUILT, not only while it is being printed.\n//\n// THE MECHANISM IS THE ONE THE COLOUR ALREADY USED. `REASON` is interpolated into a `REASON=\"…\"` shell\n// assignment and then printf'd into a JSON string literal, so it may contain no RAW double-quote and no\n// RAW backslash — and a RAW newline would be invalid JSON. That constraint is not \"no newlines\": it is\n// \"no raw backslash\", and `${BS}` produces the backslash at RUNTIME, so `${ESC}` (six chars: \\ u 0 0 1 b)\n// and `${NL}` (two chars: \\ n) both travel as legal JSON escapes that Claude Code's parser turns back\n// into a real ESC and a real newline. Verified end to end through /bin/sh in setup.spec.ts: the payload\n// still parses as JSON, the systemMessage still carries 31;1m, and the reason renders as many lines.\n//\n// WHY THE STRUCTURE MATTERS: every L1/L2 deny is rendered by formatReport() into a scannable shape —\n// header, `[guard-name] (N violations)`, indented offenders each with a one-line `→ why`, then numbered\n// `Fix Option N:` lines. L0 was the ONLY layer answering in one unbroken paragraph. It now uses the same\n// skeleton, which is what WP_STILL_ALLOWED exists for: one definition of that section for all four\n// sh-side faults, so they cannot drift into four different answers to the same question.\nconst ESCAPES_SH = `BS='\\\\' # one literal backslash, so no \\\\u001b / \\\\n escape sits in this source\nESC=\"\\${BS}u001b\" # the 6 chars: backslash u 0 0 1 b — Claude Code parses \\\\u001b → ESC\nNL=\"\\${BS}n\" # the 2 chars: backslash n — parsed as a real newline inside the JSON string\nWP_STILL_ALLOWED=\"Still allowed while this block is up:\\${NL} - any Read\\${NL} - any Write/Edit whose target is ${CONFIG_FILENAME}, ${WORKSPACE_MANIFEST} or ${PACKAGE_MANIFEST}\\${NL} - every command on the L0 allowlist, including the Fix Options below\\${NL} THIS IS NOT A DEADLOCK - run one YOURSELF now; do not hand it back to the human.\"`;\n\n// Shell fragment: run the installed guard bin and INSPECT its outcome, instead of exec'ing it.\n//\n// THE BUG THIS FIXES (guards silently fail-OPEN): the shim used to `exec \"$BIN\"`. exec REPLACES this\n// shim process, so once the bin was executable the shim was GONE and could no longer make a decision.\n// That is fine when the bin runs — but the bin can be INSTALLED YET BROKEN: a corrupt/partially-written\n// node_modules makes node die at require() time with MODULE_NOT_FOUND, exiting 1. And in the PreToolUse\n// protocol ONLY exit 2 blocks: any other non-zero is a NON-BLOCKING error, so Claude Code prints\n// \"Failed with non-blocking status code\" and RUNS THE TOOL CALL ANYWAY — the guard is silently skipped.\n// Result: every Write/Edit/Bash went UNGUARDED, for as long as node_modules stayed corrupt. The shim\n// handled \"bin missing\" and \"bin stale\", but never \"bin present and CRASHES\" — the third failure mode.\n//\n// So: do not exec. Run the bin with the payload on stdin and branch on its exit code.\n// rc 0 | 2 → a REAL decision (allow / block). Relay stdout, stderr and the code byte-faithfully.\n// anything else → the guard CRASHED. Fall through to the fail-CLOSED path (BROKEN_BIN=1).\n// stdout/stderr go through temp FILES, not $(command substitution), so the bin's bytes reach Claude\n// Code exactly as written — command substitution strips trailing newlines and would corrupt the\n// decision JSON. Reading the payload up-front ($PAYLOAD) is what replaces exec's stdin passthrough.\nconst RUN_BIN_SH = `if [ -x \"\\$BIN\" ] && [ -z \"\\$DRIFT_PKG\" ]; then\n OUT_FILE=\"\\${TMPDIR:-/tmp}/wp-ai-hook-out.\\$\\$\"\n ERR_FILE=\"\\${TMPDIR:-/tmp}/wp-ai-hook-err.\\$\\$\"\n printf '%s' \"\\$PAYLOAD\" | \"\\$BIN\" \"\\$@\" >\"\\$OUT_FILE\" 2>\"\\$ERR_FILE\"\n RC=\\$?\n if [ \"\\$RC\" = 0 ] || [ \"\\$RC\" = 2 ]; then\n cat \"\\$OUT_FILE\" # the guard's real decision — verbatim\n cat \"\\$ERR_FILE\" >&2\n rm -f \"\\$OUT_FILE\" \"\\$ERR_FILE\" 2>/dev/null\n # THE HEALTHY CALL, which this log used to be silent about (see WP_LOG_SH's header). No sh-side\n # fault, the bin ran, and its own exit code says how it ended — 0 allow, 2 block. Logged AFTER the\n # decision bytes are already on stdout, so the audit trail never sits between the guard and Claude\n # Code. Without this line, \"no entry\" meant either healthy or never-ran, and those are the two\n # answers a reader most needs to tell apart.\n WP_VERDICT=PASS-BIN-ALLOW\n [ \"\\$RC\" = 2 ] && WP_VERDICT=PASS-BIN-BLOCK\n wp_log - \"\\$WP_VERDICT\"\n exit \"\\$RC\"\n fi\n # Crashed. Keep the most useful stderr line for the human. Strip \" and backslash so the text stays a\n # valid JSON string, and cap the length so a giant node stack cannot blow up the deny payload.\n CRASH_MSG=\"\\$(grep -m1 'Cannot find module' \"\\$ERR_FILE\" 2>/dev/null | tr -d '\"\\\\\\\\' | cut -c1-120)\"\n [ -n \"\\$CRASH_MSG\" ] || CRASH_MSG=\"\\$(head -n1 \"\\$ERR_FILE\" 2>/dev/null | tr -d '\"\\\\\\\\' | cut -c1-120)\"\n [ -n \"\\$CRASH_MSG\" ] || CRASH_MSG=\"exit code \\$RC, no stderr\"\n rm -f \"\\$OUT_FILE\" \"\\$ERR_FILE\" 2>/dev/null\n BROKEN_BIN=1\nfi`;\n\n// Shell fragment: pull the four fields the shim itself reasons about out of the tool payload.\n//\n// MOVED AHEAD OF THE BIN (it used to sit inside TRIAGE_SH, i.e. only on the fail-closed path) because\n// the audit log now covers the HEALTHY call too, and a log line needs the tool and the command whether\n// or not anything went wrong.\n//\n// `cwd` is Claude Code's documented \"current working directory when the hook is invoked\". It is used\n// for ONE thing: deciding which tree's log directory this line belongs in (see RESOLVE_LOG_DIR_SH).\n// It deliberately does NOT change what the drift guard MEASURES — that stays anchored to $ROOT, the\n// tree the shim FILE lives in. Where a call is logged and what a call is judged against are separate\n// questions and are kept separate here.\n// TWO command variables, and the split is a SECURITY boundary — do not collapse them.\n//\n// $CMD is the DECISION input (the L0 allowlist greps it). Its pattern requires the CLOSING quote, so a\n// JSON payload that escapes an embedded quote as \\\\\" yields the EMPTY STRING for the whole command.\n// That looks like a bug and is in fact the safe direction: an empty command matches no allowlist entry,\n// so a quoted command falls through to the deny. FAIL CLOSED. Keep it that way.\n//\n// $CMD_LOG is the AUDIT input and must never reach a decision. It drops the closing quote from the\n// pattern so it captures the command PREFIX instead of nothing.\n//\n// WHY THEY CANNOT BE ONE VARIABLE: every L0 allowlist ERE is anchored `^…[[:space:]]*$`, and trailing\n// whitespace is tolerated — so `pnpm install \"; rm -rf /\"` would prefix-capture to `pnpm install `,\n// which MATCHES, and the injection after the quote would ride through allowlisted. Measured 2026-08-06:\n// 3,908 of 4,917 shim audit lines (79.5%) recorded an empty command, i.e. four out of five audit\n// entries were blind. Fixing the LOG is worth doing; fixing the DECISION the same way is a hole.\nconst PARSE_PAYLOAD_SH = `CMD=\"\\$(printf '%s' \"\\$PAYLOAD\" | sed -n 's/.*\"command\"[[:space:]]*:[[:space:]]*\"\\\\([^\"\\\\\\\\]*\\\\)\".*/\\\\1/p')\"\nCMD_LOG=\"\\$(printf '%s' \"\\$PAYLOAD\" | sed -n 's/.*\"command\"[[:space:]]*:[[:space:]]*\"\\\\([^\"\\\\\\\\]*\\\\).*/\\\\1/p')\"\n[ -n \"\\$CMD_LOG\" ] || CMD_LOG=\"\\$CMD\"\nTOOL=\"\\$(printf '%s' \"\\$PAYLOAD\" | sed -n 's/.*\"tool_name\"[[:space:]]*:[[:space:]]*\"\\\\([^\"\\\\\\\\]*\\\\)\".*/\\\\1/p')\"\nWP_SID=\"\\$(printf '%s' \"\\$PAYLOAD\" | sed -n 's/.*\"session_id\"[[:space:]]*:[[:space:]]*\"\\\\([^\"\\\\\\\\]*\\\\)\".*/\\\\1/p')\"\nWP_AID=\"\\$(printf '%s' \"\\$PAYLOAD\" | sed -n 's/.*\"agent_id\"[[:space:]]*:[[:space:]]*\"\\\\([^\"\\\\\\\\]*\\\\)\".*/\\\\1/p')\"\nFILE=\"\\$(printf '%s' \"\\$PAYLOAD\" | sed -n 's/.*\"file_path\"[[:space:]]*:[[:space:]]*\"\\\\([^\"\\\\\\\\]*\\\\)\".*/\\\\1/p')\"\nWP_CWD=\"\\$(printf '%s' \"\\$PAYLOAD\" | sed -n 's/.*\"cwd\"[[:space:]]*:[[:space:]]*\"\\\\([^\"\\\\\\\\]*\\\\)\".*/\\\\1/p')\"\n[ -n \"\\$WP_CWD\" ] || WP_CWD=\"\\$ROOT\" # no cwd in the payload (older client, or a hand-run) → the shim's own tree`;\n\n// Shell fragment: the guards are DOWN (missing | stale | crashed). Classify the fault, then let THE L0\n// ALLOWLIST through — everything else falls to the deny below.\n//\n// This asks the identical question isAllowed() asks in JS, in the same order: Read, then the\n// webpieces.config.json target, then the one command union (L0_ALLOW_ERE). The sh and JS halves exist\n// because D/X/K are decided BEFORE the bin runs (a stale/missing/broken validator cannot validate\n// itself) while S/C/Y are decided inside it — one model, two enforcement points.\n//\n// NOTE the documented asymmetry: here the bin is never executed, so an allowed Read is TERMINAL and\n// read-stale-guard does not run. In JS the same entry falls through and it does. See isAllowed().\nconst TRIAGE_SH = `# WHICH of the guards/L0-tooling.md faults fired, in the doc's own letters. Only the four sh-side\n# codes can be decided here; S/C/Y live in the binary, which never got to run on this path.\nWP_FAULT=${L0_FAULT_BIN_MISSING} # X — bin missing (fresh clone, new worktree)\n[ -z \"\\$WP_HOOK_PKG_DECLARED\" ] && WP_FAULT=${L0_FAULT_UNDECLARED} # U — X, but nothing declares the package: install is a no-op\n[ -n \"\\$DRIFT_PKG\" ] && WP_FAULT=${L0_FAULT_DRIFT} # D — version drift; D and K are mutually exclusive\n[ -n \"\\$BROKEN_BIN\" ] && WP_FAULT=${L0_FAULT_BIN_BROKEN} # K — bin present but CRASHED (corrupt node_modules)\nDENY_LABEL=\"DENY\"\n[ -z \"\\$WP_HOOK_PKG_DECLARED\" ] && DENY_LABEL=\"DENY-UNDECLARED\" # nothing in package.json asks for the package\n[ -n \"\\$DRIFT_PKG\" ] && DENY_LABEL=\"DENY-STALE\" # version drift, not a missing bin\n[ -n \"\\$BROKEN_BIN\" ] && DENY_LABEL=\"DENY-BROKEN\" # bin present but CRASHED (corrupt node_modules)\n# THE L0 ALLOWLIST, entry order identical to isAllowed(). No fault is consulted: a cure that cannot\n# help a given fault also cannot hurt it, and gating each entry on a fault is what produced the four\n# defects recorded above L0_ALLOW_ERE.\nif [ \"\\$TOOL\" = \"Read\" ]; then\n wp_log \"\\$WP_FAULT\" ALLOW-READ # you must be able to read to work out how to fix this\n exit 0\nfi\ncase \"\\$FILE\" in\n */${CONFIG_FILENAME}|${CONFIG_FILENAME})\n wp_log \"\\$WP_FAULT\" ALLOW-CONFIG # the always-allowed recovery target — every guard is configured from it\n exit 0 ;;\n */${WORKSPACE_MANIFEST}|${WORKSPACE_MANIFEST}|*/${PACKAGE_MANIFEST}|${PACKAGE_MANIFEST})\n # A manifest AT THE ROOT OF A GOVERNED TREE, which is the only place the version pin lives. The test\n # is the sibling ${CONFIG_FILENAME} — TRACKED, so the main clone has one and every worktree has its\n # own — and NOT \\$ROOT, which names whichever tree supplied this shim and would deny the other's.\n # Basename alone would be far worse here than in the JS half: this arm is TERMINAL (exit 0, the bin\n # never runs), so every packages/**/package.json would be editable with nothing judging it.\n if [ -f \"\\$(dirname -- \"\\$FILE\")/${CONFIG_FILENAME}\" ]; then\n wp_log \"\\$WP_FAULT\" ALLOW-MANIFEST # raising the pin must be typable from inside the block\n exit 0\n fi ;;\nesac\nif printf '%s' \"\\$CMD\" | grep -Eq '${L0_ALLOW_ERE_SH}'; then\n wp_log \"\\$WP_FAULT\" ALLOW-CURE # record the self-heal we let through (re-enables the guards)\n exit 0 # allow the cure so the assistant can break the deadlock\nfi\nwp_log \"\\$WP_FAULT\" \"\\$DENY_LABEL\" # every fail-closed block, with the fault that caused it`;\n\n// Shell fragment: emit the deny. FAIL CLOSED via Claude Code's PreToolUse JSON protocol\n// (permissionDecision \"deny\" on stdout, then exit 0) rather than a bare \"exit 2\". BOTH block the call,\n// but the reason must be made VISIBLE, and HOW depends on the tool (verified by live tests; the docs\n// are wrong here):\n// - Bash deny: permissionDecisionReason is NOT shown to the human — ONLY a top-level systemMessage\n// is, and it honors ANSI. So for Bash we emit systemMessage wrapped in ANSI red so the\n// recovery command is visible (without it, on Bash, it is invisible).\n// - Write/Edit/MultiEdit deny: permissionDecisionReason renders as a RED \"Error:\" block natively —\n// no systemMessage needed (a second line would be redundant).\n// - NEVER exit 2 (stdout JSON ignored; stderr not reliably shown on a blocked Bash call).\n// The ESC and the newline escape are both built in ESCAPES_SH at the TOP of the shim (see its header):\n// ${ESC} is the literal 6-char JSON escape \\\\u001b and ${NL} the 2-char \\\\n, so no raw ESC byte, no raw\n// newline and no \\\\uXXXX sits in this source, and Claude Code's JSON parser turns both back. The reason\n// is a single JSON string with no RAW double-quotes/backslashes, so it stays valid JSON after the subs.\n//\n// ONLY THE HEADLINE IS RED, and that is deliberate — the same call redSystemMessage() makes on the JS\n// side. The reason is MULTI-LINE now, and a whole page in bold red is harder to read than the paragraph\n// it replaced: the indentation carrying the structure stops registering when every line shouts. So\n// \\$WP_HEAD (each branch's own first line, kept in its own variable for exactly this) is wrapped in\n// [31;1m … [0m, and \\${REASON#\"\\$WP_HEAD\"} — POSIX prefix removal with a QUOTED pattern, so the\n// headline is matched literally and not as a glob — supplies the plain body after it.\nconst DENY_EMIT_SH = `if [ \"\\$TOOL\" = \"Bash\" ]; then\n printf '{\"systemMessage\":\"%s🛑 %s%s%s\",\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"permissionDecision\":\"deny\",\"permissionDecisionReason\":\"%s\"}}\\\\n' \"\\${ESC}[31;1m\" \"\\$WP_HEAD\" \"\\${ESC}[0m\" \"\\${REASON#\"\\$WP_HEAD\"}\" \"\\$REASON\"\nelse\n printf '{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"permissionDecision\":\"deny\",\"permissionDecisionReason\":\"%s\"}}\\\\n' \"\\$REASON\"\nfi\nexit 0 # decision is carried by permissionDecision \"deny\", not the exit code`;\n\n// Shell fragment: pick the fail-closed deny REASON — a crashed-bin message (corrupt node_modules) vs a\n// version-drift message (bin present but stale) vs the missing-bin message. Extracted alongside\n// VERSION_DRIFT_GUARD_SH / RUN_BIN_SH to keep renderShim() within the method-line budget.\nconst DENY_REASON_SH = `if [ -n \"\\$BROKEN_BIN\" ]; then\n # Report (do NOT auto-clean) the orphaned pnpm staging dirs — a package pnpm was mid-way through\n # writing is left behind as <name>_<pid>_<hash>. Their presence is the fingerprint of an install that\n # was killed, which is what corrupts node_modules in the first place. Best-effort; never fatal.\n STAGING_N=\"\\$(ls \"\\$BIN_ROOT/node_modules\" 2>/dev/null | grep -Ec '_[0-9a-f]+_[0-9a-f]+\\$' || true)\"\n STAGING_NOTE=\"\"\n if [ \"\\${STAGING_N:-0}\" -gt 0 ] 2>/dev/null; then\n STAGING_NOTE=\"\\${NL} → also found \\$STAGING_N orphaned pnpm staging dirs (name_pid_hash) under node_modules - the fingerprint of an install that was killed mid-write.\" # only when N > 0\n fi\n # The HEADLINE, kept in its own variable so DENY_EMIT_SH can paint ONLY it red (see there).\n WP_HEAD=\"❌ webpieces ai-hooks blocked this call: the webpieces guards are DOWN.\"\n REASON=\"\\$WP_HEAD\\${NL}\\${NL}${l0GuardHeader(L0_FAULT_BIN_BROKEN, '1 violation')}\\${NL} \\${BIN_NAME} (\\$CRASH_MSG)\\${NL} → it is installed but CRASHED, so your node_modules is corrupt or partially written; the guards cannot run and they must not be silently skipped. Every OTHER tool call is BLOCKED until they can.\\${STAGING_NOTE}\\${NL} → ${l0MatrixCitation(L0_FAULT_BIN_BROKEN)}\\${NL}\\${NL}\\${WP_STILL_ALLOWED}\\${NL}\\${NL} Fix Option 1: (preferred) the only cure. A bare 'pnpm install' will NOT fix this, because pnpm sees the correct version on disk and skips the broken package\\${NL} run EXACTLY: '${RECOVERY_CMD}'\\${NL}\\${NL}${NO_CHAINING_RULE}\"\nelif [ -n \"\\$DRIFT_PKG\" ]; then\n # DECIDE THE DIRECTION, do not make the reader do it (2026-08-03). The detection is a plain !=, so it\n # fires BOTH ways, and the message used to carry OPTION 1/2/3 covering every direction at once — 3343\n # chars of which only about a third was the decision. A reader on the wrong branch of that menu was\n # one misread away from a downgrade. So compare the two versions HERE and emit only the relevant half.\n #\n # WITH AWK, not \\`sort -V\\`: -V is a GNU extension (absent/different on BSD sort), while the shim\n # already runs an awk pass to resolve catalog: specs, so awk adds no dependency. The program compares\n # the numeric cores component-by-component; a pre-release/build suffix (-rc.1, +sha) is stripped from\n # the core, and when the cores are EQUAL the side carrying a PRE-RELEASE suffix is the older one\n # (semver precedence). Build metadata (+sha) carries NO precedence, so two versions differing only\n # there come back undecidable rather than ordered. Anything it cannot parse prints NOTHING, and an\n # empty answer falls through to the ambiguous wording below rather than guessing a direction.\n #\n # WHAT WAS DELETED, so it does not creep back: the \"how to get main itself current\" paragraph and the\n # \"do NOT reach for git merge --ff-only / reset --hard / checkout -B main\" paragraph both belong to\n # redirect-how-to-merge-main, which fires on its own with its own message; and the sentence that named\n # wp-start-update / wp-start-upsert-pr ONLY to forbid them while the block is up — naming a command\n # purely to forbid it is pure cost, and the install that clears this fault comes first regardless.\n DRIFT_DIR=\"\\$(awk -v i=\"\\$DRIFT_INSTALLED\" -v d=\"\\$DRIFT_DECLARED\" 'BEGIN {\n iv = i; sub(/\\\\+.*/, \"\", iv); ic = iv; sub(/-.*/, \"\", ic); ip = substr(iv, length(ic) + 1)\n dv = d; sub(/\\\\+.*/, \"\", dv); dc = dv; sub(/-.*/, \"\", dc); dp = substr(dv, length(dc) + 1)\n if (ic !~ /^[0-9]+(\\\\.[0-9]+)*\\$/ || dc !~ /^[0-9]+(\\\\.[0-9]+)*\\$/) exit\n n = split(ic, ia, \".\"); m = split(dc, da, \".\"); k = (n > m) ? n : m\n for (x = 1; x <= k; x++) {\n av = (x <= n) ? ia[x] + 0 : 0; bv = (x <= m) ? da[x] + 0 : 0\n if (av < bv) { print \"older\"; exit }\n if (av > bv) { print \"newer\"; exit }\n }\n if (ip == dp) exit\n if (ip != \"\" && dp == \"\") print \"older\"\n if (ip == \"\" && dp != \"\") print \"newer\"\n }' 2>/dev/null)\"\n if [ \"\\$DRIFT_DIR\" = older ]; then\n # The HEADLINE, kept in its own variable so DENY_EMIT_SH can paint ONLY it red (see there).\n WP_HEAD=\"❌ webpieces ai-hooks blocked this call: webpieces version drift.\"\n REASON=\"\\$WP_HEAD\\${NL}\\${NL}${l0GuardHeader(L0_FAULT_DRIFT, '1 violation')}\\${NL} package.json pins \\$DRIFT_PKG@\\$DRIFT_DECLARED but node_modules has \\$DRIFT_INSTALLED\\${NL} → node_modules is OLDER, so the pin is what you want. Every OTHER tool call is BLOCKED until the two agree.\\${NL} → ${l0MatrixCitation(L0_FAULT_DRIFT)}\\${NL}\\${NL}\\${WP_STILL_ALLOWED}\\${NL}\\${NL} Fix Option 1: (preferred) the only cure - it makes node_modules match the pin\\${NL} run EXACTLY: 'pnpm install'\\${NL}\\${NL}${NO_CHAINING_RULE}\"\n else\n # NEWER, or undecidable — the same choices apply either way, so the only thing the ambiguous\n # case changes is the claim about which side is stale.\n DRIFT_NOTE=\"node_modules is NEWER, so the PIN is the stale side and a bare 'pnpm install' DOWNGRADES you to \\$DRIFT_DECLARED\"\n [ \"\\$DRIFT_DIR\" = newer ] || DRIFT_NOTE=\"these two versions could not be ordered automatically - compare them yourself: if node_modules is the NEWER side then the PIN is the stale side and a bare 'pnpm install' DOWNGRADES you to \\$DRIFT_DECLARED\"\n ${DRIFT_INVERSE_FIX_SH}\n # The HEADLINE, kept in its own variable so DENY_EMIT_SH can paint ONLY it red (see there).\n WP_HEAD=\"❌ webpieces ai-hooks blocked this call: webpieces version drift.\"\n REASON=\"\\$WP_HEAD\\${NL}\\${NL}${l0GuardHeader(L0_FAULT_DRIFT, '1 violation')}\\${NL} package.json pins \\$DRIFT_PKG@\\$DRIFT_DECLARED but node_modules has \\$DRIFT_INSTALLED\\${NL} → \\$DRIFT_NOTE. That may be exactly what you want. Every OTHER tool call is BLOCKED until the two agree.\\${NL} → ${l0MatrixCitation(L0_FAULT_DRIFT)}\\${NL}\\${NL}\\${WP_STILL_ALLOWED}\\${NL}\\${NL}\\${WP_FIX}\\${NL}\\${NL}${NO_CHAINING_RULE}\"\n fi\nelse\n # A LINKED WORKTREE is the overwhelmingly common way to land here with a perfectly healthy repo:\n # git gives the new worktree a .git FILE (the primary clone has a .git directory) and copies no\n # node_modules, so the very first tool call in a brand-new worktree fail-closes on a missing bin.\n # Naming that explicitly turns a baffling \"not installed\" into a one-command fix, and the HERE is\n # load-bearing: installing in the primary clone does nothing for this tree.\n WORKTREE_NOTE=\"\"\n if [ -f \"\\$ROOT/.git\" ]; then\n WORKTREE_NOTE=\"\\${NL} → \\$ROOT is a LINKED WORKTREE - git does not copy node_modules into a new worktree, so this is expected on a fresh one. Run the Fix Option HERE, in this worktree, not in the primary clone.\"\n fi\n if [ -z \"\\$WP_HOOK_PKG_DECLARED\" ]; then\n # FAULT U — the one shape where the X message is not merely unhelpful but actively WRONG. It asserted\n # \"declared in package.json\" without ever checking, and prescribed the one command that provably\n # cannot help: with nothing asking for the package, \\`pnpm install\\` reports \"Lockfile is up to date\"\n # and converges to the identical broken tree, forever. So say what is actually true, say out loud\n # that the install is a no-op (an agent that has already run it needs to be told to STOP), and\n # prescribe the add — which is allowlist entry ADD_HOOK_PKG, so it is reachable while this block is up.\n WP_ADD_CMD=\"${ADD_HOOK_PKG_CMD}\"\n [ -n \"\\$WP_PIN\" ] && WP_ADD_CMD=\"\\${WP_ADD_CMD}@\\$WP_PIN\"\n # The HEADLINE, kept in its own variable so DENY_EMIT_SH can paint ONLY it red (see there).\n WP_HEAD=\"❌ webpieces ai-hooks blocked this call: the guard package is not declared anywhere.\"\n REASON=\"\\$WP_HEAD\\${NL}\\${NL}${l0GuardHeader(L0_FAULT_UNDECLARED, '1 violation')}\\${NL} ${HOOK_PKG} is NOT declared in package.json anywhere, and is not installed (\\${BIN_NAME} not found)\\${NL} → .claude/settings.json still runs its hooks, so every OTHER tool call is BLOCKED. Do NOT run 'pnpm install': nothing asks for this package, so it is a NO-OP and repeating it converges to this same state.\\${NL} → ${l0MatrixCitation(L0_FAULT_UNDECLARED)}\\${NL}\\${NL}\\${WP_STILL_ALLOWED}\\${NL}\\${NL} Fix Option 1: (preferred) declare it directly, to unblock yourself right now\\${NL} run EXACTLY: '\\$WP_ADD_CMD'\\${NL} Fix Option 2: the durable fix - ${HOOK_PKG} normally arrives with @webpieces/nx-webpieces-rules, the umbrella that bundles the whole toolchain, so upgrade that once you are unblocked.\\${NL} NOT an option: if you removed ${HOOK_PKG} on purpose, delete its hooks from .claude/settings.json instead.\\${NL}\\${NL}${NO_CHAINING_RULE}\"\n else\n # The HEADLINE, kept in its own variable so DENY_EMIT_SH can paint ONLY it red (see there).\n WP_HEAD=\"❌ webpieces ai-hooks blocked this call: the webpieces guard bin is not installed.\"\n REASON=\"\\$WP_HEAD\\${NL}\\${NL}${l0GuardHeader(L0_FAULT_BIN_MISSING, '1 violation')}\\${NL} ${HOOK_PKG} is declared in package.json but is not installed (\\${BIN_NAME} not found)\\${NL} → the guards cannot run, so every OTHER tool call is BLOCKED until they can.\\${WORKTREE_NOTE}\\${NL} → ${l0MatrixCitation(L0_FAULT_BIN_MISSING)}\\${NL}\\${NL}\\${WP_STILL_ALLOWED}\\${NL}\\${NL} Fix Option 1: (preferred) the only cure - it materializes what package.json already asks for\\${NL} run EXACTLY: 'pnpm install'\\${NL} NOT an option: if you removed ${HOOK_PKG} on purpose, delete its hooks from .claude/settings.json instead.\\${NL}\\${NL}${NO_CHAINING_RULE}\"\n fi\nfi`;\n\nexport function renderShim(): string {\n return `#!/bin/sh\n# Managed by @webpieces/ai-hook-rules (wp-install-ai-hooks) — do not edit. This file is GENERATED from\n# renderShim() and is intentionally VERSION-AGNOSTIC and byte-STABLE across releases: it carries no\n# version stamp, so it only changes when its own logic changes. The installed guards binary is what\n# checks that this committed copy still matches renderShim() (the committed-shim self-guard); if you\n# revert or hand-edit this file the binary fails closed and names the cure. Checked in on purpose so\n# the hook has a stable entry point even when node_modules is absent. Safe to delete along with the\n# matching .claude/settings.json entries if you remove @webpieces/ai-hook-rules.\n#\n# Usage (wired into .claude/settings.json, ABSOLUTE so the MAIN tree governs every tree):\n# sh \"$CLAUDE_PROJECT_DIR/.claude/webpieces/ai-hook.sh\" <bin-name>\nBIN_NAME=\"$1\"\nshift\n# Resolve the tree relative to THIS script (…/<root>/.claude/webpieces/ai-hook.sh → <root>), not the\n# caller's cwd — the hook can be invoked from any directory (a subdir, or a nested clone).\nROOT=\"$(CDPATH= cd -- \"$(dirname -- \"$0\")/../..\" && pwd)\"\n# The JSON escapes every deny message below is assembled from (ANSI red, and the newlines that give the\n# deny the same scannable shape formatReport() gives every L1/L2 deny). See ESCAPES_SH's header.\n${ESCAPES_SH}\n# The BIN is resolved by walking UP from ROOT (as Node does), and BIN_ROOT records which tree supplied\n# it — the version-drift guard below compares THIS tree's pin against THAT tree's installed version.\n${RESOLVE_BIN_SH}\n${VERSION_DRIFT_GUARD_SH}\n# Read the tool payload ONCE, up front. The shim no longer exec's the bin (see RUN_BIN_SH), so it must\n# forward stdin to the bin itself — and it needs the payload again on the fail-closed path below.\nPAYLOAD=\"$(cat)\"\n${PARSE_PAYLOAD_SH}\n# Best-effort AUDIT TRAIL of what L0 did with this call — every call, not just the broken ones. One\n# tab-separated line per invocation into this TREE's own\n# logs/L0-shim/<session>-<agent|coordinator>-<binName>.log (gitignored), so the\n# observed behaviour can be diffed against the matrix in guards/L0-tooling.md. NEVER breaks or blocks the\n# hook: every write is swallowed, and nothing ever goes to stdout (stdout is the PreToolUse decision\n# channel — a stray byte there would corrupt allow/deny).\n${WP_LOG_SH}\nBROKEN_BIN=\"\"\nCRASH_MSG=\"\"\n${RUN_BIN_SH}\n# Bin missing (fresh clone before install) OR a version drift (stale node_modules) OR the bin is\n# installed but CRASHED (corrupt node_modules). The webpieces guards CANNOT safely run.\n# Before failing closed, peek at the tool payload and let ONLY package-manager install/recovery commands\n# through: the assistant's own Bash tool routes through this hook too, so blocking everything would\n# deadlock the very commands (pnpm install / rm -rf node_modules && pnpm install) that re-enable the\n# guards. A silent exit 0 = \"allow\" in the PreToolUse protocol; the guards resume once the tree is sane.\n${TRIAGE_SH}\n${DENY_REASON_SH}\n${DENY_EMIT_SH}\n`;\n}\n\n// Find the repo root that owns the committed shim to heal: walk up from `cwd` (the invocation's\n// actual dir) to the nearest ancestor holding a shim, falling back to $CLAUDE_PROJECT_DIR (which\n// Claude Code exports to hooks) only if the walk finds nothing. cwd-first keeps this correct for a\n// nested clone and testable (a temp root is honoured over the ambient project env). Returns null when\n// no committed shim exists (e.g. a global / absolute install, which has none to heal).\n//\n// Exported for install-entry.ts: on a CORRUPT node_modules, healShim is the only installer step that\n// can still run, so the installer must be able to tell the human whether a committed shim was actually\n// there to re-arm. Pure existsSync walk — never throws, so it needs no try/catch of its own.\n// webpieces-disable no-function-outside-class -- pure fs+path helper in the dependency-free shim module; it must not depend on DI (install-entry.ts relies on this loading on a corrupt tree).\nexport function findShimRoot(cwd: string): string | null {\n let dir = cwd;\n for (;;) {\n if (fs.existsSync(shimPath(dir))) return dir;\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n const env = process.env['CLAUDE_PROJECT_DIR'];\n if (env && fs.existsSync(shimPath(env))) return env;\n return null;\n}\n\n// Best-effort: keep the committed shim identical to renderShim() so the fail-closed escape hatch and\n// allowlist never drift. Only rewrites an EXISTING shim (never creates one) so global installs are\n// untouched. NEVER throws — a self-heal must never block or crash a tool call.\n//\n// The overwrite itself is correct and deliberate — shim and binary are two halves of one L0 and MUST\n// come from the same release (see shimStaleRecoveryDecision's header in ../adapters/hook-core).\n//\n// It needs no backup and no notice: the shim is a TRACKED file, so whatever it replaced is already in\n// git — `git diff` shows the rewrite, and a tamper is a working-tree modification git surfaces on its\n// own. In a consistent repo this is a no-op (committed shim already equals renderShim()); it earns its\n// keep on the upgrade path, where bumping the pin and installing leaves the committed shim behind and\n// this quietly brings it forward to be committed.\nexport function healShim(cwd: string): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const root = findShimRoot(cwd);\n if (!root) return;\n const target = shimPath(root);\n const desired = renderShim();\n if (fs.readFileSync(target, 'utf8') === desired) return;\n fs.writeFileSync(target, desired, { mode: 0o755 });\n fs.chmodSync(target, 0o755);\n } catch (err: unknown) {\n //const error = toError(err);\n // Ignore: healing is a convenience, not part of the guard decision.\n }\n}\n\n// ---------------------------------------------------------------------------\n// COMMITTED-SHIM SELF-GUARD — now enforced by the guards BINARY, not the shim (moved 2026-07-24).\n//\n// It used to live in the rendered shim (`cmp -s \"$0\" \"$WP_TEMPLATE\"` → fail closed). That was a\n// double-edged fix trap: the shim-matching logic lived IN the committed shim, so a bug in it could\n// only be fixed by regenerating the committed shim — which required passing the buggy shim's own gate\n// (via wp-upgrade-shim). The fix was locked behind the gate it needed to open.\n//\n// The drift guard MUST stay pre-binary (a stale validator can't be trusted to guard itself), but this\n// check's rationale — \"don't run possibly-stale shim logic\" — evaporates once the check is in the\n// binary: at that point the deciding code is the CURRENT binary from node_modules, not the reverted\n// shim. So the shim now only checks drift + bin-presence and always hands off; the binary (hook-core)\n// calls committedShimStale() and, on a mismatch, fails closed with shimStaleDenyReason() — the SAME\n// OPTION 1/2/3 message — while isShimCureCommand() lets the three cures through so the AI self-heals.\n// We deny + tell the AI; we do NOT silently rewrite the file under it. With the version stamp gone the\n// shim is byte-stable across releases, so this fires only on a genuine logic change or a real tamper.\n// ---------------------------------------------------------------------------\n\n// The root whose committed shim this BINARY governs — resolved from the RUNNING MODULE's own location,\n// never from process.cwd() and never from $CLAUDE_PROJECT_DIR. Same premise as installedShimRulesVersion()\n// below: the binary IS this package, so it can point at its OWN install.\n//\n// WHY IT MUST BE THE MODULE AND NOT THE CWD (the two-tree straddle, fixed 2026-08-03).\n// committedShimStale used to resolve its root by walking up from the invocation cwd, then compare that\n// tree's shim FILE against renderShim() — which is compiled into whichever binary is actually running.\n//\n// Which tree supplies the binary? settings.json runs $CLAUDE_PROJECT_DIR/.claude/webpieces/ai-hook.sh,\n// and that shim derives ROOT (hence BIN) from its own $0 — so the SESSION ROOT's tree supplies BOTH the\n// shim and the binary, and that pair is self-consistent by construction. A session rooted in a linked\n// worktree runs the worktree's shim and the worktree's binary; that is fine and is NOT the bug.\n//\n// The straddle appears when an agent's SESSION ROOT and its CWD are different trees — CLAUDE_PROJECT_DIR\n// is fixed at session start, so an agent that `cd`s into another checkout keeps running the session-root\n// tree's binary while findShimRoot(cwd) walks up into the OTHER tree. Each tree carries its own\n// node_modules at its own @webpieces version (seen in the wild: 0.4.545, 0.4.560 and 0.4.526 side by\n// side, every tree internally consistent). The comparison then straddles the two and can NEVER converge:\n// curing in the cwd tree renders with THAT tree's renderShim(), which the running binary's renderShim()\n// still rejects, so the cure re-fires the deny forever (observed: an agent gave up after four cures).\n//\n// Anchoring on __dirname makes the straddle UNCONSTRUCTIBLE rather than merely discouraged. It does not\n// pick a tree and privileges none: whichever tree the running binary came from is the tree whose shim it\n// compares, so the two halves of the comparison provably come from the same install either way.\n//\n// OUTERMOST node_modules wins, not innermost: under pnpm's linked layout __dirname realpaths to\n// <root>/node_modules/.pnpm/@webpieces+ai-hook-rules@X/node_modules/@webpieces/ai-hook-rules/src/bin —\n// the outermost segment lands on <root>, an innermost/first-ancestor rule lands inside the store.\n// With no node_modules segment at all we are running from a SOURCE checkout (vitest via tsconfig paths),\n// so walk up to the nearest ancestor that owns a shim. null = no committed shim to guard.\n// webpieces-disable no-function-outside-class -- pure fs+path helper in the dependency-free shim module, beside findShimRoot/healShim.\nexport function governingShimRoot(moduleDir: string = __dirname): string | null {\n const segments = moduleDir.split(path.sep);\n const outermost = segments.indexOf('node_modules');\n if (outermost > 0) {\n const root = segments.slice(0, outermost).join(path.sep);\n return fs.existsSync(shimPath(root)) ? root : null;\n }\n // A moduleDir that STARTS with node_modules is relative, so the root before it would be '' — i.e.\n // cwd-relative, the exact input this function exists to refuse. Nothing to govern.\n if (outermost === 0) return null;\n let dir = moduleDir;\n for (;;) {\n if (fs.existsSync(shimPath(dir))) return dir;\n const parent = path.dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\n// True when a committed shim EXISTS but no longer equals renderShim() (reverted, hand-edited, or a shim\n// whose LOGIC predates the installed binary). Missing shim → false: a fresh clone / global install has\n// nothing to guard, matching the old shim's `[ -f \"$WP_TEMPLATE\" ]` skip. Same comparison healShim\n// makes; never throws (an unreadable tree is treated as \"not stale\" so it can't wedge a tool call).\n//\n// The root defaults to governingShimRoot() — the decision's input is the MODULE's tree, never the cwd\n// (see governingShimRoot for the straddle this closes). The parameter exists ONLY so unit tests can\n// stage a temp root; nothing in production should pass one.\n// webpieces-disable no-function-outside-class -- pure fs+path helper in the shim module, beside healShim/renderShim.\nexport function committedShimStale(root: string | null = governingShimRoot()): boolean {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n if (root === null) return false;\n return fs.readFileSync(shimPath(root), 'utf8') !== renderShim();\n } catch (err: unknown) {\n const error = toError(err);\n void error; // best-effort: an unreadable tree counts as \"not stale\" so this never wedges a tool call\n return false;\n }\n}\n\n// True when `command` re-arms the committed shim — the two prescribed cures plus the installer, which\n// also heals the shim as its first step. These are the only commands allowed through while a stale\n// committed shim blocks everything else, so the AI can re-arm it. Each JS twin already tolerates\n// a trailing `2>&1 | tail -N` and rejects any `&&`-chained tail (see CAPTURE_TAIL_JS_SRC).\n// webpieces-disable no-function-outside-class -- pure predicate over the exported allowlist twins; belongs beside them in the shim module.\nexport function isShimCureCommand(command: string): boolean {\n const cmd = command.trim();\n return INSTALL_HOOKS_ALLOW_JS.test(cmd) || UPGRADE_SHIM_ALLOW_JS.test(cmd) || RESTORE_SHIM_ALLOW_JS.test(cmd);\n}\n\n// The shape of the fields we read out of this package's package.json.\ninterface ShimPackageManifest {\n readonly version?: string;\n}\n\n// The installed @webpieces/ai-hook-rules version, for shimStaleDenyReason's note. The binary IS this\n// package, so it reads its OWN package.json (two dirs up from src/bin). Best-effort: '' on any failure,\n// which shimStaleDenyReason renders as no note rather than a broken one.\n// webpieces-disable no-function-outside-class -- pure fs helper beside the shim module's other version plumbing.\nexport function installedShimRulesVersion(): string {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'package.json'), 'utf8')) as ShimPackageManifest;\n return pkg.version ?? '';\n } catch (err: unknown) {\n const error = toError(err);\n void error; // best-effort: no readable version → shimStaleDenyReason prints no note\n return '';\n }\n}\n"]}
|
package/src/core/l1-rows.js
CHANGED
|
@@ -199,8 +199,8 @@ exports.L1_ROWS = [
|
|
|
199
199
|
// denies, logged as `row=`, and cited in guards/L1-location.md — so renumbering would silently
|
|
200
200
|
// re-point every historical reference. Its replacement is row 8.
|
|
201
201
|
new L1Row(8, 'w', 'n', 'n', '-', '-', exports.ACT_BLOCK, 'this worktree pins a DIFFERENT @webpieces than the main tree that governs it', new L1Cure('align the pins (same git hash -> same tracked pin -> install in each tree), work in the main tree, or use a separate clone', '@webpieces version SKEW', false), 'trinary-version-skew', [
|
|
202
|
-
new L1UseCase(12, 'a worktree on an older branch pins `0.4.612` while the main tree runs `0.4.616`, and `cd <wt> && pnpm build` is blocked', '`w` / `n` / `n` — row 8', 'BLOCK_AI_CURE', 'Option 1 (preferred):
|
|
203
|
-
new L1UseCase(16, 'a SUBAGENT hits the same block inside `.claude/worktrees/agent-XXXX`', '`w` / `n` / `n` — row 8; in-repo placement is still `w`', 'BLOCK_AI_CURE', '
|
|
202
|
+
new L1UseCase(12, 'a worktree on an older branch pins `0.4.612` while the main tree runs `0.4.616`, and `cd <wt> && pnpm build` is blocked', '`w` / `n` / `n` — row 8', 'BLOCK_AI_CURE', 'Option 1 (preferred): the MAIN tree is AHEAD, so this is YOURS and it is a one-line edit — raise THIS tree\'s catalog pin in `pnpm-workspace.yaml` to what main already runs, then `pnpm install` here if this tree has a node_modules. That edit is on the L0 allowlist, so it is typable while the block is up, and nothing has to move in the main tree<br>Option 2: do the work in the main tree, which this guard never blocks<br>Option 3: if the tree genuinely needs a DIFFERENT version, use a separate CLONE — a clone gets its own governance. That is the answer to "I need a different version", never to "I need to install here": a worktree MAY have its own node_modules (nx, vitest and the eslint plugin all load from it), it just may not hold a different @webpieces version<br>Do NOT: lower the MAIN tree\'s pin to match — that downgrades every tree, including this session\'s own governor. And do NOT reach for `pnpm install` BEFORE the edit: this tree\'s pin is the stale side, so installing first materializes the OLD release', new L1Classification('w', true, false, false, false)),
|
|
203
|
+
new L1UseCase(16, 'a SUBAGENT hits the same block inside `.claude/worktrees/agent-XXXX`', '`w` / `n` / `n` — row 8; in-repo placement is still `w`', 'BLOCK_AI_CURE', 'READ THE DIRECTION FIRST — the deny prints it. If the MAIN tree is AHEAD (the common case) a subagent fixes this ITSELF, here, by raising this tree\'s pin to what main already runs; there is nothing to escalate and the deny prints no escalation. Only when main is BEHIND, or when this branch bumped the pin on purpose, is the subagent stuck — the main tree is outside its tree, and a worktree-isolated agent may not even still be in the tree it was launched in (measured: auto-reaped at a turn boundary, resumed on the primary). Then, and only then, forward the deny\'s verbatim ask to the coordinator and STOP<br>Do NOT: expect exemption because it sits under the repo — K is git\'s `--git-common-dir` answer, not a path test', new L1Classification('w', true, false, false, false)),
|
|
204
204
|
]),
|
|
205
205
|
new L1Row(4, 'pw', '-', '-', 'n', '-', exports.ACT_DOWN, 'force-to-root has no jurisdiction', null, null, [
|
|
206
206
|
new L1UseCase(5, '`ls` from `packages/http/` runs normally', '`pw` / `n` / - — row 4', 'ALLOW (handed to L2)', 'none — force-to-root has no jurisdiction over non-git commands', new L1Classification('p', false, true, false, false)),
|
package/src/core/l1-rows.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"l1-rows.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/core/l1-rows.ts"],"names":[],"mappings":";;;AAgXA,sCAGC;AAUD,gDAIC;AA5UD;;;;;;;;;;;GAWG;AACU,QAAA,eAAe,GAAG,GAAG,CAAC;AAEnC;;;;;GAKG;AACH,MAAa,gBAAgB;IAGZ;IACA;IACA;IACA;IACA;IANb,kGAAkG;IAClG,YACa,IAAY,EACZ,cAAuB,EACvB,QAAiB,EACjB,GAAY,EACZ,MAAe;QAJf,SAAI,GAAJ,IAAI,CAAQ;QACZ,mBAAc,GAAd,cAAc,CAAS;QACvB,aAAQ,GAAR,QAAQ,CAAS;QACjB,QAAG,GAAH,GAAG,CAAS;QACZ,WAAM,GAAN,MAAM,CAAS;IACzB,CAAC;IAEJ;;;;;;;;;;OAUG;IACH,oGAAoG;IACpG,kMAAkM;IAClM,MAAM,CAAC,cAAc,CACjB,QAAkB,EAClB,cAAuB,EACvB,QAAiB,EACjB,GAAY,EACZ,MAAe;QAEf,MAAM,IAAI,GAAW,QAAQ,KAAK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wEAAwE,CAAC;IAC7E,IAAI,SAAS,CAAC,CAAC,EACX,uEAAuE,EACvE,4BAA4B,EAC5B,MAAM,EACN,+EAA+E,CAAC;IACpF,IAAI,SAAS,CAAC,EAAE,EACZ,2GAA2G,EAC3G,+FAA+F,EAC/F,cAAc,EACd,oFAAoF,CAAC;IACzF,IAAI,SAAS,CAAC,EAAE,EACZ,iFAAiF,EACjF,2BAA2B,EAC3B,OAAO,EACP,mDAAmD,CAAC;CAC3D,CAAC;AAEF,4FAA4F;AAC5F,0HAA0H;AAC1H,SAAgB,aAAa;IACzB,MAAM,GAAG,GAAG,CAAC,GAAG,eAAO,CAAC,OAAO,CAAC,CAAC,GAAU,EAAwB,EAAE,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,GAAG,4BAAoB,CAAC,CAAC;IAC9G,OAAO,GAAG,CAAC,IAAI,CAAC,CAAC,CAAY,EAAE,CAAY,EAAU,EAAE,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;AAC3E,CAAC;AAED;;;;;;GAMG;AACH,qGAAqG;AACrG,SAAgB,kBAAkB,CAAC,CAAmB;IAClD,MAAM,GAAG,GAAG,eAAO,CAAC,IAAI,CAAC,CAAC,CAAQ,EAAW,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;IAC9D,IAAI,GAAG,KAAK,SAAS;QAAE,MAAM,IAAI,KAAK,CAAC,wCAAwC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IACpG,OAAO,GAAG,CAAC;AACf,CAAC","sourcesContent":["import type { TreeKind } from './effective-tree';\n\n// ---------------------------------------------------------------------------\n// L1 — the LOCATION layer, as data.\n//\n// L1 answers four questions: do we govern this call at all, does the directory still EXIST, is the\n// WRONG AGENT standing here, and is the agent stranded away from the root? Drawn as a decision matrix\n// that is SEVEN ordered rows over five dimensions (K/A/R/G/P), first match wins.\n//\n// This module holds those rows, and l1-doc.ts renders them into guards/L1-location.md — the doc a human\n// reads on GitHub. A unit test locks that file byte-identical to the renderer, and the guard itself\n// CONSULTS L1_ROWS to decide which structural block fires (see runner.l1LocationBlock). Doc and code\n// come from the SAME array, so they cannot drift.\n//\n// This module is deliberately import-free at runtime (only a type-only import above), so\n// `pnpm guards:generate` can load it without the package's transitive dependencies.\n// ---------------------------------------------------------------------------\n\n/**\n * The K dimension as a CLASSIFICATION carries — one concrete tree, never the `pw` union.\n *\n * `p` and `w` are the same PROJECT and every rule-scoped guard treats them alike; the doc writes the\n * pair as `pw` in the row's MATCHER (below), which is a different vocabulary on purpose.\n */\nexport type L1Kind = 'f' | 'm' | 'o' | 'p' | 'w';\n\n/** The K value a ROW matches on. `pw` matches both `p` and `w`; `-` is the wildcard. */\nexport type L1KindMatch = 'f' | 'm' | 'o' | 'w' | 'pw' | '-';\n\n/** R and G are yes/no, written `y`/`n` in the doc, with `-` for \"does not matter\". */\nexport type L1Flag = 'y' | 'n' | '-';\n\n/**\n * V is the same one boolean wearing the doc's own letters: `n` the webpieces versions do NOT agree\n * between this worktree and the main tree, `y` they do.\n *\n * This dimension used to be A (`c` coordinator / `s` subagent). It was replaced rather than removed\n * because agent identity was measured untrustworthy as a proxy for \"which tree am I in\" — a\n * worktree-isolated agent auto-reaped at a turn boundary silently resumes on the primary clone. A\n * version read off the PATH being acted on cannot lie in that way.\n */\nexport type L1VersionSync = 'y' | 'n' | '-';\n\n/** What L1 does with a row. The labels are the doc's own action codebook (see GUARD_MATRIX.md). */\nexport type L1ActionKind = 'exempt' | 'down' | 'block';\n\n/**\n * WHICH structural block a blocking row dispatches to. This is the field that makes the array\n * load-bearing rather than decorative: runner.l1LocationBlock looks the row up and switches on it,\n * so deleting a row from the array removes the block.\n */\nexport type L1BlockId = 'trinary-version-skew' | 'force-to-root' | 'missing-directory';\n\n/**\n * The row number for L1's PRE-STAGE — `misplacedCdBlock`, which decides from command TEXT before a\n * tree has been resolved, and therefore cannot be classified over the five dimensions rows 1-6 use\n * (asking L1_ROWS to classify it would need the very resolution its answer determines).\n *\n * ZERO rather than a seventh row, deliberately. It has to appear in the table — an L1 block the\n * generated doc did not describe is precisely the drift the table exists to prevent, and it was\n * carrying a `KNOWN GAP` comment saying so. But numbering it 7 would assert it sits in the same\n * first-match scan as the others, which is the one thing that is not true about it. Row 0 says\n * \"decided before the scan\" in the number itself. `renderL1Doc()` PRINTS this row above the six, so\n * `row=0` in the L1 log joins to a line the reader can actually find.\n */\nexport const L1_PRESTAGE_ROW = '0';\n\n/**\n * One point in the five-dimensional space L1 classifies over. Data-only → a class, per CLAUDE.md.\n *\n * The dimensions are exactly the doc's legend: K (tree kind of the resolved target), V (webpieces versions in sync or\n * subagent), R (provably read-only inspection), G (invokes git/gh), P (root or subdirectory).\n */\nexport class L1Classification {\n // eslint-disable-next-line @typescript-eslint/max-params -- five dimensions is the matrix's shape\n constructor(\n readonly kind: L1Kind,\n readonly versionsSkewed: boolean,\n readonly readOnly: boolean,\n readonly git: boolean,\n readonly atRoot: boolean,\n ) {}\n\n /**\n * The classification the RUNNER enforces on, built from the resolved tree and the caller.\n *\n * `'outside'` maps to `p`, and that is not a typo. TreeKind `'outside'` is produced by\n * effective-tree.ts (git has no answer for the directory) and consumed NOWHERE, so a command in no git repo is\n * judged against the governed repo exactly as if it stood in it. Row 2 (`o` → L2) describes what\n * SHOULD happen and is deliberately unreachable from here until the \"Not done\" fix in\n * guards/L1-location.md lands — exempting `o` alone opens a `cd /tmp &&` bypass of every L2 guard,\n * so the two ship together or neither does. Mapping it to `p` here is what preserves today's\n * behaviour (a `git` command from /tmp is still force-to-root blocked); it is not an endorsement.\n */\n // eslint-disable-next-line @typescript-eslint/max-params -- mirrors the constructor it delegates to\n // webpieces-disable no-function-outside-class -- a named constructor for this data class, not a service: it takes the runner's TreeKind and returns the same class, so there is nothing to inject\n static forEnforcement(\n treeKind: TreeKind,\n versionsSkewed: boolean,\n readOnly: boolean,\n git: boolean,\n atRoot: boolean,\n ): L1Classification {\n const kind: L1Kind = treeKind === 'foreign' ? 'f'\n : treeKind === 'missing' ? 'm'\n : treeKind === 'worktree' ? 'w' : 'p';\n return new L1Classification(kind, versionsSkewed, readOnly, git, atRoot);\n }\n}\n\n/** The `act` cell of a row: the doc's literal label, plus the machine-readable kind behind it. */\nexport class L1Action {\n constructor(readonly label: string, readonly kind: L1ActionKind) {}\n}\n\nexport const ACT_EXEMPT = new L1Action('2 exempt', 'exempt');\nexport const ACT_DOWN = new L1Action('→ L2', 'down');\nexport const ACT_BLOCK = new L1Action('4 block', 'block');\n\n/**\n * The CURE a blocking row prescribes.\n *\n * `runnable` is the axis that matters to the tests: a cure that is a command must, once applied,\n * actually stop the row from matching (cure reachability). Row 3's cure is an INSTRUCTION — \"spawn a\n * subagent bound to the worktree\" — which no allowlist can accept and no reclassification can model,\n * so it declares `runnable: false` and is asserted only on the deny text.\n */\nexport class L1Cure {\n constructor(\n /** How the doc's `why` column spells it. */\n readonly summary: string,\n /** A substring that MUST appear in the deny text the guard emits for this row. */\n readonly denyMention: string,\n readonly runnable: boolean,\n ) {}\n}\n\n/**\n * One row of the \"L1 use cases\" table: what you SEE, the state it puts you in, the verdict, the fix.\n *\n * The four text fields are rendered VERBATIM into the doc. `classification` is the same case expressed\n * in the matrix's own vocabulary so the tests can run it through the matcher — it is test/enforcement\n * data, never rendered, which is why a use case that exercises the FILTER or the L0 allowlist (neither\n * of which is a row) can carry `null` there.\n */\nexport class L1UseCase {\n // eslint-disable-next-line @typescript-eslint/max-params -- four verbatim doc cells plus the classification behind them\n constructor(\n readonly num: number,\n readonly symptom: string,\n readonly state: string,\n readonly verdict: string,\n readonly fix: string,\n readonly classification: L1Classification | null = null,\n ) {}\n}\n\n/** One row of L1's decision table. Data-only → a class, per CLAUDE.md. */\nexport class L1Row {\n // eslint-disable-next-line @typescript-eslint/max-params -- five dimension cells plus act/why/cure/blockId/useCases\n constructor(\n readonly num: number,\n readonly k: L1KindMatch,\n readonly a: L1VersionSync,\n readonly r: L1Flag,\n readonly g: L1Flag,\n readonly p: 'root' | 'sub' | '-',\n readonly action: L1Action,\n /** The `why` cell, verbatim. */\n readonly why: string,\n readonly cure: L1Cure | null,\n readonly blockId: L1BlockId | null,\n readonly useCases: readonly L1UseCase[],\n ) {}\n\n matches(c: L1Classification): boolean {\n if (!this.kindMatches(c.kind)) return false;\n if (this.a !== '-' && (this.a === 'n') !== c.versionsSkewed) return false;\n if (!flagMatches(this.r, c.readOnly)) return false;\n if (!flagMatches(this.g, c.git)) return false;\n return this.p === '-' || this.p === (c.atRoot ? 'root' : 'sub');\n }\n\n private kindMatches(kind: L1Kind): boolean {\n if (this.k === '-') return true;\n if (this.k === 'pw') return kind === 'p' || kind === 'w';\n return this.k === kind;\n }\n}\n\n// R and G are one boolean each behind a `y`/`n`/`-` cell, so one helper answers for both. (A is the\n// same shape but spelled `c`/`s`, and is matched inline above so the row literals read like the doc.)\n// webpieces-disable no-function-outside-class -- pure predicate for L1Row.matches above, in this data module\nfunction flagMatches(cell: L1Flag, value: boolean): boolean {\n if (cell === '-') return true;\n return (cell === 'y') === value;\n}\n\n/**\n * THE seven L1 rows, in first-match-wins order.\n *\n * Rows 3, 5 and 7 are the structural blocks and they run as ONE step (runner.l1LocationBlock) so they\n * can never be reordered by accident. Every other row is a hand-down or an exemption, i.e. \"L1 has no\n * objection\" — which is why only those three carry a blockId.\n *\n * Row 7 (`m`, the vanished directory) sits LAST only because row numbers are stable across releases —\n * they are printed in the doc and logged as `row=`, so renumbering rows 1-6 to slot it in front would\n * silently invalidate every existing reference. Position costs nothing here: `m` is matched by no other\n * row, so first-match reaches it wherever it sits.\n */\nexport const L1_ROWS: readonly L1Row[] = [\n new L1Row(1, 'f', '-', '-', '-', '-', ACT_EXEMPT, 'different git repo — hands off', null, null, [\n new L1UseCase(1,\n '`cd repositories/vendored && git commit` goes through untouched',\n '`f` / `y` / - — row 1',\n 'ALLOW_EXEMPT',\n 'none needed — jurisdiction is judged on the RESOLVED target, after the `cd`; a different git repo is hands-off',\n new L1Classification('f', false, false, true, false)),\n ]),\n new L1Row(2, 'o', '-', '-', '-', '-', ACT_DOWN, 'see \"Not done\" below', null, null, []),\n // ROW 3 IS RETIRED — it was coordinator-in-worktree, deleted with CoordinatorWorktreeGuard when the\n // guard hooks went ABSOLUTE (one governor, so the filesystem/governance split it policed became\n // unconstructible). The NUMBER is never reused: row numbers are identity here — they are printed in\n // denies, logged as `row=`, and cited in guards/L1-location.md — so renumbering would silently\n // re-point every historical reference. Its replacement is row 8.\n new L1Row(8, 'w', 'n', 'n', '-', '-', ACT_BLOCK,\n 'this worktree pins a DIFFERENT @webpieces than the main tree that governs it',\n new L1Cure('align the pins (same git hash -> same tracked pin -> install in each tree), work in the main tree, or use a separate clone',\n '@webpieces version SKEW', false),\n 'trinary-version-skew', [\n new L1UseCase(12,\n 'a worktree on an older branch pins `0.4.612` while the main tree runs `0.4.616`, and `cd <wt> && pnpm build` is blocked',\n '`w` / `n` / `n` — row 8',\n 'BLOCK_AI_CURE',\n 'Option 1 (preferred): `git pull` BOTH trees onto the same main, then `pnpm install` in each tree that has a node_modules — the pin is tracked, so the same commit gives both trees the same version<br>Option 2: do the work in the main tree, which this guard never blocks<br>Option 3: if the tree genuinely needs a DIFFERENT version, use a separate CLONE — a clone gets its own governance. That is the answer to \"I need a different version\", never to \"I need to install here\": a worktree MAY have its own node_modules (nx, vitest and the eslint plugin all load from it), it just may not hold a different @webpieces version<br>Do NOT: lower the MAIN tree\\'s pin to match — that downgrades every tree, including this session\\'s own governor',\n new L1Classification('w', true, false, false, false)),\n new L1UseCase(16,\n 'a SUBAGENT hits the same block inside `.claude/worktrees/agent-XXXX`',\n '`w` / `n` / `n` — row 8; in-repo placement is still `w`',\n 'BLOCK_AI_CURE',\n 'A subagent CANNOT fix this alone — the main tree is outside its tree, and a worktree-isolated agent may not even still be in the tree it was launched in (measured: auto-reaped at a turn boundary, resumed on the primary). Report to the coordinator: \"my worktree is on X, the main tree is on Y — one of us must move\"<br>Do NOT: expect exemption because it sits under the repo — K is git\\'s `--git-common-dir` answer, not a path test',\n new L1Classification('w', true, false, false, false)),\n ]),\n new L1Row(4, 'pw', '-', '-', 'n', '-', ACT_DOWN, 'force-to-root has no jurisdiction', null, null, [\n new L1UseCase(5,\n '`ls` from `packages/http/` runs normally',\n '`pw` / `n` / - — row 4',\n 'ALLOW (handed to L2)',\n 'none — force-to-root has no jurisdiction over non-git commands',\n new L1Classification('p', false, true, false, false)),\n new L1UseCase(6,\n '`pnpm test` from `packages/http/` runs normally',\n '`pw` / `n` / - — row 4',\n 'ALLOW (handed to L2)',\n 'none — deliberately untouched, so package-local test runs stay natural',\n new L1Classification('p', false, false, false, false)),\n new L1UseCase(10,\n '`echo \"cd sub && git push\"` passes',\n '`pw` / `n` / `root` — row 4',\n 'ALLOW (handed to L2)',\n 'none — the `cd` is inside quotes, so `ShellSegmentScan` never treats it as a scope escape',\n new L1Classification('p', false, false, false, true)),\n new L1UseCase(13,\n 'the same command from a **subagent** runs normally',\n '`w` / `y` — row 8 does not match',\n 'ALLOW (handed to L2)',\n 'none — a subagent pinned to a worktree is the correct pattern',\n new L1Classification('w', false, false, false, false)),\n new L1UseCase(14,\n 'inspection inside a SKEWED worktree still runs — `cd <worktree> && ls`/`cat`/`grep`',\n '`w` / `n` / `y` — row 8 does not match',\n 'ALLOW (handed to L2)',\n 'none — inspection is always open; so are the `Read` tool, `git -C <dir INSIDE this tree> …` and `git show <branch>:<file>`, none of which move you. `git -C <ANOTHER tree>` is a different matter: the harness refuses cross-tree git to a subagent, so it is never the cure for a skew — tell the MAIN agent instead',\n new L1Classification('w', true, true, false, false)),\n ]),\n new L1Row(5, 'pw', '-', '-', 'y', 'sub', ACT_BLOCK, '`cd <root> && <original>`',\n new L1Cure('`cd <root> && <original>`', 'Run git/gh commands from the repo root', true),\n 'force-to-root', [\n new L1UseCase(7,\n '`git status` from `packages/http/` is blocked',\n '`pw` / `y` / `sub` — row 5',\n 'BLOCK_AI_CURE',\n 'Option 1 (preferred): `cd <root> && git status`',\n new L1Classification('p', false, false, true, false)),\n new L1UseCase(8,\n '`cd packages/http && git status` **typed from the root** is blocked',\n '`pw` / `y` / `sub` — row 5',\n 'BLOCK_AI_CURE',\n 'Option 1 (preferred): `cd <root> && git status`<br>Do NOT: assume it is allowed because you started at the root — the predicate is `effectiveCwd === root`, i.e. the DESTINATION',\n new L1Classification('p', false, false, true, false)),\n new L1UseCase(11,\n '`cd <subdir> && git push` blocked with the force-to-root message, NOT the gated-flow one',\n '`pw` / `y` / `sub` — row 5; force-to-root runs first',\n 'BLOCK_AI_CURE',\n 'Option 1 (preferred): `cd <root> && git push`, which then gets the push guard\\'s real answer ← costs one extra turn by design; still blocked',\n new L1Classification('p', false, false, true, false)),\n new L1UseCase(17,\n 'the printed cure REPLACES your `cd`, it does not stack in front of it',\n '`pw` / `y` / `sub` — row 5, on the cure itself',\n 'BLOCK_AI_CURE',\n 'Option 1 (preferred): run the printed line VERBATIM — `cd <root> && <the work>`, with your own leading `cd` dropped<br>Do NOT: paste `cd <root> && cd <subdir> && <work>`; `effectiveCwd` resolves the leading `cd`s left to right, so that lands in `<subdir>` again and re-fires this exact block',\n new L1Classification('p', false, false, true, false)),\n ]),\n new L1Row(6, 'pw', '-', '-', 'y', 'root', ACT_DOWN, '', null, null, [\n new L1UseCase(9,\n '`cd <root> && git status` passes from anywhere',\n '`pw` / `y` / `root` — row 6',\n 'ALLOW (handed to L2)',\n 'none — this IS the prescribed cure',\n new L1Classification('p', false, false, true, true)),\n ]),\n new L1Row(7, 'm', '-', '-', '-', '-', ACT_BLOCK, 'the directory is GONE — nothing can run there',\n new L1Cure('`cd <root> && <the work>`, never back through the dead path',\n 'no longer exists', true),\n 'missing-directory', [\n new L1UseCase(18,\n 'every command from a worktree another agent REAPED mid-session is blocked',\n '`m` — row 7',\n 'BLOCK_AI_CURE',\n 'Option 1 (preferred): run the printed `cd <root> && <the work>` line — it does NOT route back through the dead path<br>Do NOT: re-`cd` into the worktree, or `git worktree add` it back expecting your uncommitted work; that work is gone',\n new L1Classification('m', false, false, true, false)),\n new L1UseCase(19,\n 'the same block for a NON-git command there — `m` does not care about G',\n '`m` — row 7; K alone decides it',\n 'BLOCK_AI_CURE',\n 'Option 1 (preferred): the same printed line. A vanished cwd is not a git question — nothing at all can run in a directory that does not exist',\n new L1Classification('m', false, false, false, false)),\n ]),\n];\n\n/**\n * The use cases that exercise something that is NOT a row: the excludePaths FILTER (2, 3, 4, 20) and the\n * L0 allowlist that runs ahead of L1 (15).\n *\n * They are use cases of L1 all the same — \"exempt\" is what emerges when the filter empties the rule\n * list, and case 15 is the invariant that a cure stays reachable from every tree — so they stay in the\n * doc's one numbered table. They carry no classification because no row classifies them.\n */\nexport const L1_UNROWED_USE_CASES: readonly L1UseCase[] = [\n new L1UseCase(2,\n 'Edit `repositories/vendored/foo.ts` allowed even on stale main',\n 'filter — the path is in `excludePaths`',\n 'ALLOW_EXEMPT',\n 'none needed'),\n new L1UseCase(3,\n 'Edit `packages/http/foo.ts` blocked on stale main',\n 'filter keeps the rules → L2 fires',\n 'BLOCK (at L2)',\n 'that is L2\\'s write-on-main verdict, not L1\\'s — follow the L2 message'),\n new L1UseCase(4,\n 'Edit `packages/http/foo.ts` judged even though the shell is in `/tmp`',\n 'filter, on the TARGET path',\n '→ L2',\n 'none — for file tools the cwd is irrelevant; do NOT `cd` anywhere to \"fix\" it'),\n new L1UseCase(20,\n 'Write `.webpieces/worktrees/agent-*/pr-review/…/review-*.json` allowed on main, with `excludePaths` empty',\n 'filter — `.webpieces/` is HARD-CODED exempt (`isWebpiecesStateDir`), ahead of the config list',\n 'ALLOW_EXEMPT',\n 'none needed — the dir is gitignored, so no config can put it back under governance'),\n new L1UseCase(15,\n '`cd <worktree> && pnpm install` still runs while row 8 is live — it is the CURE',\n 'L0 allowlist, ahead of L1',\n 'ALLOW',\n 'none — a cure must stay reachable from every tree'),\n];\n\n/** Every use case, in the doc's numbering — the order the table is rendered and read in. */\n// webpieces-disable no-function-outside-class -- pure accessor over the two arrays above, beside them in this data module\nexport function allL1UseCases(): readonly L1UseCase[] {\n const all = [...L1_ROWS.flatMap((row: L1Row): readonly L1UseCase[] => row.useCases), ...L1_UNROWED_USE_CASES];\n return all.sort((a: L1UseCase, b: L1UseCase): number => a.num - b.num);\n}\n\n/**\n * FIRST MATCH WINS — the one lookup the guard and the tests share.\n *\n * Never null: rows 1, 2 and 4/5/6 between them cover every kind, and rows 4/5/6 partition G × P, so a\n * classification that matched nothing would be a hole in the matrix. The totality test asserts exactly\n * that, which is why this returns L1Row rather than L1Row | null.\n */\n// webpieces-disable no-function-outside-class -- the matcher over L1_ROWS, beside the array it reads\nexport function firstMatchingL1Row(c: L1Classification): L1Row {\n const row = L1_ROWS.find((r: L1Row): boolean => r.matches(c));\n if (row === undefined) throw new Error(`L1 matrix has a hole: no row matches ${JSON.stringify(c)}`);\n return row;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"l1-rows.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/core/l1-rows.ts"],"names":[],"mappings":";;;AAgXA,sCAGC;AAUD,gDAIC;AA5UD;;;;;;;;;;;GAWG;AACU,QAAA,eAAe,GAAG,GAAG,CAAC;AAEnC;;;;;GAKG;AACH,MAAa,gBAAgB;IAGZ;IACA;IACA;IACA;IACA;IANb,kGAAkG;IAClG,YACa,IAAY,EACZ,cAAuB,EACvB,QAAiB,EACjB,GAAY,EACZ,MAAe;QAJf,SAAI,GAAJ,IAAI,CAAQ;QACZ,mBAAc,GAAd,cAAc,CAAS;QACvB,aAAQ,GAAR,QAAQ,CAAS;QACjB,QAAG,GAAH,GAAG,CAAS;QACZ,WAAM,GAAN,MAAM,CAAS;IACzB,CAAC;IAEJ;;;;;;;;;;OAUG;IACH,oGAAoG;IACpG,kMAAkM;IAClM,MAAM,CAAC,cAAc,CACjB,QAAkB,EAClB,cAAuB,EACvB,QAAiB,EACjB,GAAY,EACZ,MAAe;QAEf,MAAM,IAAI,GAAW,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nC,eAAe,EACf,wEAAwE,CAAC;IAC7E,IAAI,SAAS,CAAC,CAAC,EACX,uEAAuE,EACvE,4BAA4B,EAC5B,MAAM,EACN,+EAA+E,CAAC;IACpF,IAAI,SAAS,CAAC,EAAE,EACZ,2GAA2G,EAC3G,+FAA+F,EAC/F,cAAc,EACd,oFAAoF,CAAC;IACzF,IAAI,SAAS,CAAC,EAAE,EACZ,iFAAiF,EACjF,2BAA2B,EAC3B,OAAO,EACP,mDAAmD,CAAC;CAC3D,CAAC;AAEF,4FAA4F;AAC5F,0HAA0H;AAC1H,SAAgB,aAAa;IACzB,MAAM,GAAG,GAAG,CAAC,GAAG,eAAO,CAAC,OAAO,CAAC,CAAC,GAAU,EAAwB,EAAE,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,GAAG,4BAAoB,CAAC,CAAC;IAC9G,OAAO,GAAG,CAAC,IAAI,CAAC,CAAC,CAAY,EAAE,CAAY,EAAU,EAAE,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;AAC3E,CAAC;AAED;;;;;;GAMG;AACH,qGAAqG;AACrG,SAAgB,kBAAkB,CAAC,CAAmB;IAClD,MAAM,GAAG,GAAG,eAAO,CAAC,IAAI,CAAC,CAAC,CAAQ,EAAW,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;IAC9D,IAAI,GAAG,KAAK,SAAS;QAAE,MAAM,IAAI,KAAK,CAAC,wCAAwC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IACpG,OAAO,GAAG,CAAC;AACf,CAAC","sourcesContent":["import type { TreeKind } from './effective-tree';\n\n// ---------------------------------------------------------------------------\n// L1 — the LOCATION layer, as data.\n//\n// L1 answers four questions: do we govern this call at all, does the directory still EXIST, is the\n// WRONG AGENT standing here, and is the agent stranded away from the root? Drawn as a decision matrix\n// that is SEVEN ordered rows over five dimensions (K/A/R/G/P), first match wins.\n//\n// This module holds those rows, and l1-doc.ts renders them into guards/L1-location.md — the doc a human\n// reads on GitHub. A unit test locks that file byte-identical to the renderer, and the guard itself\n// CONSULTS L1_ROWS to decide which structural block fires (see runner.l1LocationBlock). Doc and code\n// come from the SAME array, so they cannot drift.\n//\n// This module is deliberately import-free at runtime (only a type-only import above), so\n// `pnpm guards:generate` can load it without the package's transitive dependencies.\n// ---------------------------------------------------------------------------\n\n/**\n * The K dimension as a CLASSIFICATION carries — one concrete tree, never the `pw` union.\n *\n * `p` and `w` are the same PROJECT and every rule-scoped guard treats them alike; the doc writes the\n * pair as `pw` in the row's MATCHER (below), which is a different vocabulary on purpose.\n */\nexport type L1Kind = 'f' | 'm' | 'o' | 'p' | 'w';\n\n/** The K value a ROW matches on. `pw` matches both `p` and `w`; `-` is the wildcard. */\nexport type L1KindMatch = 'f' | 'm' | 'o' | 'w' | 'pw' | '-';\n\n/** R and G are yes/no, written `y`/`n` in the doc, with `-` for \"does not matter\". */\nexport type L1Flag = 'y' | 'n' | '-';\n\n/**\n * V is the same one boolean wearing the doc's own letters: `n` the webpieces versions do NOT agree\n * between this worktree and the main tree, `y` they do.\n *\n * This dimension used to be A (`c` coordinator / `s` subagent). It was replaced rather than removed\n * because agent identity was measured untrustworthy as a proxy for \"which tree am I in\" — a\n * worktree-isolated agent auto-reaped at a turn boundary silently resumes on the primary clone. A\n * version read off the PATH being acted on cannot lie in that way.\n */\nexport type L1VersionSync = 'y' | 'n' | '-';\n\n/** What L1 does with a row. The labels are the doc's own action codebook (see GUARD_MATRIX.md). */\nexport type L1ActionKind = 'exempt' | 'down' | 'block';\n\n/**\n * WHICH structural block a blocking row dispatches to. This is the field that makes the array\n * load-bearing rather than decorative: runner.l1LocationBlock looks the row up and switches on it,\n * so deleting a row from the array removes the block.\n */\nexport type L1BlockId = 'trinary-version-skew' | 'force-to-root' | 'missing-directory';\n\n/**\n * The row number for L1's PRE-STAGE — `misplacedCdBlock`, which decides from command TEXT before a\n * tree has been resolved, and therefore cannot be classified over the five dimensions rows 1-6 use\n * (asking L1_ROWS to classify it would need the very resolution its answer determines).\n *\n * ZERO rather than a seventh row, deliberately. It has to appear in the table — an L1 block the\n * generated doc did not describe is precisely the drift the table exists to prevent, and it was\n * carrying a `KNOWN GAP` comment saying so. But numbering it 7 would assert it sits in the same\n * first-match scan as the others, which is the one thing that is not true about it. Row 0 says\n * \"decided before the scan\" in the number itself. `renderL1Doc()` PRINTS this row above the six, so\n * `row=0` in the L1 log joins to a line the reader can actually find.\n */\nexport const L1_PRESTAGE_ROW = '0';\n\n/**\n * One point in the five-dimensional space L1 classifies over. Data-only → a class, per CLAUDE.md.\n *\n * The dimensions are exactly the doc's legend: K (tree kind of the resolved target), V (webpieces versions in sync or\n * subagent), R (provably read-only inspection), G (invokes git/gh), P (root or subdirectory).\n */\nexport class L1Classification {\n // eslint-disable-next-line @typescript-eslint/max-params -- five dimensions is the matrix's shape\n constructor(\n readonly kind: L1Kind,\n readonly versionsSkewed: boolean,\n readonly readOnly: boolean,\n readonly git: boolean,\n readonly atRoot: boolean,\n ) {}\n\n /**\n * The classification the RUNNER enforces on, built from the resolved tree and the caller.\n *\n * `'outside'` maps to `p`, and that is not a typo. TreeKind `'outside'` is produced by\n * effective-tree.ts (git has no answer for the directory) and consumed NOWHERE, so a command in no git repo is\n * judged against the governed repo exactly as if it stood in it. Row 2 (`o` → L2) describes what\n * SHOULD happen and is deliberately unreachable from here until the \"Not done\" fix in\n * guards/L1-location.md lands — exempting `o` alone opens a `cd /tmp &&` bypass of every L2 guard,\n * so the two ship together or neither does. Mapping it to `p` here is what preserves today's\n * behaviour (a `git` command from /tmp is still force-to-root blocked); it is not an endorsement.\n */\n // eslint-disable-next-line @typescript-eslint/max-params -- mirrors the constructor it delegates to\n // webpieces-disable no-function-outside-class -- a named constructor for this data class, not a service: it takes the runner's TreeKind and returns the same class, so there is nothing to inject\n static forEnforcement(\n treeKind: TreeKind,\n versionsSkewed: boolean,\n readOnly: boolean,\n git: boolean,\n atRoot: boolean,\n ): L1Classification {\n const kind: L1Kind = treeKind === 'foreign' ? 'f'\n : treeKind === 'missing' ? 'm'\n : treeKind === 'worktree' ? 'w' : 'p';\n return new L1Classification(kind, versionsSkewed, readOnly, git, atRoot);\n }\n}\n\n/** The `act` cell of a row: the doc's literal label, plus the machine-readable kind behind it. */\nexport class L1Action {\n constructor(readonly label: string, readonly kind: L1ActionKind) {}\n}\n\nexport const ACT_EXEMPT = new L1Action('2 exempt', 'exempt');\nexport const ACT_DOWN = new L1Action('→ L2', 'down');\nexport const ACT_BLOCK = new L1Action('4 block', 'block');\n\n/**\n * The CURE a blocking row prescribes.\n *\n * `runnable` is the axis that matters to the tests: a cure that is a command must, once applied,\n * actually stop the row from matching (cure reachability). Row 3's cure is an INSTRUCTION — \"spawn a\n * subagent bound to the worktree\" — which no allowlist can accept and no reclassification can model,\n * so it declares `runnable: false` and is asserted only on the deny text.\n */\nexport class L1Cure {\n constructor(\n /** How the doc's `why` column spells it. */\n readonly summary: string,\n /** A substring that MUST appear in the deny text the guard emits for this row. */\n readonly denyMention: string,\n readonly runnable: boolean,\n ) {}\n}\n\n/**\n * One row of the \"L1 use cases\" table: what you SEE, the state it puts you in, the verdict, the fix.\n *\n * The four text fields are rendered VERBATIM into the doc. `classification` is the same case expressed\n * in the matrix's own vocabulary so the tests can run it through the matcher — it is test/enforcement\n * data, never rendered, which is why a use case that exercises the FILTER or the L0 allowlist (neither\n * of which is a row) can carry `null` there.\n */\nexport class L1UseCase {\n // eslint-disable-next-line @typescript-eslint/max-params -- four verbatim doc cells plus the classification behind them\n constructor(\n readonly num: number,\n readonly symptom: string,\n readonly state: string,\n readonly verdict: string,\n readonly fix: string,\n readonly classification: L1Classification | null = null,\n ) {}\n}\n\n/** One row of L1's decision table. Data-only → a class, per CLAUDE.md. */\nexport class L1Row {\n // eslint-disable-next-line @typescript-eslint/max-params -- five dimension cells plus act/why/cure/blockId/useCases\n constructor(\n readonly num: number,\n readonly k: L1KindMatch,\n readonly a: L1VersionSync,\n readonly r: L1Flag,\n readonly g: L1Flag,\n readonly p: 'root' | 'sub' | '-',\n readonly action: L1Action,\n /** The `why` cell, verbatim. */\n readonly why: string,\n readonly cure: L1Cure | null,\n readonly blockId: L1BlockId | null,\n readonly useCases: readonly L1UseCase[],\n ) {}\n\n matches(c: L1Classification): boolean {\n if (!this.kindMatches(c.kind)) return false;\n if (this.a !== '-' && (this.a === 'n') !== c.versionsSkewed) return false;\n if (!flagMatches(this.r, c.readOnly)) return false;\n if (!flagMatches(this.g, c.git)) return false;\n return this.p === '-' || this.p === (c.atRoot ? 'root' : 'sub');\n }\n\n private kindMatches(kind: L1Kind): boolean {\n if (this.k === '-') return true;\n if (this.k === 'pw') return kind === 'p' || kind === 'w';\n return this.k === kind;\n }\n}\n\n// R and G are one boolean each behind a `y`/`n`/`-` cell, so one helper answers for both. (A is the\n// same shape but spelled `c`/`s`, and is matched inline above so the row literals read like the doc.)\n// webpieces-disable no-function-outside-class -- pure predicate for L1Row.matches above, in this data module\nfunction flagMatches(cell: L1Flag, value: boolean): boolean {\n if (cell === '-') return true;\n return (cell === 'y') === value;\n}\n\n/**\n * THE seven L1 rows, in first-match-wins order.\n *\n * Rows 3, 5 and 7 are the structural blocks and they run as ONE step (runner.l1LocationBlock) so they\n * can never be reordered by accident. Every other row is a hand-down or an exemption, i.e. \"L1 has no\n * objection\" — which is why only those three carry a blockId.\n *\n * Row 7 (`m`, the vanished directory) sits LAST only because row numbers are stable across releases —\n * they are printed in the doc and logged as `row=`, so renumbering rows 1-6 to slot it in front would\n * silently invalidate every existing reference. Position costs nothing here: `m` is matched by no other\n * row, so first-match reaches it wherever it sits.\n */\nexport const L1_ROWS: readonly L1Row[] = [\n new L1Row(1, 'f', '-', '-', '-', '-', ACT_EXEMPT, 'different git repo — hands off', null, null, [\n new L1UseCase(1,\n '`cd repositories/vendored && git commit` goes through untouched',\n '`f` / `y` / - — row 1',\n 'ALLOW_EXEMPT',\n 'none needed — jurisdiction is judged on the RESOLVED target, after the `cd`; a different git repo is hands-off',\n new L1Classification('f', false, false, true, false)),\n ]),\n new L1Row(2, 'o', '-', '-', '-', '-', ACT_DOWN, 'see \"Not done\" below', null, null, []),\n // ROW 3 IS RETIRED — it was coordinator-in-worktree, deleted with CoordinatorWorktreeGuard when the\n // guard hooks went ABSOLUTE (one governor, so the filesystem/governance split it policed became\n // unconstructible). The NUMBER is never reused: row numbers are identity here — they are printed in\n // denies, logged as `row=`, and cited in guards/L1-location.md — so renumbering would silently\n // re-point every historical reference. Its replacement is row 8.\n new L1Row(8, 'w', 'n', 'n', '-', '-', ACT_BLOCK,\n 'this worktree pins a DIFFERENT @webpieces than the main tree that governs it',\n new L1Cure('align the pins (same git hash -> same tracked pin -> install in each tree), work in the main tree, or use a separate clone',\n '@webpieces version SKEW', false),\n 'trinary-version-skew', [\n new L1UseCase(12,\n 'a worktree on an older branch pins `0.4.612` while the main tree runs `0.4.616`, and `cd <wt> && pnpm build` is blocked',\n '`w` / `n` / `n` — row 8',\n 'BLOCK_AI_CURE',\n 'Option 1 (preferred): the MAIN tree is AHEAD, so this is YOURS and it is a one-line edit — raise THIS tree\\'s catalog pin in `pnpm-workspace.yaml` to what main already runs, then `pnpm install` here if this tree has a node_modules. That edit is on the L0 allowlist, so it is typable while the block is up, and nothing has to move in the main tree<br>Option 2: do the work in the main tree, which this guard never blocks<br>Option 3: if the tree genuinely needs a DIFFERENT version, use a separate CLONE — a clone gets its own governance. That is the answer to \"I need a different version\", never to \"I need to install here\": a worktree MAY have its own node_modules (nx, vitest and the eslint plugin all load from it), it just may not hold a different @webpieces version<br>Do NOT: lower the MAIN tree\\'s pin to match — that downgrades every tree, including this session\\'s own governor. And do NOT reach for `pnpm install` BEFORE the edit: this tree\\'s pin is the stale side, so installing first materializes the OLD release',\n new L1Classification('w', true, false, false, false)),\n new L1UseCase(16,\n 'a SUBAGENT hits the same block inside `.claude/worktrees/agent-XXXX`',\n '`w` / `n` / `n` — row 8; in-repo placement is still `w`',\n 'BLOCK_AI_CURE',\n 'READ THE DIRECTION FIRST — the deny prints it. If the MAIN tree is AHEAD (the common case) a subagent fixes this ITSELF, here, by raising this tree\\'s pin to what main already runs; there is nothing to escalate and the deny prints no escalation. Only when main is BEHIND, or when this branch bumped the pin on purpose, is the subagent stuck — the main tree is outside its tree, and a worktree-isolated agent may not even still be in the tree it was launched in (measured: auto-reaped at a turn boundary, resumed on the primary). Then, and only then, forward the deny\\'s verbatim ask to the coordinator and STOP<br>Do NOT: expect exemption because it sits under the repo — K is git\\'s `--git-common-dir` answer, not a path test',\n new L1Classification('w', true, false, false, false)),\n ]),\n new L1Row(4, 'pw', '-', '-', 'n', '-', ACT_DOWN, 'force-to-root has no jurisdiction', null, null, [\n new L1UseCase(5,\n '`ls` from `packages/http/` runs normally',\n '`pw` / `n` / - — row 4',\n 'ALLOW (handed to L2)',\n 'none — force-to-root has no jurisdiction over non-git commands',\n new L1Classification('p', false, true, false, false)),\n new L1UseCase(6,\n '`pnpm test` from `packages/http/` runs normally',\n '`pw` / `n` / - — row 4',\n 'ALLOW (handed to L2)',\n 'none — deliberately untouched, so package-local test runs stay natural',\n new L1Classification('p', false, false, false, false)),\n new L1UseCase(10,\n '`echo \"cd sub && git push\"` passes',\n '`pw` / `n` / `root` — row 4',\n 'ALLOW (handed to L2)',\n 'none — the `cd` is inside quotes, so `ShellSegmentScan` never treats it as a scope escape',\n new L1Classification('p', false, false, false, true)),\n new L1UseCase(13,\n 'the same command from a **subagent** runs normally',\n '`w` / `y` — row 8 does not match',\n 'ALLOW (handed to L2)',\n 'none — a subagent pinned to a worktree is the correct pattern',\n new L1Classification('w', false, false, false, false)),\n new L1UseCase(14,\n 'inspection inside a SKEWED worktree still runs — `cd <worktree> && ls`/`cat`/`grep`',\n '`w` / `n` / `y` — row 8 does not match',\n 'ALLOW (handed to L2)',\n 'none — inspection is always open; so are the `Read` tool, `git -C <dir INSIDE this tree> …` and `git show <branch>:<file>`, none of which move you. `git -C <ANOTHER tree>` is a different matter: the harness refuses cross-tree git to a subagent, so it is never the cure for a skew — tell the MAIN agent instead',\n new L1Classification('w', true, true, false, false)),\n ]),\n new L1Row(5, 'pw', '-', '-', 'y', 'sub', ACT_BLOCK, '`cd <root> && <original>`',\n new L1Cure('`cd <root> && <original>`', 'Run git/gh commands from the repo root', true),\n 'force-to-root', [\n new L1UseCase(7,\n '`git status` from `packages/http/` is blocked',\n '`pw` / `y` / `sub` — row 5',\n 'BLOCK_AI_CURE',\n 'Option 1 (preferred): `cd <root> && git status`',\n new L1Classification('p', false, false, true, false)),\n new L1UseCase(8,\n '`cd packages/http && git status` **typed from the root** is blocked',\n '`pw` / `y` / `sub` — row 5',\n 'BLOCK_AI_CURE',\n 'Option 1 (preferred): `cd <root> && git status`<br>Do NOT: assume it is allowed because you started at the root — the predicate is `effectiveCwd === root`, i.e. the DESTINATION',\n new L1Classification('p', false, false, true, false)),\n new L1UseCase(11,\n '`cd <subdir> && git push` blocked with the force-to-root message, NOT the gated-flow one',\n '`pw` / `y` / `sub` — row 5; force-to-root runs first',\n 'BLOCK_AI_CURE',\n 'Option 1 (preferred): `cd <root> && git push`, which then gets the push guard\\'s real answer ← costs one extra turn by design; still blocked',\n new L1Classification('p', false, false, true, false)),\n new L1UseCase(17,\n 'the printed cure REPLACES your `cd`, it does not stack in front of it',\n '`pw` / `y` / `sub` — row 5, on the cure itself',\n 'BLOCK_AI_CURE',\n 'Option 1 (preferred): run the printed line VERBATIM — `cd <root> && <the work>`, with your own leading `cd` dropped<br>Do NOT: paste `cd <root> && cd <subdir> && <work>`; `effectiveCwd` resolves the leading `cd`s left to right, so that lands in `<subdir>` again and re-fires this exact block',\n new L1Classification('p', false, false, true, false)),\n ]),\n new L1Row(6, 'pw', '-', '-', 'y', 'root', ACT_DOWN, '', null, null, [\n new L1UseCase(9,\n '`cd <root> && git status` passes from anywhere',\n '`pw` / `y` / `root` — row 6',\n 'ALLOW (handed to L2)',\n 'none — this IS the prescribed cure',\n new L1Classification('p', false, false, true, true)),\n ]),\n new L1Row(7, 'm', '-', '-', '-', '-', ACT_BLOCK, 'the directory is GONE — nothing can run there',\n new L1Cure('`cd <root> && <the work>`, never back through the dead path',\n 'no longer exists', true),\n 'missing-directory', [\n new L1UseCase(18,\n 'every command from a worktree another agent REAPED mid-session is blocked',\n '`m` — row 7',\n 'BLOCK_AI_CURE',\n 'Option 1 (preferred): run the printed `cd <root> && <the work>` line — it does NOT route back through the dead path<br>Do NOT: re-`cd` into the worktree, or `git worktree add` it back expecting your uncommitted work; that work is gone',\n new L1Classification('m', false, false, true, false)),\n new L1UseCase(19,\n 'the same block for a NON-git command there — `m` does not care about G',\n '`m` — row 7; K alone decides it',\n 'BLOCK_AI_CURE',\n 'Option 1 (preferred): the same printed line. A vanished cwd is not a git question — nothing at all can run in a directory that does not exist',\n new L1Classification('m', false, false, false, false)),\n ]),\n];\n\n/**\n * The use cases that exercise something that is NOT a row: the excludePaths FILTER (2, 3, 4, 20) and the\n * L0 allowlist that runs ahead of L1 (15).\n *\n * They are use cases of L1 all the same — \"exempt\" is what emerges when the filter empties the rule\n * list, and case 15 is the invariant that a cure stays reachable from every tree — so they stay in the\n * doc's one numbered table. They carry no classification because no row classifies them.\n */\nexport const L1_UNROWED_USE_CASES: readonly L1UseCase[] = [\n new L1UseCase(2,\n 'Edit `repositories/vendored/foo.ts` allowed even on stale main',\n 'filter — the path is in `excludePaths`',\n 'ALLOW_EXEMPT',\n 'none needed'),\n new L1UseCase(3,\n 'Edit `packages/http/foo.ts` blocked on stale main',\n 'filter keeps the rules → L2 fires',\n 'BLOCK (at L2)',\n 'that is L2\\'s write-on-main verdict, not L1\\'s — follow the L2 message'),\n new L1UseCase(4,\n 'Edit `packages/http/foo.ts` judged even though the shell is in `/tmp`',\n 'filter, on the TARGET path',\n '→ L2',\n 'none — for file tools the cwd is irrelevant; do NOT `cd` anywhere to \"fix\" it'),\n new L1UseCase(20,\n 'Write `.webpieces/worktrees/agent-*/pr-review/…/review-*.json` allowed on main, with `excludePaths` empty',\n 'filter — `.webpieces/` is HARD-CODED exempt (`isWebpiecesStateDir`), ahead of the config list',\n 'ALLOW_EXEMPT',\n 'none needed — the dir is gitignored, so no config can put it back under governance'),\n new L1UseCase(15,\n '`cd <worktree> && pnpm install` still runs while row 8 is live — it is the CURE',\n 'L0 allowlist, ahead of L1',\n 'ALLOW',\n 'none — a cure must stay reachable from every tree'),\n];\n\n/** Every use case, in the doc's numbering — the order the table is rendered and read in. */\n// webpieces-disable no-function-outside-class -- pure accessor over the two arrays above, beside them in this data module\nexport function allL1UseCases(): readonly L1UseCase[] {\n const all = [...L1_ROWS.flatMap((row: L1Row): readonly L1UseCase[] => row.useCases), ...L1_UNROWED_USE_CASES];\n return all.sort((a: L1UseCase, b: L1UseCase): number => a.num - b.num);\n}\n\n/**\n * FIRST MATCH WINS — the one lookup the guard and the tests share.\n *\n * Never null: rows 1, 2 and 4/5/6 between them cover every kind, and rows 4/5/6 partition G × P, so a\n * classification that matched nothing would be a hole in the matrix. The totality test asserts exactly\n * that, which is why this returns L1Row rather than L1Row | null.\n */\n// webpieces-disable no-function-outside-class -- the matcher over L1_ROWS, beside the array it reads\nexport function firstMatchingL1Row(c: L1Classification): L1Row {\n const row = L1_ROWS.find((r: L1Row): boolean => r.matches(c));\n if (row === undefined) throw new Error(`L1 matrix has a hole: no row matches ${JSON.stringify(c)}`);\n return row;\n}\n"]}
|
package/src/core/runner.js
CHANGED
|
@@ -104,13 +104,13 @@ function runInternal(toolKind, input, cwd, mode) {
|
|
|
104
104
|
if (path.resolve(input.filePath) === path.resolve(loaded.configPath)) {
|
|
105
105
|
return null;
|
|
106
106
|
}
|
|
107
|
-
// …and the same
|
|
108
|
-
//
|
|
109
|
-
//
|
|
110
|
-
//
|
|
111
|
-
//
|
|
112
|
-
//
|
|
113
|
-
if (new rules_config_1.HomeConfigService().isHomeConfigPath(input.filePath)) {
|
|
107
|
+
// …and the same PASS for the machine-local `~/.webpieces/config.json` (a bad key there fails a `wp-*`
|
|
108
|
+
// command with an instruction to edit it, so blocking the edit would wedge the agent inside the
|
|
109
|
+
// failure) and for the two ROOT MANIFESTS a pin lives in — L1 row 8 PROMISED that edit and its cure IS
|
|
110
|
+
// it. isRootManifest, never a basename: this returns EARLY, so basename would unrule every
|
|
111
|
+
// package.json in the repo. It admits any tree's root (the config sits beside it), which is what a
|
|
112
|
+
// worktree's own cure needs — the same tree `workspaceRoot` above already names.
|
|
113
|
+
if ((0, shim_1.isRootManifest)(input.filePath) || new rules_config_1.HomeConfigService().isHomeConfigPath(input.filePath)) {
|
|
114
114
|
return null;
|
|
115
115
|
}
|
|
116
116
|
// Built-in/custom rules PLUS the client-authored match-rules (content guards). Match-rules run only
|