@webpieces/agent-workflow-rules 0.4.1004 → 0.4.1006

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.
@@ -1 +1 @@
1
- {"version":3,"file":"runner.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/core/runner.ts"],"names":[],"mappings":";;AAgEA,4CAEC;AAKD,4CAEC;AAkBD,kBAOC;AAkFD,0BAEC;AAmBD,0BA2CC;;AApPD,0DAAiG;AACjG,mDAA6B;AAE7B,0DAYiC;AAEjC,0DAA0E;AAC1E,0DAA4D;AAC5D,iDAAkD;AAClD,0DAA+E;AAC/E,0DAA2E;AAC3E,0DAAkF;AAClF,iEAAgE;AAChE,mDAAqD;AACrD,6CAAoD;AACpD,+DAA0D;AAC1D,2DAA4D;AAC5D,2DAAmF;AACnF,iDAAsJ;AACtJ,iEAA6D;AAC7D,0DAAmF;AACnF,iEAAgE;AAChE,sCAA0D;AAC1D,0DAAyD;AAEzD,0DAA8G;AAC9G,0DAA2F;AAC3F,2CAAsE;AACtE,uCAAkF;AAClF,mDAA4D;AAC5D,0DAAoK;AAEpK,8DAA0D;AAE1D,mGAAmG;AACnG,oGAAoG;AACpG,oGAAoG;AACpG,2BAA2B;AAC3B,oGAAoG;AACpG,2FAA2F;AAC3F,gGAAgG;AAChG,yFAAyF;AACzF,mKAAmK;AACnK,SAAS,YAAY,CAAC,KAAsB,EAAE,IAAc,EAAE,QAA0B;IACpF,IAAI,IAAI,KAAK,KAAK;QAAE,OAAO,KAAK,CAAC;IACjC,IAAI,IAAI,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC,MAAM,CAAC,CAAC,CAAO,EAAW,EAAE,CAAC,IAAA,0BAAW,EAAC,CAAC,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC,CAAC;IACrG,OAAO,KAAK,CAAC,MAAM,CAAC,CAAC,CAAO,EAAW,EAAE,CAAC,CAAC,IAAA,0BAAW,EAAC,CAA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,EAAC,IAAI,CAAC,IAAI,CAAC,EACvB,eAAe,EACf,kBAAkB,EAClB,GAAG,EACH,4BAAa,EACb,gCAAiB,CACpB,CACJ,CAAC;IACF,MAAM,MAAM,GACR,IAAI,6CAAsB,CAAC,aAAa,EAAE,IAAI,CAAC,YAAY,CAAC,CAAC,MAAM,CAC/D,OAAO,EACP,MAAM,CAAC,YAAY,CACtB;QACD,IAAA,2BAAY,EAAC,YAAY,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,2BAAY,CAAC;QACzD,eAAe,CAAC,MAAM,EAAE,MAAM,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;IACvD,OAAO,IAAI,4BAAa,CAAC,MAAM,CAAC,CAAC;AACrC,CAAC;AAED,oHAAoH;AACpH,SAAS,gBAAgB,CAAC,OAAe,EAAE,IAAmB,EAAE,aAAqB;IACjF,IAAI,IAAI,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;QAC1B,IAAA,+BAAgB,EACZ,aAAa,EACb,IAAI,4BAAa,CACb,GAAG,EACH,MAAM,EACN,OAAO,EACP,IAAA,2BAAY,EAAC,aAAa,CAAC,EAC3B,cAAc,EACd,iCAAiC,EACjC,GAAG,EACH,4BAAa,EACb,IAAI,wBAAS,CAAC,IAAI,EAAE,GAAG,CAAC,CAC3B,CACJ,CAAC;QACF,OAAO,IAAI,CAAC;IAChB,CAAC;IAED,OAAO,KAAK,CAAC;AACjB,CAAC","sourcesContent":["import { runRuleCheck, runEditRules, runFileRules, runBashRules } from '@webpieces/hook-runtime';\nimport * as path from 'path';\n\nimport {\n loadAndValidate,\n LoadedConfig,\n ConfigRepairAccess,\n RulePackRegistry,\n WebpiecesRulesConfig,\n isHookGuard,\n HomeConfigService,\n RepoRootFinder,\n seedEntryForRule,\n CONFIG_FILENAME,\n renderRuleFailForAi,\n} from '@webpieces/rules-config';\n\nimport { buildContexts, buildBashContext } from '@webpieces/hook-runtime';\nimport { DeleteScopedRules } from '@webpieces/hook-runtime';\nimport { VersionSyncGuard } from './version-sync';\nimport { EffectiveTree, EffectiveTreeResolver } from '@webpieces/hook-runtime';\nimport { GovernedPath, TargetTreeResolver } from '@webpieces/hook-runtime';\nimport { bashGovernedPath, filterByExcludedPaths } from '@webpieces/hook-runtime';\nimport { ExcludedPathEscapeHint } from './excluded-path-escape';\nimport { gitFromSubdirBlock } from './force-to-root';\nimport { loadKeylessBashRules } from './load-rules';\nimport { WorkflowHookRules } from './workflow-hook-rules';\nimport { missingDirectoryBlock } from './missing-directory';\nimport { branchStateHangTimeout, maybeRefreshMainSync } from './main-sync-timeout';\nimport { logGuardDecision, logL1Decision, GuardDecision, branchForLog, MatrixRef, Verdict, MATRIX_L0_ALLOW, MATRIX_L2_UNROWED } from './decision-log';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { formatReport, READ_SUBJECT, BASH_SUBJECT } from '@webpieces/hook-runtime';\nimport { ReadOnlyInspectionScan } from './read-only-inspection';\nimport { L0_CURE_ALLOW_JS, isAllowed } from '../bin/shim';\nimport { isRootManifest } from '@webpieces/hook-runtime';\nimport { AiType } from '@webpieces/hook-runtime';\nimport { L0_FAULT_CONFIG_MISSING, L0_FAULT_CONFIG_OUT_OF_SYNC, L0_FAULT_NONE } from '@webpieces/rules-config';\nimport { CONFIG_MISSING_REPORT, CONFIG_OUT_OF_SYNC_HEADER } from '@webpieces/rules-config';\nimport { writeGuardMatrixDoc, guardMatrixPointer } from './l0-matrix';\nimport { L1Classification, firstMatchingL1Row, L1_PRESTAGE_ROW } from './l1-rows';\nimport { withLocationMatrixPointer } from './l1-matrix-doc';\nimport { ToolKind, NormalizedToolInput, BlockedResult, HookMode, Rule, Violation, RuleGroup, EditContext, FileContext, BashContext } from '@webpieces/hook-runtime';\nimport { RuleFailError } from '@webpieces/rules-config';\nimport { InformAiError } from '@webpieces/tooling-common';\n\n// Restrict loaded rules to the category this hook invocation runs. The two split hooks each pass a\n// disjoint category ('rules' = code-style, 'guards' = the hookGuards section); 'all' runs both (the\n// openclaw plugin adapter, a single before_tool_call hook). isHookGuard is the shared classifier in\n// @webpieces/rules-config.\n// isHookGuard is asked about the rule's CONFIG KEY, never its name. Since the collapse those differ\n// for every class behind a policy key — `feature-branch-guard` is a rule NAME whose key is\n// `branch-state-guard` — and asking about the name would classify all eight collapsed guards as\n// code-style rules, i.e. run them in the wrong hook and never in the guards hook at all.\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nfunction filterByMode(rules: readonly Rule[], mode: HookMode, registry: RulePackRegistry): readonly Rule[] {\n if (mode === 'all') return rules;\n if (mode === 'guards') return rules.filter((r: Rule): boolean => isHookGuard(r.configKey, registry));\n return rules.filter((r: Rule): boolean => !isHookGuard(r.configKey, registry));\n}\n\n// The cwd a command actually runs from, after its own leading `cd`/`pushd` run. Thin delegate kept\n// for the callers (and specs) that only need the directory; the full tree classification — primary\n// clone vs linked worktree vs nested clone vs outside any repo — is EffectiveTreeResolver.resolve().\n// webpieces-disable no-function-outside-class -- sibling of the module-scope runner helpers; the whole file is functions and a lone class here would break its shape\nexport function effectiveBashCwd(command: string, cwd: string): string {\n return new EffectiveTreeResolver().effectiveCwd(command, cwd);\n}\n\n// A git or gh invocation anywhere in the command (start, or after a ;/&&/|| separator or pipe).\nconst GIT_OR_GH_RE = /(?:^|[;&|]\\s*)(?:git|gh)\\b/;\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nexport function isGitOrGhCommand(command: string): boolean {\n return GIT_OR_GH_RE.test(command);\n}\n\n// Fault C (webpieces.config.json missing) — the deny text lives in ./l0-matrix beside the rest of the\n// L0 fault table, so the message and the allowlist can never prescribe different cures. `cwd` is used\n// only to drop the matrix doc where the AI can read it (the config root does not exist yet here).\n//\n// THE ALLOWLIST ESCAPE IS THE CALLER'S (moved out 2026-09-01): behind an optional `command` it could\n// not see the harness, so the gated half of the list was unreachable under C while\n// CONFIG_MISSING_REPORT promised it. See l0FaultAllows. This has one job now: build the block.\n// webpieces-disable no-function-outside-class -- sibling of the module-scope runner helpers; the whole file is functions and a lone class here would break its shape\nfunction configMissingBlock(cwd: string): BlockedResult {\n const root = new RepoRootFinder().resolveRepoRoot(cwd);\n // Stamped with its L0 letter so the block is greppable as fault C wherever it is recorded — the\n // adapter carries it to the audit line rather than re-deriving it from the report text.\n return new BlockedResult(CONFIG_MISSING_REPORT + guardMatrixPointer(writeGuardMatrixDoc(root)), L0_FAULT_CONFIG_MISSING);\n}\n\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nexport function run(\n toolKind: ToolKind,\n input: NormalizedToolInput,\n cwd: string,\n mode: HookMode = 'all',\n): BlockedResult | null {\n return runInternal(toolKind, input, cwd, mode);\n}\n\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nfunction runInternal(\n toolKind: ToolKind,\n input: NormalizedToolInput,\n cwd: string,\n mode: HookMode,\n): BlockedResult | null {\n if (\n toolKind !== 'Delete' &&\n (new ConfigRepairAccess().isRepairFile(\n new RepoRootFinder().resolveRepoRoot(cwd),\n input.filePath,\n ) ||\n isRootManifest(input.filePath) ||\n new HomeConfigService().isHomeConfigPath(input.filePath))\n )\n return null;\n const loaded = loadAndValidate(cwd);\n if (loaded.configPath === null) return configMissingBlock(cwd);\n\n const workspaceRoot = path.dirname(loaded.configPath);\n\n // Always allow edits to webpieces.config.json — it's the fix target when out of sync\n if (path.resolve(input.filePath) === path.resolve(loaded.configPath)) {\n return null;\n }\n\n // …and the same PASS for the machine-local `~/.webpieces/config.json` (a bad key there fails a `wp-*`\n // command with an instruction to edit it, so blocking the edit would wedge the agent inside the\n // failure) and for the two ROOT MANIFESTS a pin lives in — L1 row 8 PROMISED that edit and its cure IS\n // it. isRootManifest, never a basename: this returns EARLY, so basename would unrule every\n // package.json in the repo. It admits any tree's root (the config sits beside it), which is what a\n // worktree's own cure needs — the same tree `workspaceRoot` above already names.\n if (\n isRootManifest(input.filePath) ||\n new HomeConfigService().isHomeConfigPath(input.filePath)\n ) {\n return null;\n }\n\n // Built-in/custom rules PLUS the client-authored match-rules (content guards). Match-rules run only\n // in the file-edit path (they are code-style, so filterByMode keeps them out of the bash/guards path).\n const allRules = [...new WorkflowHookRules().load(loaded).rules];\n const modeRules = filterByMode(allRules, mode, loaded.ruleRegistry);\n if (modeRules.length === 0) return null;\n\n // Suppress enforcement for files under this category's excludePaths (e.g. vendored repos under\n // repositories/**). Exclusion is all-or-nothing per category, so an excluded file drops the whole\n // rule set and is fully hands-off — no violations AND no config-sync nag on those files.\n const governed = new TargetTreeResolver().governedPath(input.filePath, workspaceRoot);\n const relativePath = governed.relativePath;\n const rules = new DeleteScopedRules().narrow(\n toolKind,\n filterByExcludedPaths(modeRules, governed, loaded.excludePaths),\n );\n if (rules.length === 0) return null;\n\n const contexts = buildContexts(toolKind, input, workspaceRoot, governed);\n\n const editGroups = runEditRules(rules, contexts.editContexts);\n const fileGroups = runFileRules(rules, contexts.fileContext);\n const allGroups = [...editGroups, ...fileGroups];\n\n if (allGroups.length === 0) return null;\n\n const report = formatReport(relativePath, allGroups);\n return new BlockedResult(report);\n}\n\n// SINGLETON, deliberately: WebpiecesVersions memoizes per root, and the same two roots are asked for on\n// every Bash call. A fresh instance per call would spawn `git worktree list` and re-read two manifests\n// on the hook's blocking path each time.\nconst VERSION_SYNC = new VersionSyncGuard();\n\n// There is deliberately NO agent parameter. It existed only for CoordinatorWorktreeGuard, which asked\n// WHO was calling; that guard is gone and its replacement asks WHICH TREE the command acts on. Agent\n// identity was measured untrustworthy for that question anyway — a worktree-isolated agent auto-reaped\n// at a turn boundary silently resumes with its cwd on the primary clone — so a guard must never infer\n// a tree from who is asking.\n// webpieces-disable no-function-outside-class -- sibling of run()/runRead() in this module; the whole runner is module-scope functions and a lone class for this one entry point would break the file's shape\nexport function runBash(command: string, cwd: string, mode: HookMode, aiType: AiType): BlockedResult | null {\n return runBashInternal(command, cwd, mode, aiType);\n}\n\n// The name of the ONLY rule permitted to block a Read. Reads are the highest-blast-radius tool\n// there is, so this path is an explicit single-rule allowlist rather than the general rule loop.\nconst READ_SCOPED_GUARDS: ReadonlySet<string> = new Set(['read-stale-guard']);\n\n/**\n * The Read path. Deliberately NOT `run()`:\n *\n * - NO config-sync check. A rule present in code but missing from webpieces.config.json blocks\n * every Write/Edit/Bash by design — but applying that to Read would mean an upgrade that adds\n * any new rule instantly blocks the agent from reading the very config file it must edit to fix\n * it. Reads must never carry that failure mode.\n * - NO general rule loop. Only READ_SCOPED_GUARDS run, so no code-style rule can ever see a Read.\n * - Fails OPEN everywhere, including on a thrown rule (the caller catches and allows).\n *\n * Returns null (allow) unless the one guard fires.\n */\n// webpieces-disable no-function-outside-class -- sibling of run()/runBash() in this module; the whole runner is module-scope functions and a lone class for this one entry point would break the file's shape\nexport function runRead(\n filePath: string,\n cwd: string,\n mode: HookMode = 'all',\n): BlockedResult | null {\n // Code-style mode has nothing to say about a read.\n if (mode === 'rules') return null;\n\n let loaded: LoadedConfig;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- broken configuration must remain readable without enabling any mutating policy\n try {\n loaded = loadAndValidate(cwd);\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n } catch (err: unknown) {\n const error = toError(err);\n if (error instanceof InformAiError) return null;\n throw error;\n }\n // No config → nothing to enforce. Unlike the edit path we do NOT block: an unconfigured repo\n // must still be readable.\n if (loaded.configPath === null) return null;\n\n const workspaceRoot = path.dirname(loaded.configPath);\n\n // Same git-repo-boundary governance as bash, through the SAME resolver: a read inside a different\n // clone is out of scope. (No command to parse here, so the shell cwd IS the effective cwd.)\n if (new EffectiveTreeResolver().resolve('', cwd, workspaceRoot).kind === 'foreign') return null;\n\n const governed = new TargetTreeResolver().governedPath(filePath, workspaceRoot);\n const relativePath = governed.relativePath;\n const all = new WorkflowHookRules().load(loaded).rules;\n const rules = filterByExcludedPaths(\n all.filter((r: Rule): boolean => READ_SCOPED_GUARDS.has(r.name)),\n governed,\n loaded.excludePaths,\n );\n if (rules.length === 0) return null;\n\n const ctx = new FileContext('Read', filePath, relativePath, workspaceRoot, null, 0, 0, 0, 0);\n const groups = runFileRules(rules, ctx);\n if (groups.length === 0) return null;\n\n return new BlockedResult(formatReport(relativePath, groups, READ_SUBJECT));\n}\n\n// L0 cure bypass — every command on THE L0 allowlist passes here, ahead of any config load. A\n// webpieces.config.json that is ahead of the installed validator (new rule tokens the published\n// binary doesn't know yet) makes loadAndValidate() throw and would deny `pnpm install` — the very\n// command that updates the validator (deadlock).\n//\n// This used to test INSTALLER_ALLOW_JS alone, which made the config faults (C = config missing,\n// Y = config out of sync) accept a bare `pnpm install` while denying `rm -rf node_modules && pnpm\n// install` — the one cure that works when node_modules is CORRUPT rather than merely stale. Same\n// intent, opposite verdict, for no reason anyone recorded. Each alternative is still anchored at both\n// ends, so `pnpm install && rm -rf /` still falls to the guards.\n//\n// It tests the CURE subset (L0_CURE_ALLOW_JS), not the whole list, and the distinction matters here\n// and nowhere else: this call site runs BEFORE any fault has been established, so whatever it accepts\n// is waved past the L1 guards on a perfectly healthy repo too. A repair command has to be waved past —\n// it runs before the config can be loaded at all. Read-only ORIENTATION does not: it fixes nothing, and\n// letting `git status` through here would delete force-to-root as a side effect of adding `pwd`. Under\n// an actual fault, l0FaultAllows() below consults the WHOLE list.\n// webpieces-disable no-function-outside-class -- sibling of the module-scope runner helpers; the whole file is functions and a lone class here would break its shape\nfunction isL0CureCommand(command: string): boolean {\n return L0_CURE_ALLOW_JS.test(command.trim());\n}\n\n// The FULL L0 list, asked only where this file has actually detected an L0 fault (C = config missing,\n// Y = config out of sync). D/X/U/K are decided in the shim, which greps the same union.\n// IT ASKS `isAllowed()`, not a regex: that is the ONE question both halves of L0 ask, and the only\n// place harness-gated entries are consulted. Testing `L0_ALLOW_JS` directly (which is what this did)\n// dropped the Codex read under C and Y while D/X/U/K honoured it — a per-fault carve-out again.\n// webpieces-disable no-function-outside-class -- sibling of the module-scope runner helpers; the whole file is functions and a lone class here would break its shape\nfunction l0FaultAllows(command: string, aiType: AiType): boolean {\n return isAllowed('Bash', command.trim(), '', aiType) !== null;\n}\n\n// The L0 cure bypass's audit line. Anchored at the repo root that owns `.webpieces` — RepoRootFinder\n// (config-walk-up first, then git toplevel) is the authority for that, and it is correct in a linked\n// worktree because each worktree checks out its own webpieces.config.json. This runs BEFORE\n// loadAndValidate, which is why it resolves the root itself rather than using workspaceRoot.\n// webpieces-disable no-function-outside-class -- sibling of the module-scope runner helpers; the whole file is functions and a lone class here would break its shape\nfunction logL0CureBypass(command: string, cwd: string): void {\n const root = new RepoRootFinder().resolveRepoRoot(cwd);\n logGuardDecision(root, new GuardDecision('-', 'Bash', command, branchForLog(root), 'ALLOW', 'L0 cure bypass (always allowed)', '-', L0_FAULT_NONE, MATRIX_L0_ALLOW));\n}\n\n/**\n * Load the config for the bash path — but do NOT let an unloadable config trap the tools needed to\n * repair it.\n *\n * loadAndValidate throws an InformAiError when webpieces.config.json is unparseable (a real syntax\n * error, or leftover `<<<<<<< HEAD` markers mid-merge) or fails validation. That throw propagates to\n * the hook adapter, which fails CLOSED and denies the command — correct for work, since a config that\n * did not load means no guards ran. But it denied `cat`/`grep`/`sed -n` on webpieces.config.json too,\n * i.e. it blocked the only way to see the problem it was reporting. Observed live, twice.\n *\n * So: on a load failure, a provably-inert INSPECTION command is allowed through (returns null, \"no\n * block\"), matching the escape hatch every other layer already grants this file. Everything else —\n * every write, every git/gh command, every build — still hits the same hard failure as before. The\n * bypass cannot be widened by accident; see ReadOnlyInspectionScan for how narrow \"inert\" is.\n *\n * Returns the loaded config, or null meaning \"allow this command without guards\".\n */\n// webpieces-disable no-function-outside-class -- sibling of the module-scope runner helpers; the whole file is functions and a lone class here would break its shape\nfunction loadConfigOrAllowInspection(command: string, cwd: string): LoadedConfig | null {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- rethrown unchanged unless the command is provably inert\n try {\n return loadAndValidate(cwd);\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n } catch (err: unknown) {\n const error = toError(err);\n if (error instanceof InformAiError && new ReadOnlyInspectionScan().isReadOnlyInspection(command)) {\n return null;\n }\n throw error;\n }\n}\n\n// Version skew: this worktree pins a different @webpieces than the MAIN tree that governs it. The guard\n// hooks are absolute, so the main tree's binary judges every tree — which is fine until the two trees\n// disagree about which release that should be. L1 row 8; guards/L1-location.md carries the table.\n// webpieces-disable no-function-outside-class -- sibling of the other module-scope runner helpers; the whole file is functions and a lone class here would break its shape\nfunction versionSkewBlock(command: string, tree: EffectiveTree, aiType: AiType): BlockedResult | null {\n const report = VERSION_SYNC.block(command, tree, aiType);\n return report === null ? null : new BlockedResult(report);\n}\n\n// Where the command lands in L1's five dimensions (K/A/R/G/P). The ONE place the runner's view of the\n// world is translated into the matrix's vocabulary — see L1Classification.forEnforcement for why\n// TreeKind 'outside' currently classifies as `p`.\n// webpieces-disable no-function-outside-class -- sibling of the other module-scope runner helpers; the whole file is functions and a lone class here would break its shape\nfunction l1Classify(command: string, tree: EffectiveTree): L1Classification {\n return L1Classification.forEnforcement(\n tree.kind,\n VERSION_SYNC.skewed(tree),\n new ReadOnlyInspectionScan().isReadOnlyInspection(command),\n isGitOrGhCommand(command),\n path.resolve(tree.effectiveCwd) === path.resolve(tree.root),\n );\n}\n\n// The structural L1 blocks, in order: the misplaced-`cd` PRE-STAGE, then version skew (row 8), then\n// force-to-root (row 5). None is a configurable rule — they are decided from the command text, the\n// resolved tree and the caller, so they run as one step here rather than as three near-identical\n// stanzas in runBashInternal.\n//\n// For the two TREE-BASED blocks the ORDER and the CHOICE are not written here: they come from L1_ROWS\n// (l1-rows.ts), the same array guards/L1-location.md is rendered from. Classify, take the first\n// matching row, dispatch on its blockId — so a row deleted from the array is a block that stops firing,\n// and the doc cannot describe a table the guard does not consult. The two report builders below still\n// own their own predicates and their deny strings; l1-matrix.spec.ts asserts the row lookup and those\n// predicates agree.\n//\n// misplacedCdBlock is deliberately OUTSIDE that lookup, and runs ahead of it, for the reason its own\n// docblock gives: it decides from command TEXT, before a tree has been resolved, and the other two\n// reason FROM the resolved tree. Classifying it would mean asking L1_ROWS a question whose answer the\n// classification itself depends on. It is the same shape as L2's `bareCheckoutOfMain` pre-stage. It is\n// therefore ROW 0 — \"pre-stage, decided from command text\" — rather than a row among 1-6, which keeps\n// it IN the table (the drift this table exists to prevent) without pretending it is classified over the\n// same five dimensions. `L1_PRESTAGE_ROW` is the number the doc prints and `row=` logs, so the two join.\n//\n// THIS FUNCTION IS THE ONE PLACE L1 REPORTS. It is the only scope holding the classification, the\n// matched row, the resolved tree and the agent at once — so logging here, BEFORE the early return,\n// is what finally records the outcomes that were previously invisible: the exempt row and the three\n// hand-downs wrote nothing at all, which is why \"L1 had no objection\" could not be observed and\n// \"show me every L1 decision\" had no answer. The three block helpers no longer log for themselves —\n// and, for the same reason, none of them knows about the matrix POINTER either: every deny is stamped\n// with it HERE, from the same scope and the same row number, so deny and log line cannot disagree.\n// webpieces-disable no-function-outside-class -- sibling of the other module-scope runner helpers; the whole file is functions and a lone class here would break its shape\nfunction l1LocationBlock(command: string, tree: EffectiveTree, aiType: AiType): BlockedResult | null {\n const misplacedCd = misplacedCdBlock(command, tree);\n if (misplacedCd !== null) {\n logL1(tree, command, 'BLOCK_AI_CURE', L1_PRESTAGE_ROW, 'cd-must-be-first', 'cd not leading/literal');\n return withLocationMatrixPointer(misplacedCd, tree.root, L1_PRESTAGE_ROW);\n }\n\n const row = firstMatchingL1Row(l1Classify(command, tree));\n const rowNum = String(row.num);\n if (row.blockId === null) {\n // ALLOW_EXEMPT stops here; ALLOW means \"no objection, handed down to L2\". Recording the\n // difference is the point — see Verdict. Neither claims the call RAN: the other parallel hook\n // may still have denied it.\n logL1(tree, command, row.action.kind === 'exempt' ? 'ALLOW_EXEMPT' : 'ALLOW', rowNum, '-', row.why);\n return null;\n }\n logL1(tree, command, 'BLOCK_AI_CURE', rowNum, row.blockId, row.why);\n if (row.blockId === 'missing-directory') return withLocationMatrixPointer(missingDirectoryBlock(command, tree), tree.root, rowNum);\n if (row.blockId === 'trinary-version-skew') return withLocationMatrixPointer(versionSkewBlock(command, tree, aiType), tree.root, rowNum);\n return withLocationMatrixPointer(gitFromSubdirBlock(command, tree, isGitOrGhCommand(command)), tree.root, rowNum);\n}\n\n// One L1 line, into L1's OWN stream. `row` is the number the generated doc prints, so a reader who sees\n// `row=5` can open the L1 matrix at row 5 — the deny for that same call names it by absolute path.\n// eslint-disable-next-line @typescript-eslint/max-params -- the six fields of one log line, and a class here would break this file's shape\n// webpieces-disable no-function-outside-class -- sibling of the module-scope runner helpers; the whole file is functions\nfunction logL1(tree: EffectiveTree, command: string, verdict: Verdict, row: string, rule: string, why: string): void {\n logL1Decision(tree.root, new GuardDecision(\n rule, 'Bash', command, branchForLog(tree.root), verdict, why, '-', L0_FAULT_NONE, new MatrixRef('L1', row),\n ));\n}\n\n/**\n * ONE legal shape for relocating a command: `cd <literal path> && <work>`. Anything else — a `cd` after\n * another command or after a `VAR=…` assignment, or a `cd \"$DIR\"` the guard cannot expand — is refused\n * here instead of being silently judged from the shell cwd.\n *\n * This changes no verdict: every command it refuses was ALREADY judged from the shell cwd, so nothing\n * it blocks was previously being allowed on the strength of its `cd`. What changes is that the agent\n * finds out. Two PRs of increasingly precise near-miss wording (#596, #597) still left the fact in a\n * paragraph appended to an unrelated block; the rule is simpler stated as a rule.\n *\n * FIRST in the L1 chain deliberately. version skew and force-to-root both reason from the\n * resolved tree, and if the `cd` did not resolve, that tree is not the one the agent thinks they are\n * in — so their remedies would be steering from a location the command does not actually run in.\n */\n// webpieces-disable no-function-outside-class -- sibling of the other module-scope runner helpers; the whole runner is module-scope functions\nfunction misplacedCdBlock(command: string, tree: EffectiveTree): BlockedResult | null {\n const reason = new EffectiveTreeResolver().misplacedCd(command);\n if (reason === null) return null;\n const report =\n `❌ A \\`cd\\` must come FIRST in the command, with a LITERAL path.\\n` +\n ` Why this one was rejected: ${reason}.\\n` +\n ` \\`cd <literal path> && <work>\\` is the ONE shape that moves where webpieces judges a command.\\n` +\n ` Any other \\`cd\\` cannot be resolved, so the command would be judged against ${tree.root}\\n` +\n ` — not where you think it runs. That used to happen silently; this block is that silence, spoken.\\n` +\n ` Fix Option 1: put the \\`cd\\` first, literal path, SAME command: cd /abs/path && <the rest>\\n` +\n ` Fix Option 2: drop the \\`cd\\` — ${tree.root} is where the command is judged anyway.\\n` +\n ` Fix Option 3: if the SECOND \\`cd\\` was there to point a tool at a directory, use that tool's own\\n` +\n ` directory flag instead — \\`git -C <dir>\\`, \\`tar -C <dir>\\`, \\`npm --prefix <dir>\\`,\\n` +\n ` \\`npm pack --pack-destination <dir>\\`, \\`pnpm --dir <dir>\\`. One \\`cd\\`, same result.\\n` +\n ` ONLY for a dir INSIDE this tree. \\`git -C <another tree>\\` is REFUSED to a subagent,\\n` +\n ` and is never the cure for a version skew — for that, tell the MAIN agent.\\n` +\n ` Fix Option 4: split it — run the work in one call, the \\`cd\\` in another (a \\`cd\\` alone still\\n` +\n ` moves nothing the guards judge; see EffectiveTree on why cwd cannot be assumed).`;\n return new BlockedResult(report);\n}\n\n/**\n * The KEYLESS bash guards, deliberately kept OUT of the config-driven rule set. They have no\n * webpieces.config.json entry at all, so passing them through checkConfigSync would make every\n * consumer's next Bash call a fault-Y block (\"this rule has no entry\") for a feature nobody opted into\n * — which is exactly what whole-repo-build-guard did on its first release. Each one decides for itself\n * whether it acts: whole-repo-build-guard reads ~/.webpieces/config.json for a machine-local OPT-IN\n * (absent means OFF); commit-message-substitution-guard and build-output-pipe-guard act unconditionally.\n * They still honour excludePaths, and they do not run in `rules` mode (code-style-only hook).\n */\n// webpieces-disable no-function-outside-class -- sibling of the module-scope runner helpers; the whole file is functions and a lone class here would break its shape\nfunction keylessBashRules(loaded: LoadedConfig, mode: HookMode, governed: GovernedPath): readonly Rule[] {\n if (mode === 'rules') return [];\n return filterByExcludedPaths(\n loadKeylessBashRules(loaded.prGate.buildCommand), governed, loaded.excludePaths,\n );\n}\n\n// webpieces-disable no-function-outside-class -- sibling of run()/runBash() in this module; the whole runner is module-scope functions and a lone class for this one entry point would break the file's shape\nfunction runBashInternal(\n command: string,\n cwd: string,\n mode: HookMode,\n aiType: AiType,\n): BlockedResult | null {\n if (isL0CureCommand(command)) {\n logL0CureBypass(command, cwd);\n return null;\n }\n\n const loaded = loadConfigOrAllowInspection(command, cwd);\n // null = the config would not load AND this command only inspects → allow, see the helper.\n if (loaded === null) return null;\n if (loaded.configPath === null)\n return l0FaultAllows(command, aiType) ? null : configMissingBlock(cwd);\n\n const workspaceRoot = path.dirname(loaded.configPath);\n\n // WHICH TREE does this command act on? Not the shell's cwd: a `cd` OUT of the workspace is reset\n // by the harness and one INSIDE it persists, so neither can be assumed (see EffectiveTree).\n // ONE resolver answers this for the guards AND for force-to-root below, so the two can never\n // disagree about which tree you are in.\n const tree = new EffectiveTreeResolver().resolve(command, cwd, workspaceRoot);\n\n if (allowForeignTree(command, tree, workspaceRoot)) return null;\n\n // Honour excludePaths on the bash path too (not just Read/Edit): a command whose effective\n // cwd sits under an excluded tree (e.g. repositories/**) drops the whole guard set — matching how\n // runInternal/runRead treat file paths. The relative path is '' when there is no `cd` (root), which\n // matches no exclusion glob, so a plain command at the repo root is unaffected.\n const governedCwd = bashGovernedPath(tree, workspaceRoot);\n const rules = filterByExcludedPaths(\n filterByMode(new WorkflowHookRules().load(loaded).rules, mode, loaded.ruleRegistry),\n governedCwd,\n loaded.excludePaths,\n );\n const keyless = keylessBashRules(loaded, mode, governedCwd);\n if (rules.length === 0 && keyless.length === 0) return null;\n\n const locationBlock = l1LocationBlock(command, tree, aiType);\n if (locationBlock) return locationBlock;\n\n // Keep the feature-branch-guard cache warm on EVERY command (not just Write/Edit): the AI runs\n // far more bash than edits, so refreshing here means the guard's next file-edit check reads a\n // fresh status. Detached + fire-and-forget — never blocks the command. Only when the guard is\n // loaded (guards/all mode) and enabled, so a project that opted out never triggers git fetches.\n // Keyed on the JUDGED tree, so a worktree's cache is refreshed rather than the primary clone's.\n maybeRefreshMainSync(rules, tree.root, branchStateHangTimeout(loaded.rulesConfig));\n\n const groups = runBashRules([...rules, ...keyless], buildBashContext(command, tree));\n return bashPolicyResult(command, tree, loaded, groups);\n}\n\n// The bash report's subject line. It used to be the literal string `<bash>`, which told the agent\n// nothing; the command itself is what was blocked, so name it — truncated, because a heredoc-bearing\n// command can run to thousands of characters and the violation lines already carry the detail.\n// webpieces-disable no-function-outside-class -- sibling of the module-scope runner helpers; the whole file is functions and a lone class here would break its shape\nfunction commandLabel(command: string): string {\n const oneLine = command.replace(/\\s+/g, ' ').trim();\n const MAX = 100;\n return oneLine.length <= MAX ? oneLine : oneLine.slice(0, MAX) + '…';\n}\n\n// When a push/PR block fires AND the config exempts vendored/nested trees, surface the escape hatch the\n// AI cannot otherwise discover: git/gh run UNGUARDED inside those trees if it cd's there first (each is\n// governed by its own repo, not this one). Scoped to pr-creation-or-push-guard — for the other guards\n// \"cd into an exempt tree\" is not the remedy — and emitted only when such trees are actually configured,\n// so a repo without exemptions never sees the noise.\n//\n// The hint MUST state the precondition, not just the remedy. \"cd into it first\" is true only for a\n// LITERAL cd at the FRONT of the same command; `D=…; cd \"$D\"; git push` lands in the identical\n// directory and does NOT relocate the verdict. That used to be silent, then a near-miss paragraph\n// appended here; it is now misplacedCdBlock, which refuses the command outright — so by the time this\n// footer is reached, any `cd` in the command is already known to be leading and literal. The wording\n// still states the shape, because this is where an agent LEARNS it, before writing the next command.\n// webpieces-disable no-function-outside-class -- sibling of the module-scope runner helpers; the whole file is functions and a lone class here would break its shape\nfunction exemptTreesHint(groups: readonly RuleGroup[], exemptGuards: readonly string[]): string {\n if (exemptGuards.length === 0) return '';\n if (!groups.some((g: RuleGroup): boolean => g.ruleName === 'pr-creation-or-push-guard'))\n return '';\n\n return (\n `\\n\\nℹ️ Working in a nested repo under one of these exempt trees (${exemptGuards.join(', ')})? ` +\n `Put a LITERAL \\`cd\\` at the FRONT of the SAME command — \\`cd /abs/path/to/repo && git push\\` — and git/gh ` +\n `run normally there: the webpieces guards do NOT govern them (each is its own repo).` +\n `\\n \\`cd <literal path> && <work>\\` is the ONE shape that moves where a command is judged. A \\`cd\\` ` +\n `anywhere else in the line, or a non-literal target like \\`cd \"$DIR\"\\`, is refused outright rather than ` +\n `judged from somewhere you did not intend.`\n );\n}\n\n// webpieces-disable no-function-outside-class -- runner result assembly is a pure orchestration helper\nfunction bashPolicyResult(command: string, tree: EffectiveTree, loaded: LoadedConfig, groups: readonly RuleGroup[]): BlockedResult | null {\n const workspaceRoot = path.dirname(loaded.configPath!);\n if (groups.length === 0) {\n // Record the ALLOW only for git/gh commands — the operations the bash guards actually reason\n // about (branch create, commit, push, merge, PR). Skipping ls/cat/grep keeps the audit log\n // focused (the whole point of the log is \"why did/didn't a guard fire?\"). Blocks are always\n // logged below.\n if (/\\b(?:git|gh)\\b/.test(command)) {\n logGuardDecision(\n tree.root,\n new GuardDecision(\n '-',\n 'Bash',\n command,\n branchForLog(tree.root),\n 'ALLOW',\n 'no bash-guard block',\n '-',\n L0_FAULT_NONE,\n MATRIX_L2_UNROWED,\n ),\n );\n }\n return null;\n }\n\n const ruleNames = groups.map((g: RuleGroup): string => g.ruleName).join(',');\n logGuardDecision(\n tree.root,\n new GuardDecision(\n ruleNames,\n 'Bash',\n command,\n branchForLog(tree.root),\n 'BLOCK_AI_CURE',\n 'bash-guard block',\n '-',\n L0_FAULT_NONE,\n MATRIX_L2_UNROWED,\n ),\n );\n const report =\n new ExcludedPathEscapeHint(workspaceRoot, tree.effectiveCwd).render(\n command,\n loaded.excludePaths,\n ) +\n formatReport(commandLabel(command), groups, BASH_SUBJECT) +\n exemptTreesHint(groups, loaded.excludePaths.paths);\n return new BlockedResult(report);\n}\n\n// webpieces-disable no-function-outside-class -- orchestration helper for the explicit foreign-repository exemption\nfunction allowForeignTree(command: string, tree: EffectiveTree, workspaceRoot: string): boolean {\n if (tree.kind === 'foreign') {\n logGuardDecision(\n workspaceRoot,\n new GuardDecision(\n '-',\n 'Bash',\n command,\n branchForLog(workspaceRoot),\n 'ALLOW_EXEMPT',\n 'foreign git repo (out of scope)',\n '-',\n L0_FAULT_NONE,\n new MatrixRef('L1', '1'),\n ),\n );\n return true;\n }\n\n return false;\n}\n"]}
1
+ {"version":3,"file":"runner.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/core/runner.ts"],"names":[],"mappings":";;AAgEA,4CAEC;AAKD,4CAEC;AAkBD,kBAOC;AAqFD,0BAEC;AAmBD,0BA2CC;;AAvPD,0DAAiG;AACjG,mDAA6B;AAE7B,0DAYiC;AAEjC,0DAA0E;AAC1E,0DAA4D;AAC5D,iDAAkD;AAClD,0DAA+E;AAC/E,0DAA2E;AAC3E,0DAAkF;AAClF,iEAAgE;AAChE,mDAAqD;AACrD,6CAAoD;AACpD,+DAA0D;AAC1D,2DAA4D;AAC5D,2DAAmF;AACnF,iDAAsJ;AACtJ,iEAA6D;AAC7D,0DAAmF;AACnF,iEAAgE;AAChE,sCAA0D;AAC1D,0DAAyD;AAEzD,0DAA8G;AAC9G,0DAA2F;AAC3F,2CAAsE;AACtE,uCAAkF;AAClF,mDAA4D;AAC5D,0DAAoK;AAEpK,8DAA0D;AAE1D,mGAAmG;AACnG,oGAAoG;AACpG,oGAAoG;AACpG,2BAA2B;AAC3B,oGAAoG;AACpG,2FAA2F;AAC3F,gGAAgG;AAChG,yFAAyF;AACzF,mKAAmK;AACnK,SAAS,YAAY,CAAC,KAAsB,EAAE,IAAc,EAAE,QAA0B;IACpF,IAAI,IAAI,KAAK,KAAK;QAAE,OAAO,KAAK,CAAC;IACjC,IAAI,IAAI,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC,MAAM,CAAC,CAAC,CAAO,EAAW,EAAE,CAAC,IAAA,0BAAW,EAAC,CAAC,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC,CAAC;IACrG,OAAO,KAAK,CAAC,MAAM,CAAC,CAAC,CA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AK,CAAC;AACjB,CAAC","sourcesContent":["import { runRuleCheck, runEditRules, runFileRules, runBashRules } from '@webpieces/hook-runtime';\nimport * as path from 'path';\n\nimport {\n loadAndValidate,\n LoadedConfig,\n ConfigRepairAccess,\n RulePackRegistry,\n WebpiecesRulesConfig,\n isHookGuard,\n HomeConfigService,\n RepoRootFinder,\n seedEntryForRule,\n CONFIG_FILENAME,\n renderRuleFailForAi,\n} from '@webpieces/rules-config';\n\nimport { buildContexts, buildBashContext } from '@webpieces/hook-runtime';\nimport { DeleteScopedRules } from '@webpieces/hook-runtime';\nimport { VersionSyncGuard } from './version-sync';\nimport { EffectiveTree, EffectiveTreeResolver } from '@webpieces/hook-runtime';\nimport { GovernedPath, TargetTreeResolver } from '@webpieces/hook-runtime';\nimport { bashGovernedPath, filterByExcludedPaths } from '@webpieces/hook-runtime';\nimport { ExcludedPathEscapeHint } from './excluded-path-escape';\nimport { gitFromSubdirBlock } from './force-to-root';\nimport { loadKeylessBashRules } from './load-rules';\nimport { WorkflowHookRules } from './workflow-hook-rules';\nimport { missingDirectoryBlock } from './missing-directory';\nimport { branchStateHangTimeout, maybeRefreshMainSync } from './main-sync-timeout';\nimport { logGuardDecision, logL1Decision, GuardDecision, branchForLog, MatrixRef, Verdict, MATRIX_L0_ALLOW, MATRIX_L2_UNROWED } from './decision-log';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { formatReport, READ_SUBJECT, BASH_SUBJECT } from '@webpieces/hook-runtime';\nimport { ReadOnlyInspectionScan } from './read-only-inspection';\nimport { L0_CURE_ALLOW_JS, isAllowed } from '../bin/shim';\nimport { isRootManifest } from '@webpieces/hook-runtime';\nimport { AiType } from '@webpieces/hook-runtime';\nimport { L0_FAULT_CONFIG_MISSING, L0_FAULT_CONFIG_OUT_OF_SYNC, L0_FAULT_NONE } from '@webpieces/rules-config';\nimport { CONFIG_MISSING_REPORT, CONFIG_OUT_OF_SYNC_HEADER } from '@webpieces/rules-config';\nimport { writeGuardMatrixDoc, guardMatrixPointer } from './l0-matrix';\nimport { L1Classification, firstMatchingL1Row, L1_PRESTAGE_ROW } from './l1-rows';\nimport { withLocationMatrixPointer } from './l1-matrix-doc';\nimport { ToolKind, NormalizedToolInput, BlockedResult, HookMode, Rule, Violation, RuleGroup, EditContext, FileContext, BashContext } from '@webpieces/hook-runtime';\nimport { RuleFailError } from '@webpieces/rules-config';\nimport { InformAiError } from '@webpieces/tooling-common';\n\n// Restrict loaded rules to the category this hook invocation runs. The two split hooks each pass a\n// disjoint category ('rules' = code-style, 'guards' = the hookGuards section); 'all' runs both (the\n// openclaw plugin adapter, a single before_tool_call hook). isHookGuard is the shared classifier in\n// @webpieces/rules-config.\n// isHookGuard is asked about the rule's CONFIG KEY, never its name. Since the collapse those differ\n// for every class behind a policy key — `feature-branch-guard` is a rule NAME whose key is\n// `branch-state-guard` — and asking about the name would classify all eight collapsed guards as\n// code-style rules, i.e. run them in the wrong hook and never in the guards hook at all.\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nfunction filterByMode(rules: readonly Rule[], mode: HookMode, registry: RulePackRegistry): readonly Rule[] {\n if (mode === 'all') return rules;\n if (mode === 'guards') return rules.filter((r: Rule): boolean => isHookGuard(r.configKey, registry));\n return rules.filter((r: Rule): boolean => !isHookGuard(r.configKey, registry));\n}\n\n// The cwd a command actually runs from, after its own leading `cd`/`pushd` run. Thin delegate kept\n// for the callers (and specs) that only need the directory; the full tree classification — primary\n// clone vs linked worktree vs nested clone vs outside any repo — is EffectiveTreeResolver.resolve().\n// webpieces-disable no-function-outside-class -- sibling of the module-scope runner helpers; the whole file is functions and a lone class here would break its shape\nexport function effectiveBashCwd(command: string, cwd: string): string {\n return new EffectiveTreeResolver().effectiveCwd(command, cwd);\n}\n\n// A git or gh invocation anywhere in the command (start, or after a ;/&&/|| separator or pipe).\nconst GIT_OR_GH_RE = /(?:^|[;&|]\\s*)(?:git|gh)\\b/;\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nexport function isGitOrGhCommand(command: string): boolean {\n return GIT_OR_GH_RE.test(command);\n}\n\n// Fault C (webpieces.config.json missing) — the deny text lives in ./l0-matrix beside the rest of the\n// L0 fault table, so the message and the allowlist can never prescribe different cures. `cwd` is used\n// only to drop the matrix doc where the AI can read it (the config root does not exist yet here).\n//\n// THE ALLOWLIST ESCAPE IS THE CALLER'S (moved out 2026-09-01): behind an optional `command` it could\n// not see the harness, so the gated half of the list was unreachable under C while\n// CONFIG_MISSING_REPORT promised it. See l0FaultAllows. This has one job now: build the block.\n// webpieces-disable no-function-outside-class -- sibling of the module-scope runner helpers; the whole file is functions and a lone class here would break its shape\nfunction configMissingBlock(cwd: string): BlockedResult {\n const root = new RepoRootFinder().resolveRepoRoot(cwd);\n // Stamped with its L0 letter so the block is greppable as fault C wherever it is recorded — the\n // adapter carries it to the audit line rather than re-deriving it from the report text.\n return new BlockedResult(CONFIG_MISSING_REPORT + guardMatrixPointer(writeGuardMatrixDoc(root)), L0_FAULT_CONFIG_MISSING);\n}\n\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nexport function run(\n toolKind: ToolKind,\n input: NormalizedToolInput,\n cwd: string,\n mode: HookMode = 'all',\n): BlockedResult | null {\n return runInternal(toolKind, input, cwd, mode);\n}\n\n// The pre-config pass: an edit whose every path — BOTH sides of a Move — is a repair file, a root\n// manifest or the home config. Checking the source is what stops a rename of ordinary code ONTO a\n// recovery file from deleting that code with nothing judging it (#1448).\n// webpieces-disable no-function-outside-class -- sibling of runInternal in this module-scope runner\nfunction isPreConfigRecoveryEdit(toolKind: ToolKind, input: NormalizedToolInput, cwd: string): boolean {\n if (toolKind === 'Delete') return false;\n const root = new RepoRootFinder().resolveRepoRoot(cwd);\n return [input.filePath, input.sourcePath].every(\n (target: string): boolean =>\n new ConfigRepairAccess().isRepairFile(root, target) ||\n isRootManifest(target) ||\n new HomeConfigService().isHomeConfigPath(target),\n );\n}\n\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nfunction runInternal(\n toolKind: ToolKind,\n input: NormalizedToolInput,\n cwd: string,\n mode: HookMode,\n): BlockedResult | null {\n if (isPreConfigRecoveryEdit(toolKind, input, cwd)) return null;\n const loaded = loadAndValidate(cwd);\n if (loaded.configPath === null) return configMissingBlock(cwd);\n\n const workspaceRoot = path.dirname(loaded.configPath);\n\n // Always allow edits to webpieces.config.json — it's the fix target when out of sync — and the same\n // PASS for the machine-local `~/.webpieces/config.json` (a bad key there fails a `wp-*` command with\n // an instruction to edit it, so blocking the edit would wedge the agent inside the failure) and for\n // the two ROOT MANIFESTS a pin lives in — L1 row 8 PROMISED that edit and its cure IS it.\n // isRootManifest, never a basename: this returns EARLY, so basename would unrule every package.json\n // in the repo. It admits any tree's root (the config sits beside it), which is what a worktree's own\n // cure needs. IN PLACE ONLY: a Move onto one of these still deletes its source, which is judged (#1448).\n if (\n input.sourcePath === input.filePath &&\n (path.resolve(input.filePath) === path.resolve(loaded.configPath) ||\n isRootManifest(input.filePath) ||\n new HomeConfigService().isHomeConfigPath(input.filePath))\n )\n return null;\n\n // Built-in/custom rules PLUS the client-authored match-rules (content guards). Match-rules run only\n // in the file-edit path (they are code-style, so filterByMode keeps them out of the bash/guards path).\n const allRules = [...new WorkflowHookRules().load(loaded).rules];\n const modeRules = filterByMode(allRules, mode, loaded.ruleRegistry);\n if (modeRules.length === 0) return null;\n\n // Suppress enforcement for files under this category's excludePaths (e.g. vendored repos under\n // repositories/**). Exclusion is all-or-nothing per category, so an excluded file drops the whole\n // rule set and is fully hands-off — no violations AND no config-sync nag on those files.\n const governed = new TargetTreeResolver().governedPath(input.filePath, workspaceRoot);\n const relativePath = governed.relativePath;\n const rules = new DeleteScopedRules().narrow(\n toolKind,\n filterByExcludedPaths(modeRules, governed, loaded.excludePaths),\n );\n if (rules.length === 0) return null;\n\n const contexts = buildContexts(toolKind, input, workspaceRoot, governed);\n\n const editGroups = runEditRules(rules, contexts.editContexts);\n const fileGroups = runFileRules(rules, contexts.fileContext);\n const allGroups = [...editGroups, ...fileGroups];\n\n if (allGroups.length === 0) return null;\n\n const report = formatReport(relativePath, allGroups);\n return new BlockedResult(report);\n}\n\n// SINGLETON, deliberately: WebpiecesVersions memoizes per root, and the same two roots are asked for on\n// every Bash call. A fresh instance per call would spawn `git worktree list` and re-read two manifests\n// on the hook's blocking path each time.\nconst VERSION_SYNC = new VersionSyncGuard();\n\n// There is deliberately NO agent parameter. It existed only for CoordinatorWorktreeGuard, which asked\n// WHO was calling; that guard is gone and its replacement asks WHICH TREE the command acts on. Agent\n// identity was measured untrustworthy for that question anyway — a worktree-isolated agent auto-reaped\n// at a turn boundary silently resumes with its cwd on the primary clone — so a guard must never infer\n// a tree from who is asking.\n// webpieces-disable no-function-outside-class -- sibling of run()/runRead() in this module; the whole runner is module-scope functions and a lone class for this one entry point would break the file's shape\nexport function runBash(command: string, cwd: string, mode: HookMode, aiType: AiType): BlockedResult | null {\n return runBashInternal(command, cwd, mode, aiType);\n}\n\n// The name of the ONLY rule permitted to block a Read. Reads are the highest-blast-radius tool\n// there is, so this path is an explicit single-rule allowlist rather than the general rule loop.\nconst READ_SCOPED_GUARDS: ReadonlySet<string> = new Set(['read-stale-guard']);\n\n/**\n * The Read path. Deliberately NOT `run()`:\n *\n * - NO config-sync check. A rule present in code but missing from webpieces.config.json blocks\n * every Write/Edit/Bash by design — but applying that to Read would mean an upgrade that adds\n * any new rule instantly blocks the agent from reading the very config file it must edit to fix\n * it. Reads must never carry that failure mode.\n * - NO general rule loop. Only READ_SCOPED_GUARDS run, so no code-style rule can ever see a Read.\n * - Fails OPEN everywhere, including on a thrown rule (the caller catches and allows).\n *\n * Returns null (allow) unless the one guard fires.\n */\n// webpieces-disable no-function-outside-class -- sibling of run()/runBash() in this module; the whole runner is module-scope functions and a lone class for this one entry point would break the file's shape\nexport function runRead(\n filePath: string,\n cwd: string,\n mode: HookMode = 'all',\n): BlockedResult | null {\n // Code-style mode has nothing to say about a read.\n if (mode === 'rules') return null;\n\n let loaded: LoadedConfig;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- broken configuration must remain readable without enabling any mutating policy\n try {\n loaded = loadAndValidate(cwd);\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n } catch (err: unknown) {\n const error = toError(err);\n if (error instanceof InformAiError) return null;\n throw error;\n }\n // No config → nothing to enforce. Unlike the edit path we do NOT block: an unconfigured repo\n // must still be readable.\n if (loaded.configPath === null) return null;\n\n const workspaceRoot = path.dirname(loaded.configPath);\n\n // Same git-repo-boundary governance as bash, through the SAME resolver: a read inside a different\n // clone is out of scope. (No command to parse here, so the shell cwd IS the effective cwd.)\n if (new EffectiveTreeResolver().resolve('', cwd, workspaceRoot).kind === 'foreign') return null;\n\n const governed = new TargetTreeResolver().governedPath(filePath, workspaceRoot);\n const relativePath = governed.relativePath;\n const all = new WorkflowHookRules().load(loaded).rules;\n const rules = filterByExcludedPaths(\n all.filter((r: Rule): boolean => READ_SCOPED_GUARDS.has(r.name)),\n governed,\n loaded.excludePaths,\n );\n if (rules.length === 0) return null;\n\n const ctx = new FileContext('Read', filePath, relativePath, workspaceRoot, null, 0, 0, 0, 0);\n const groups = runFileRules(rules, ctx);\n if (groups.length === 0) return null;\n\n return new BlockedResult(formatReport(relativePath, groups, READ_SUBJECT));\n}\n\n// L0 cure bypass — every command on THE L0 allowlist passes here, ahead of any config load. A\n// webpieces.config.json that is ahead of the installed validator (new rule tokens the published\n// binary doesn't know yet) makes loadAndValidate() throw and would deny `pnpm install` — the very\n// command that updates the validator (deadlock).\n//\n// This used to test INSTALLER_ALLOW_JS alone, which made the config faults (C = config missing,\n// Y = config out of sync) accept a bare `pnpm install` while denying `rm -rf node_modules && pnpm\n// install` — the one cure that works when node_modules is CORRUPT rather than merely stale. Same\n// intent, opposite verdict, for no reason anyone recorded. Each alternative is still anchored at both\n// ends, so `pnpm install && rm -rf /` still falls to the guards.\n//\n// It tests the CURE subset (L0_CURE_ALLOW_JS), not the whole list, and the distinction matters here\n// and nowhere else: this call site runs BEFORE any fault has been established, so whatever it accepts\n// is waved past the L1 guards on a perfectly healthy repo too. A repair command has to be waved past —\n// it runs before the config can be loaded at all. Read-only ORIENTATION does not: it fixes nothing, and\n// letting `git status` through here would delete force-to-root as a side effect of adding `pwd`. Under\n// an actual fault, l0FaultAllows() below consults the WHOLE list.\n// webpieces-disable no-function-outside-class -- sibling of the module-scope runner helpers; the whole file is functions and a lone class here would break its shape\nfunction isL0CureCommand(command: string): boolean {\n return L0_CURE_ALLOW_JS.test(command.trim());\n}\n\n// The FULL L0 list, asked only where this file has actually detected an L0 fault (C = config missing,\n// Y = config out of sync). D/X/U/K are decided in the shim, which greps the same union.\n// IT ASKS `isAllowed()`, not a regex: that is the ONE question both halves of L0 ask, and the only\n// place harness-gated entries are consulted. Testing `L0_ALLOW_JS` directly (which is what this did)\n// dropped the Codex read under C and Y while D/X/U/K honoured it — a per-fault carve-out again.\n// webpieces-disable no-function-outside-class -- sibling of the module-scope runner helpers; the whole file is functions and a lone class here would break its shape\nfunction l0FaultAllows(command: string, aiType: AiType): boolean {\n return isAllowed('Bash', command.trim(), '', aiType) !== null;\n}\n\n// The L0 cure bypass's audit line. Anchored at the repo root that owns `.webpieces` — RepoRootFinder\n// (config-walk-up first, then git toplevel) is the authority for that, and it is correct in a linked\n// worktree because each worktree checks out its own webpieces.config.json. This runs BEFORE\n// loadAndValidate, which is why it resolves the root itself rather than using workspaceRoot.\n// webpieces-disable no-function-outside-class -- sibling of the module-scope runner helpers; the whole file is functions and a lone class here would break its shape\nfunction logL0CureBypass(command: string, cwd: string): void {\n const root = new RepoRootFinder().resolveRepoRoot(cwd);\n logGuardDecision(root, new GuardDecision('-', 'Bash', command, branchForLog(root), 'ALLOW', 'L0 cure bypass (always allowed)', '-', L0_FAULT_NONE, MATRIX_L0_ALLOW));\n}\n\n/**\n * Load the config for the bash path — but do NOT let an unloadable config trap the tools needed to\n * repair it.\n *\n * loadAndValidate throws an InformAiError when webpieces.config.json is unparseable (a real syntax\n * error, or leftover `<<<<<<< HEAD` markers mid-merge) or fails validation. That throw propagates to\n * the hook adapter, which fails CLOSED and denies the command — correct for work, since a config that\n * did not load means no guards ran. But it denied `cat`/`grep`/`sed -n` on webpieces.config.json too,\n * i.e. it blocked the only way to see the problem it was reporting. Observed live, twice.\n *\n * So: on a load failure, a provably-inert INSPECTION command is allowed through (returns null, \"no\n * block\"), matching the escape hatch every other layer already grants this file. Everything else —\n * every write, every git/gh command, every build — still hits the same hard failure as before. The\n * bypass cannot be widened by accident; see ReadOnlyInspectionScan for how narrow \"inert\" is.\n *\n * Returns the loaded config, or null meaning \"allow this command without guards\".\n */\n// webpieces-disable no-function-outside-class -- sibling of the module-scope runner helpers; the whole file is functions and a lone class here would break its shape\nfunction loadConfigOrAllowInspection(command: string, cwd: string): LoadedConfig | null {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- rethrown unchanged unless the command is provably inert\n try {\n return loadAndValidate(cwd);\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n } catch (err: unknown) {\n const error = toError(err);\n if (error instanceof InformAiError && new ReadOnlyInspectionScan().isReadOnlyInspection(command)) {\n return null;\n }\n throw error;\n }\n}\n\n// Version skew: this worktree pins a different @webpieces than the MAIN tree that governs it. The guard\n// hooks are absolute, so the main tree's binary judges every tree — which is fine until the two trees\n// disagree about which release that should be. L1 row 8; guards/L1-location.md carries the table.\n// webpieces-disable no-function-outside-class -- sibling of the other module-scope runner helpers; the whole file is functions and a lone class here would break its shape\nfunction versionSkewBlock(command: string, tree: EffectiveTree, aiType: AiType): BlockedResult | null {\n const report = VERSION_SYNC.block(command, tree, aiType);\n return report === null ? null : new BlockedResult(report);\n}\n\n// Where the command lands in L1's five dimensions (K/A/R/G/P). The ONE place the runner's view of the\n// world is translated into the matrix's vocabulary — see L1Classification.forEnforcement for why\n// TreeKind 'outside' currently classifies as `p`.\n// webpieces-disable no-function-outside-class -- sibling of the other module-scope runner helpers; the whole file is functions and a lone class here would break its shape\nfunction l1Classify(command: string, tree: EffectiveTree): L1Classification {\n return L1Classification.forEnforcement(\n tree.kind,\n VERSION_SYNC.skewed(tree),\n new ReadOnlyInspectionScan().isReadOnlyInspection(command),\n isGitOrGhCommand(command),\n path.resolve(tree.effectiveCwd) === path.resolve(tree.root),\n );\n}\n\n// The structural L1 blocks, in order: the misplaced-`cd` PRE-STAGE, then version skew (row 8), then\n// force-to-root (row 5). None is a configurable rule — they are decided from the command text, the\n// resolved tree and the caller, so they run as one step here rather than as three near-identical\n// stanzas in runBashInternal.\n//\n// For the two TREE-BASED blocks the ORDER and the CHOICE are not written here: they come from L1_ROWS\n// (l1-rows.ts), the same array guards/L1-location.md is rendered from. Classify, take the first\n// matching row, dispatch on its blockId — so a row deleted from the array is a block that stops firing,\n// and the doc cannot describe a table the guard does not consult. The two report builders below still\n// own their own predicates and their deny strings; l1-matrix.spec.ts asserts the row lookup and those\n// predicates agree.\n//\n// misplacedCdBlock is deliberately OUTSIDE that lookup, and runs ahead of it, for the reason its own\n// docblock gives: it decides from command TEXT, before a tree has been resolved, and the other two\n// reason FROM the resolved tree. Classifying it would mean asking L1_ROWS a question whose answer the\n// classification itself depends on. It is the same shape as L2's `bareCheckoutOfMain` pre-stage. It is\n// therefore ROW 0 — \"pre-stage, decided from command text\" — rather than a row among 1-6, which keeps\n// it IN the table (the drift this table exists to prevent) without pretending it is classified over the\n// same five dimensions. `L1_PRESTAGE_ROW` is the number the doc prints and `row=` logs, so the two join.\n//\n// THIS FUNCTION IS THE ONE PLACE L1 REPORTS. It is the only scope holding the classification, the\n// matched row, the resolved tree and the agent at once — so logging here, BEFORE the early return,\n// is what finally records the outcomes that were previously invisible: the exempt row and the three\n// hand-downs wrote nothing at all, which is why \"L1 had no objection\" could not be observed and\n// \"show me every L1 decision\" had no answer. The three block helpers no longer log for themselves —\n// and, for the same reason, none of them knows about the matrix POINTER either: every deny is stamped\n// with it HERE, from the same scope and the same row number, so deny and log line cannot disagree.\n// webpieces-disable no-function-outside-class -- sibling of the other module-scope runner helpers; the whole file is functions and a lone class here would break its shape\nfunction l1LocationBlock(command: string, tree: EffectiveTree, aiType: AiType): BlockedResult | null {\n const misplacedCd = misplacedCdBlock(command, tree);\n if (misplacedCd !== null) {\n logL1(tree, command, 'BLOCK_AI_CURE', L1_PRESTAGE_ROW, 'cd-must-be-first', 'cd not leading/literal');\n return withLocationMatrixPointer(misplacedCd, tree.root, L1_PRESTAGE_ROW);\n }\n\n const row = firstMatchingL1Row(l1Classify(command, tree));\n const rowNum = String(row.num);\n if (row.blockId === null) {\n // ALLOW_EXEMPT stops here; ALLOW means \"no objection, handed down to L2\". Recording the\n // difference is the point — see Verdict. Neither claims the call RAN: the other parallel hook\n // may still have denied it.\n logL1(tree, command, row.action.kind === 'exempt' ? 'ALLOW_EXEMPT' : 'ALLOW', rowNum, '-', row.why);\n return null;\n }\n logL1(tree, command, 'BLOCK_AI_CURE', rowNum, row.blockId, row.why);\n if (row.blockId === 'missing-directory') return withLocationMatrixPointer(missingDirectoryBlock(command, tree), tree.root, rowNum);\n if (row.blockId === 'trinary-version-skew') return withLocationMatrixPointer(versionSkewBlock(command, tree, aiType), tree.root, rowNum);\n return withLocationMatrixPointer(gitFromSubdirBlock(command, tree, isGitOrGhCommand(command)), tree.root, rowNum);\n}\n\n// One L1 line, into L1's OWN stream. `row` is the number the generated doc prints, so a reader who sees\n// `row=5` can open the L1 matrix at row 5 — the deny for that same call names it by absolute path.\n// eslint-disable-next-line @typescript-eslint/max-params -- the six fields of one log line, and a class here would break this file's shape\n// webpieces-disable no-function-outside-class -- sibling of the module-scope runner helpers; the whole file is functions\nfunction logL1(tree: EffectiveTree, command: string, verdict: Verdict, row: string, rule: string, why: string): void {\n logL1Decision(tree.root, new GuardDecision(\n rule, 'Bash', command, branchForLog(tree.root), verdict, why, '-', L0_FAULT_NONE, new MatrixRef('L1', row),\n ));\n}\n\n/**\n * ONE legal shape for relocating a command: `cd <literal path> && <work>`. Anything else — a `cd` after\n * another command or after a `VAR=…` assignment, or a `cd \"$DIR\"` the guard cannot expand — is refused\n * here instead of being silently judged from the shell cwd.\n *\n * This changes no verdict: every command it refuses was ALREADY judged from the shell cwd, so nothing\n * it blocks was previously being allowed on the strength of its `cd`. What changes is that the agent\n * finds out. Two PRs of increasingly precise near-miss wording (#596, #597) still left the fact in a\n * paragraph appended to an unrelated block; the rule is simpler stated as a rule.\n *\n * FIRST in the L1 chain deliberately. version skew and force-to-root both reason from the\n * resolved tree, and if the `cd` did not resolve, that tree is not the one the agent thinks they are\n * in — so their remedies would be steering from a location the command does not actually run in.\n */\n// webpieces-disable no-function-outside-class -- sibling of the other module-scope runner helpers; the whole runner is module-scope functions\nfunction misplacedCdBlock(command: string, tree: EffectiveTree): BlockedResult | null {\n const reason = new EffectiveTreeResolver().misplacedCd(command);\n if (reason === null) return null;\n const report =\n `❌ A \\`cd\\` must come FIRST in the command, with a LITERAL path.\\n` +\n ` Why this one was rejected: ${reason}.\\n` +\n ` \\`cd <literal path> && <work>\\` is the ONE shape that moves where webpieces judges a command.\\n` +\n ` Any other \\`cd\\` cannot be resolved, so the command would be judged against ${tree.root}\\n` +\n ` — not where you think it runs. That used to happen silently; this block is that silence, spoken.\\n` +\n ` Fix Option 1: put the \\`cd\\` first, literal path, SAME command: cd /abs/path && <the rest>\\n` +\n ` Fix Option 2: drop the \\`cd\\` — ${tree.root} is where the command is judged anyway.\\n` +\n ` Fix Option 3: if the SECOND \\`cd\\` was there to point a tool at a directory, use that tool's own\\n` +\n ` directory flag instead — \\`git -C <dir>\\`, \\`tar -C <dir>\\`, \\`npm --prefix <dir>\\`,\\n` +\n ` \\`npm pack --pack-destination <dir>\\`, \\`pnpm --dir <dir>\\`. One \\`cd\\`, same result.\\n` +\n ` ONLY for a dir INSIDE this tree. \\`git -C <another tree>\\` is REFUSED to a subagent,\\n` +\n ` and is never the cure for a version skew — for that, tell the MAIN agent.\\n` +\n ` Fix Option 4: split it — run the work in one call, the \\`cd\\` in another (a \\`cd\\` alone still\\n` +\n ` moves nothing the guards judge; see EffectiveTree on why cwd cannot be assumed).`;\n return new BlockedResult(report);\n}\n\n/**\n * The KEYLESS bash guards, deliberately kept OUT of the config-driven rule set. They have no\n * webpieces.config.json entry at all, so passing them through checkConfigSync would make every\n * consumer's next Bash call a fault-Y block (\"this rule has no entry\") for a feature nobody opted into\n * — which is exactly what whole-repo-build-guard did on its first release. Each one decides for itself\n * whether it acts: whole-repo-build-guard reads ~/.webpieces/config.json for a machine-local OPT-IN\n * (absent means OFF); commit-message-substitution-guard and build-output-pipe-guard act unconditionally.\n * They still honour excludePaths, and they do not run in `rules` mode (code-style-only hook).\n */\n// webpieces-disable no-function-outside-class -- sibling of the module-scope runner helpers; the whole file is functions and a lone class here would break its shape\nfunction keylessBashRules(loaded: LoadedConfig, mode: HookMode, governed: GovernedPath): readonly Rule[] {\n if (mode === 'rules') return [];\n return filterByExcludedPaths(\n loadKeylessBashRules(loaded.prGate.buildCommand), governed, loaded.excludePaths,\n );\n}\n\n// webpieces-disable no-function-outside-class -- sibling of run()/runBash() in this module; the whole runner is module-scope functions and a lone class for this one entry point would break the file's shape\nfunction runBashInternal(\n command: string,\n cwd: string,\n mode: HookMode,\n aiType: AiType,\n): BlockedResult | null {\n if (isL0CureCommand(command)) {\n logL0CureBypass(command, cwd);\n return null;\n }\n\n const loaded = loadConfigOrAllowInspection(command, cwd);\n // null = the config would not load AND this command only inspects → allow, see the helper.\n if (loaded === null) return null;\n if (loaded.configPath === null)\n return l0FaultAllows(command, aiType) ? null : configMissingBlock(cwd);\n\n const workspaceRoot = path.dirname(loaded.configPath);\n\n // WHICH TREE does this command act on? Not the shell's cwd: a `cd` OUT of the workspace is reset\n // by the harness and one INSIDE it persists, so neither can be assumed (see EffectiveTree).\n // ONE resolver answers this for the guards AND for force-to-root below, so the two can never\n // disagree about which tree you are in.\n const tree = new EffectiveTreeResolver().resolve(command, cwd, workspaceRoot);\n\n if (allowForeignTree(command, tree, workspaceRoot)) return null;\n\n // Honour excludePaths on the bash path too (not just Read/Edit): a command whose effective\n // cwd sits under an excluded tree (e.g. repositories/**) drops the whole guard set — matching how\n // runInternal/runRead treat file paths. The relative path is '' when there is no `cd` (root), which\n // matches no exclusion glob, so a plain command at the repo root is unaffected.\n const governedCwd = bashGovernedPath(tree, workspaceRoot);\n const rules = filterByExcludedPaths(\n filterByMode(new WorkflowHookRules().load(loaded).rules, mode, loaded.ruleRegistry),\n governedCwd,\n loaded.excludePaths,\n );\n const keyless = keylessBashRules(loaded, mode, governedCwd);\n if (rules.length === 0 && keyless.length === 0) return null;\n\n const locationBlock = l1LocationBlock(command, tree, aiType);\n if (locationBlock) return locationBlock;\n\n // Keep the feature-branch-guard cache warm on EVERY command (not just Write/Edit): the AI runs\n // far more bash than edits, so refreshing here means the guard's next file-edit check reads a\n // fresh status. Detached + fire-and-forget — never blocks the command. Only when the guard is\n // loaded (guards/all mode) and enabled, so a project that opted out never triggers git fetches.\n // Keyed on the JUDGED tree, so a worktree's cache is refreshed rather than the primary clone's.\n maybeRefreshMainSync(rules, tree.root, branchStateHangTimeout(loaded.rulesConfig));\n\n const groups = runBashRules([...rules, ...keyless], buildBashContext(command, tree));\n return bashPolicyResult(command, tree, loaded, groups);\n}\n\n// The bash report's subject line. It used to be the literal string `<bash>`, which told the agent\n// nothing; the command itself is what was blocked, so name it — truncated, because a heredoc-bearing\n// command can run to thousands of characters and the violation lines already carry the detail.\n// webpieces-disable no-function-outside-class -- sibling of the module-scope runner helpers; the whole file is functions and a lone class here would break its shape\nfunction commandLabel(command: string): string {\n const oneLine = command.replace(/\\s+/g, ' ').trim();\n const MAX = 100;\n return oneLine.length <= MAX ? oneLine : oneLine.slice(0, MAX) + '…';\n}\n\n// When a push/PR block fires AND the config exempts vendored/nested trees, surface the escape hatch the\n// AI cannot otherwise discover: git/gh run UNGUARDED inside those trees if it cd's there first (each is\n// governed by its own repo, not this one). Scoped to pr-creation-or-push-guard — for the other guards\n// \"cd into an exempt tree\" is not the remedy — and emitted only when such trees are actually configured,\n// so a repo without exemptions never sees the noise.\n//\n// The hint MUST state the precondition, not just the remedy. \"cd into it first\" is true only for a\n// LITERAL cd at the FRONT of the same command; `D=…; cd \"$D\"; git push` lands in the identical\n// directory and does NOT relocate the verdict. That used to be silent, then a near-miss paragraph\n// appended here; it is now misplacedCdBlock, which refuses the command outright — so by the time this\n// footer is reached, any `cd` in the command is already known to be leading and literal. The wording\n// still states the shape, because this is where an agent LEARNS it, before writing the next command.\n// webpieces-disable no-function-outside-class -- sibling of the module-scope runner helpers; the whole file is functions and a lone class here would break its shape\nfunction exemptTreesHint(groups: readonly RuleGroup[], exemptGuards: readonly string[]): string {\n if (exemptGuards.length === 0) return '';\n if (!groups.some((g: RuleGroup): boolean => g.ruleName === 'pr-creation-or-push-guard'))\n return '';\n\n return (\n `\\n\\nℹ️ Working in a nested repo under one of these exempt trees (${exemptGuards.join(', ')})? ` +\n `Put a LITERAL \\`cd\\` at the FRONT of the SAME command — \\`cd /abs/path/to/repo && git push\\` — and git/gh ` +\n `run normally there: the webpieces guards do NOT govern them (each is its own repo).` +\n `\\n \\`cd <literal path> && <work>\\` is the ONE shape that moves where a command is judged. A \\`cd\\` ` +\n `anywhere else in the line, or a non-literal target like \\`cd \"$DIR\"\\`, is refused outright rather than ` +\n `judged from somewhere you did not intend.`\n );\n}\n\n// webpieces-disable no-function-outside-class -- runner result assembly is a pure orchestration helper\nfunction bashPolicyResult(command: string, tree: EffectiveTree, loaded: LoadedConfig, groups: readonly RuleGroup[]): BlockedResult | null {\n const workspaceRoot = path.dirname(loaded.configPath!);\n if (groups.length === 0) {\n // Record the ALLOW only for git/gh commands — the operations the bash guards actually reason\n // about (branch create, commit, push, merge, PR). Skipping ls/cat/grep keeps the audit log\n // focused (the whole point of the log is \"why did/didn't a guard fire?\"). Blocks are always\n // logged below.\n if (/\\b(?:git|gh)\\b/.test(command)) {\n logGuardDecision(\n tree.root,\n new GuardDecision(\n '-',\n 'Bash',\n command,\n branchForLog(tree.root),\n 'ALLOW',\n 'no bash-guard block',\n '-',\n L0_FAULT_NONE,\n MATRIX_L2_UNROWED,\n ),\n );\n }\n return null;\n }\n\n const ruleNames = groups.map((g: RuleGroup): string => g.ruleName).join(',');\n logGuardDecision(\n tree.root,\n new GuardDecision(\n ruleNames,\n 'Bash',\n command,\n branchForLog(tree.root),\n 'BLOCK_AI_CURE',\n 'bash-guard block',\n '-',\n L0_FAULT_NONE,\n MATRIX_L2_UNROWED,\n ),\n );\n const report =\n new ExcludedPathEscapeHint(workspaceRoot, tree.effectiveCwd).render(\n command,\n loaded.excludePaths,\n ) +\n formatReport(commandLabel(command), groups, BASH_SUBJECT) +\n exemptTreesHint(groups, loaded.excludePaths.paths);\n return new BlockedResult(report);\n}\n\n// webpieces-disable no-function-outside-class -- orchestration helper for the explicit foreign-repository exemption\nfunction allowForeignTree(command: string, tree: EffectiveTree, workspaceRoot: string): boolean {\n if (tree.kind === 'foreign') {\n logGuardDecision(\n workspaceRoot,\n new GuardDecision(\n '-',\n 'Bash',\n command,\n branchForLog(workspaceRoot),\n 'ALLOW_EXEMPT',\n 'foreign git repo (out of scope)',\n '-',\n L0_FAULT_NONE,\n new MatrixRef('L1', '1'),\n ),\n );\n return true;\n }\n\n return false;\n}\n"]}
@@ -19,7 +19,7 @@ ROOT="$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd)"
19
19
  BS='\' # one literal backslash, so no \u001b / \n escape sits in this source
20
20
  ESC="${BS}u001b" # the 6 chars: backslash u 0 0 1 b — Claude Code parses \u001b → ESC
21
21
  NL="${BS}n" # the 2 chars: backslash n — parsed as a real newline inside the JSON string
22
- WP_STILL_ALLOWED="Still allowed while this block is up:${NL} - any Read, and on CODEX (no Read tool): a bare read command - cat/head/tail/less/more/bat <file>, or sed -n '1,240p' package.json - with nothing piped, redirected or chained onto it${NL} - any Write/Edit whose target is webpieces.config.json, pnpm-workspace.yaml or package.json${NL} - every command on the L0 allowlist, including the Fix Options below${NL} THIS IS NOT A DEADLOCK - run one YOURSELF now; do not hand it back to the human."
22
+ WP_STILL_ALLOWED="Still allowed while this block is up:${NL} - any Read, and on CODEX (no Read tool): a bare read command - cat/head/tail/less/more/bat <file>, or sed -n '1,240p' package.json - with nothing piped, redirected or chained onto it${NL} - a Write/Edit/MultiEdit or Codex apply_patch of ONLY webpieces.config.json, .webpieces-config/ files, or a tree-root package.json / pnpm-workspace.yaml${NL} - every command on the L0 allowlist, including the Fix Options below${NL} THIS IS NOT A DEADLOCK - run one YOURSELF now; do not hand it back to the human."
23
23
  # The BIN is resolved by walking UP from ROOT (as Node does), and BIN_ROOT records which tree supplied
24
24
  # it — the version-drift guard below compares THIS tree's pin against THAT tree's installed version.
25
25
  BIN_ROOT="$ROOT"
@@ -384,13 +384,39 @@ case "$TOOL" in
384
384
  wp_log "$WP_FAULT" ALLOW-IGNORED
385
385
  exit 0 ;;
386
386
  esac
387
- # The same compiled Node probe is used by the live runner; it requires no installed package.
388
- if printf '%s' "$PAYLOAD" | node -e '/**
389
- * Self-contained Node probe: serialized into the POSIX shim so repairs work with missing packages.
387
+ # THE EDIT ESCAPE (issue #1448) — ONE compiled Node probe for every edit-tool spelling: Claude's
388
+ # Write/Edit/MultiEdit (file_path) and Codex's apply_patch (the patch rides in command; the name may be
389
+ # namespace-qualified). It needs no installed package. Every path the edit touches must be a repair file
390
+ # or the package.json / pnpm-workspace.yaml at a governed tree ROOT (a webpieces.config.json beside
391
+ # it) — a nested project manifest, a Delete, a .. segment or a Move out of scope refuses the WHOLE edit.
392
+ # This arm is TERMINAL (exit 0, the bin never runs), which is why the scope is that narrow. The JS half
393
+ # (isAllowed) calls the same class, so the two halves cannot disagree. Exit 0 = permitted (stdout names
394
+ # the label), 1 = not an edit, 3 = an edit refused (stdout: one line per offending path, for the deny).
395
+ WP_EDIT_REFUSED=""
396
+ WP_EDIT="$(printf '%s' "$PAYLOAD" | node -e '/**
397
+ * Self-contained Node probe: serialized into the POSIX shim so recovery edits work with missing packages.
390
398
  *
391
399
  * A REPAIR FILE is one a config-repair deny can tell the agent to edit, so it is permitted while the
392
400
  * config is invalid: the root `webpieces.config.json`, `.gitignore`, everything under `.webpieces-config/`,
393
401
  * and any owner file `rulePacks` declares elsewhere. Nothing that resolves outside the repository counts.
402
+ *
403
+ * A RECOVERY MANIFEST is the `package.json` / `pnpm-workspace.yaml` at the ROOT of a governed tree (a
404
+ * `webpieces.config.json` sits beside it) — the only two files a version pin or a `patchedDependencies`
405
+ * registration lives in. Every OTHER `package.json` in the repo is ordinary code and is NOT one.
406
+ *
407
+ * THE ONE EDIT ESCAPE (issue #1448). Every L0 deny promises that an edit of webpieces.config.json,
408
+ * pnpm-workspace.yaml or package.json is still allowed. `recoveryVerdict()` is the single predicate
409
+ * behind that promise, for EVERY edit-tool spelling: Claude'\''s Write/Edit/MultiEdit (`file_path`) and
410
+ * Codex'\''s `apply_patch` (`command` holds the patch; the name may arrive namespace-qualified, e.g.
411
+ * `functions.apply_patch`). The sh half of L0 runs this compiled class through `node -e` and the JS half
412
+ * calls it directly, so the two halves cannot answer differently. It used to be answered three ways — a
413
+ * `file_path` scrape in sh, a config-only patch check here, and a `file_path`-only JS predicate — and a
414
+ * Codex rollback of `pnpm-workspace.yaml` matched none of them.
415
+ *
416
+ * ATOMIC: a patch is permitted only when EVERY path it touches is permitted. A Delete is never a
417
+ * recovery edit. A Move is judged on BOTH its source and its destination. A raw path carrying a `..`
418
+ * segment is refused outright (a recovery edit never needs one), and a symlink that resolves outside the
419
+ * repository is refused by `canonical()`.
394
420
  */
395
421
  class ConfigRepairProbe {
396
422
  rootFor(cwd) {
@@ -404,20 +430,117 @@ class ConfigRepairProbe {
404
430
  }
405
431
  return directory;
406
432
  }
407
- isRepairPatch(root, patch) {
408
- const lines = patch.trim().split('\''\n'\'');
409
- if (lines[0] !== '\''*** Begin Patch'\'' || lines.at(-1) !== '\''*** End Patch'\'')
410
- return false;
411
- let targets = 0;
433
+ /**
434
+ * `functions.apply_patch`, `tools.apply_patch`, `codex:apply_patch` → `apply_patch`. Only the Codex
435
+ * edit tool is canonicalized: every other name is returned untouched, so this can never turn an
436
+ * unknown tool into one L0 trusts.
437
+ */
438
+ canonicalTool(toolName) {
439
+ return /^(?:[A-Za-z0-9_-]+[.:/])+apply_patch$/.test(toolName) ? '\''apply_patch'\'' : toolName;
440
+ }
441
+ /**
442
+ * The one question both L0 halves ask about an edit. Returns:
443
+ * - `['\''not-an-edit'\'']` → not an edit tool; L0 has no edit-escape opinion.
444
+ * - `['\''config'\'']` / `['\''manifest'\'']` → every touched path is permitted (`manifest` when at least one
445
+ * is a root manifest — the audit label).
446
+ * - `['\''refused'\'', ...lines]` → an edit that is NOT permitted, one line per offending path.
447
+ */
448
+ recoveryVerdict(cwd, toolName, filePath, command) {
449
+ const tool = this.canonicalTool(toolName);
450
+ let targets;
451
+ if (['\''Write'\'', '\''Edit'\'', '\''MultiEdit'\''].includes(tool)) {
452
+ if (filePath === '\'''\'')
453
+ return ['\''refused'\'', '\''the edit names no file_path'\''];
454
+ targets = [['\''Edit'\'', filePath]];
455
+ }
456
+ else if (tool === '\''apply_patch'\'') {
457
+ const parsed = this.patchTargets(command);
458
+ if (typeof parsed === '\''string'\'')
459
+ return ['\''refused'\'', parsed];
460
+ targets = parsed;
461
+ }
462
+ else {
463
+ return ['\''not-an-edit'\''];
464
+ }
465
+ const refusals = [];
466
+ let manifest = false;
467
+ for (const target of targets) {
468
+ const op = target[0];
469
+ const raw = target[1];
470
+ const kind = this.targetKind(cwd, op, raw);
471
+ if (kind === '\''manifest'\'')
472
+ manifest = true;
473
+ else if (kind !== '\''config'\'')
474
+ refusals.push(`${op} ${raw}: ${kind}`);
475
+ }
476
+ if (refusals.length > 0)
477
+ return ['\''refused'\'', ...refusals];
478
+ return [manifest ? '\''manifest'\'' : '\''config'\''];
479
+ }
480
+ /**
481
+ * Every `[op, rawPath]` an `apply_patch` envelope touches — Add, Update, Delete, and BOTH sides of a
482
+ * Move — or a string saying why the envelope could not be read (fail closed: an envelope this does
483
+ * not understand is never partially judged).
484
+ */
485
+ patchTargets(patch) {
486
+ const lines = patch.replace(/\r\n/g, '\''\n'\'').trim().split('\''\n'\'');
487
+ if (lines[0]?.trim() !== '\''*** Begin Patch'\'' || lines.at(-1)?.trim() !== '\''*** End Patch'\'')
488
+ return '\''the patch has no *** Begin Patch / *** End Patch envelope'\'';
489
+ const targets = [];
412
490
  for (const line of lines.slice(1, -1)) {
413
491
  if (!line.startsWith('\''*** '\''))
414
492
  continue;
415
- const match = /^\*\*\* (?:Add|Update) File: (.+)$/.exec(line);
416
- if (!match || !this.isRepairFile(root, match[1]))
493
+ const match = /^\*\*\* (Add|Update|Delete) File: (.+)$/.exec(line) ?? /^\*\*\* (Move) to: (.+)$/.exec(line);
494
+ if (match) {
495
+ targets.push([match[1], match[2].trim()]);
496
+ continue;
497
+ }
498
+ if (line.trim() === '\''*** End of File'\'')
499
+ continue;
500
+ return `unrecognised patch directive ${line.trim()}`;
501
+ }
502
+ return targets.length > 0 ? targets : '\''the patch names no file'\'';
503
+ }
504
+ /** `config`, `manifest`, or the reason this one path is not a recovery target. */
505
+ targetKind(cwd, op, raw) {
506
+ const path = require('\''node:path'\'');
507
+ if (op === '\''Delete'\'')
508
+ return '\''a Delete is never a recovery edit'\'';
509
+ if (raw === '\'''\'' || raw.includes('\''\0'\''))
510
+ return '\''an empty or malformed path'\'';
511
+ if (raw.split(/[\\/]/).includes('\''..'\''))
512
+ return '\''a .. path segment is refused - name the file directly'\'';
513
+ const fs = require('\''node:fs'\'');
514
+ const absolute = path.resolve(cwd, raw);
515
+ // The governed tree the FILE sits in (main clone or any worktree); with none above it, the
516
+ // session'\''s own tree — so a path outside every governed tree is judged against, and contained
517
+ // by, the repository the call came from.
518
+ const own = this.rootFor(path.dirname(absolute));
519
+ const root = fs.existsSync(path.join(own, '\''webpieces.config.json'\'')) ? own : this.rootFor(cwd);
520
+ if (this.isRepairFile(root, absolute))
521
+ return '\''config'\'';
522
+ if (this.isRecoveryManifest(root, absolute))
523
+ return '\''manifest'\'';
524
+ return '\''not webpieces.config.json, a .webpieces-config/ file, or the package.json / pnpm-workspace.yaml at a governed tree root'\'';
525
+ }
526
+ /** The root `package.json` / `pnpm-workspace.yaml` of a governed tree, resolved inside the repository. */
527
+ isRecoveryManifest(root, filename) {
528
+ const toError = this.error;
529
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- bootstrap cannot trust package imports; an unresolvable path is simply not a manifest
530
+ try {
531
+ const fs = require('\''node:fs'\''), path = require('\''node:path'\'');
532
+ const target = this.canonical(root, path.resolve(root, filename));
533
+ if (!['\''package.json'\'', '\''pnpm-workspace.yaml'\''].includes(path.basename(target)))
417
534
  return false;
418
- targets += 1;
535
+ return fs.existsSync(path.join(path.dirname(target), '\''webpieces.config.json'\''));
536
+ // webpieces-disable catch-must-propagate -- a path that escapes the repository IS the refusal verdict; the error carries nothing a caller could act on
537
+ // webpieces-disable no-any-unknown -- a path that escapes the repository throws from canonical()
538
+ }
539
+ catch (err) {
540
+ const error = toError(err);
541
+ void error;
542
+ return false;
419
543
  }
420
- return targets > 0;
421
544
  }
422
545
  isRepairFile(root, filename) {
423
546
  const toError = this.error;
@@ -445,6 +568,7 @@ class ConfigRepairProbe {
445
568
  return true;
446
569
  }
447
570
  return false;
571
+ // webpieces-disable catch-must-propagate -- an escaping path or malformed declaration IS the refusal verdict; the error carries nothing a caller could act on
448
572
  // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution
449
573
  }
450
574
  catch (err) {
@@ -474,22 +598,21 @@ class ConfigRepairProbe {
474
598
  return err instanceof Error ? err : new Error(String(err));
475
599
  }
476
600
  }
477
- const probe = new ConfigRepairProbe(); const root = probe.rootFor(process.argv[1]); const payload = JSON.parse(require('\''node:fs'\'').readFileSync(0, '\''utf8'\'')); const input = payload.tool_input; const tool = payload.tool_name; const allowed = ['\''Write'\'','\''Edit'\'','\''MultiEdit'\''].includes(tool) && input && typeof input.file_path === '\''string'\'' ? probe.isRepairFile(root, input.file_path) : tool === '\''apply_patch'\'' && input && typeof input.command === '\''string'\'' && probe.isRepairPatch(root, input.command); if (!allowed) process.exitCode = 1;' "$WP_CWD" >/dev/null 2>&1; then
478
- wp_log "$WP_FAULT" ALLOW-CONFIG
601
+ const payload = JSON.parse(require('\''node:fs'\'').readFileSync(0, '\''utf8'\'')); const input = payload.tool_input || {}; const verdict = new ConfigRepairProbe().recoveryVerdict(typeof payload.cwd === '\''string'\'' && payload.cwd !== '\'''\'' ? payload.cwd : process.argv[1], String(payload.tool_name || '\'''\''), typeof input.file_path === '\''string'\'' ? input.file_path : '\'''\'', typeof input.command === '\''string'\'' ? input.command : '\'''\''); if (verdict[0] === '\''not-an-edit'\'') process.exitCode = 1; else if (verdict[0] === '\''refused'\'') { process.stdout.write(verdict.slice(1).join('\''\n'\'')); process.exitCode = 3; } else process.stdout.write(verdict[0]);' "$WP_CWD" 2>/dev/null)"
602
+ WP_EDIT_RC=$?
603
+ if [ "$WP_EDIT_RC" = 0 ]; then
604
+ if [ "$WP_EDIT" = manifest ]; then
605
+ wp_log "$WP_FAULT" ALLOW-MANIFEST # the pin / patch registration must be editable from inside the block
606
+ else
607
+ wp_log "$WP_FAULT" ALLOW-CONFIG
608
+ fi
479
609
  exit 0
480
610
  fi
481
- case "$FILE" in
482
- */pnpm-workspace.yaml|pnpm-workspace.yaml|*/package.json|package.json)
483
- # A manifest AT THE ROOT OF A GOVERNED TREE, which is the only place the version pin lives. The test
484
- # is the sibling webpieces.config.json — TRACKED, so the main clone has one and every worktree has its
485
- # own — and NOT $ROOT, which names whichever tree supplied this shim and would deny the other's.
486
- # Basename alone would be far worse here than in the JS half: this arm is TERMINAL (exit 0, the bin
487
- # never runs), so every packages/**/package.json would be editable with nothing judging it.
488
- if [ -f "$(dirname -- "$FILE")/webpieces.config.json" ]; then
489
- wp_log "$WP_FAULT" ALLOW-MANIFEST # raising the pin must be typable from inside the block
490
- exit 0
491
- fi ;;
492
- esac
611
+ if [ "$WP_EDIT_RC" = 3 ]; then
612
+ # One deny line per offending path. tr strips the bytes a JSON string may not carry raw.
613
+ WP_EDIT_REFUSED="$(printf '%s\n' "$WP_EDIT" | tr -d '"\\\t\r' | while IFS= read -r WP_L; do printf '%s - %s' "$NL" "$WP_L"; done)"
614
+ WP_STILL_ALLOWED="Your $TOOL edit was REFUSED as a whole - not every file it touches is a recovery edit:${WP_EDIT_REFUSED}${NL}${NL}${WP_STILL_ALLOWED}"
615
+ fi
493
616
  if printf '%s' "$CMD" | grep -Eq '^(cd[[:space:]]+([A-Za-z0-9._/@~+-]+|'\''[^'\'']+'\'')[[:space:]]*&&[[:space:]]*)?((pnpm|npm)[[:space:]]+(install|i)([[:space:]]+--[A-Za-z][A-Za-z0-9=._/@:-]*)*|rm[[:space:]]+-rf[[:space:]]+(\./)?node_modules/?([[:space:]]*&&[[:space:]]*(pnpm|npm)[[:space:]]+(install|i)([[:space:]]+--[A-Za-z][A-Za-z0-9=._/@:-]*)*)?|git[[:space:]]+fetch([[:space:]]+(--)?[A-Za-z0-9][A-Za-z0-9=._/@:-]*)*|git[[:space:]]+checkout[[:space:]]+main[[:space:]]*&&[[:space:]]*git[[:space:]]+pull[[:space:]]+origin[[:space:]]+main|(pnpm|npm|npx)([[:space:]]+(exec|run))?[[:space:]]+wp-upgrade-shim|cp[[:space:]]+(\./)?node_modules/@webpieces/agent-workflow-rules/templates/ai-hook\.sh[[:space:]]+(\./)?\.claude/webpieces/ai-hook\.sh|(pnpm|npm|npx)([[:space:]]+(exec|run))?[[:space:]]+wp-prune-unknown-config|(pnpm|npm|npx)([[:space:]]+(exec|run))?[[:space:]]+wp-migrate-dirs([[:space:]]+--stage)?|(pnpm|npm|npx)([[:space:]]+(exec|run))?[[:space:]]+wp-install-ai-hooks([[:space:]]+--[A-Za-z][A-Za-z0-9=._/@:-]*)*|(pnpm|npm)[[:space:]]+add([[:space:]]+(-[A-Za-z]|--[A-Za-z][A-Za-z0-9=._/@:-]*))*[[:space:]]+@webpieces/agent-workflow-rules(@[A-Za-z0-9._+-]+)?([[:space:]]+(-[A-Za-z]|--[A-Za-z][A-Za-z0-9=._/@:-]*))*|(pwd|git[[:space:]]+(status|log|diff|show|branch|rev-parse)|git[[:space:]]+worktree[[:space:]]+list)([[:space:]]+(--)?[A-Za-z0-9][A-Za-z0-9=._/@:-]*)*)([[:space:]]+2>(&1|/dev/null))?([[:space:]]*\|[[:space:]]*(tail|head)([[:space:]]+-(n[[:space:]]+)?[0-9]+)?)?[[:space:]]*$'; then
494
617
  wp_log "$WP_FAULT" ALLOW-CURE # record the self-heal we let through (re-enables the guards)
495
618
  exit 0 # allow the cure so the assistant can break the deadlock
@@ -554,7 +677,7 @@ elif [ -n "$DRIFT_PKG" ]; then
554
677
  if [ "$DRIFT_DIR" = older ]; then
555
678
  # The HEADLINE, kept in its own variable so DENY_EMIT_SH can paint ONLY it red (see there).
556
679
  WP_HEAD="❌ webpieces ai-hooks blocked this call: webpieces version drift."
557
- REASON="$WP_HEAD${NL}${NL}[version-drift] (layer=L0 fault=D row=3, 1 violation)${NL} package.json pins $DRIFT_PKG@$DRIFT_DECLARED but node_modules has $DRIFT_INSTALLED${NL} → node_modules is OLDER, so the pin is what you want. Every OTHER tool call is BLOCKED until the two agree.${NL} → matrix row 3: fault=D present / on the allowlist? no -> BLOCK. Those are the same coordinates the audit line carries (layer=L0 row=3 fault=D) and the same row webpieces.guard-matrix.md prints.${NL}${NL}${WP_STILL_ALLOWED}${NL}${NL} Fix Option 1: (preferred) the only cure - it makes node_modules match the pin${NL} run EXACTLY: 'pnpm install'${NL}${NL}Run it EXACTLY as written - the allowlist matches the whole command, so appending anything (even && git status) makes it a different command and it is rejected; that is not the guard blocking its own cure. Only these may be added: a leading cd <dir> && (single-quote a path containing spaces), a trailing 2>&1, and | tail -N."
680
+ REASON="$WP_HEAD${NL}${NL}[version-drift] (layer=L0 fault=D row=3, 1 violation)${NL} package.json pins $DRIFT_PKG@$DRIFT_DECLARED but node_modules has $DRIFT_INSTALLED${NL} → node_modules is OLDER, so the pin is what you want. Every OTHER tool call is BLOCKED until the two agree.${NL} → matrix row 3: fault=D present / on the allowlist? no -> BLOCK. Those are the same coordinates the audit line carries (layer=L0 row=3 fault=D) and the same row webpieces.guard-matrix.md prints.${NL}${NL}${WP_STILL_ALLOWED}${NL}${NL} Fix Option 1: (preferred) it makes node_modules match the pin${NL} run EXACTLY: 'pnpm install'${NL} Fix Option 2: 'pnpm install' itself FAILED (the pinned version is not on the registry yet, or ERR_PNPM_UNUSED_PATCH from a stale patchedDependencies entry)? Re-running it fails the same way. Repair the manifests instead - roll the pin in $ROOT/pnpm-workspace.yaml back to $DRIFT_INSTALLED, or fix the patchedDependencies entry in $ROOT/package.json or $ROOT/pnpm-workspace.yaml - with Write/Edit (Claude Code) or apply_patch (Codex); that edit is ALLOWED while this block is up. Then run 'pnpm install' again.${NL}${NL}Run it EXACTLY as written - the allowlist matches the whole command, so appending anything (even && git status) makes it a different command and it is rejected; that is not the guard blocking its own cure. Only these may be added: a leading cd <dir> && (single-quote a path containing spaces), a trailing 2>&1, and | tail -N."
558
681
  else
559
682
  # NEWER, or undecidable — the same choices apply either way, so the only thing the ambiguous
560
683
  # case changes is the claim about which side is stale.