@webpieces/ai-hook-rules 0.4.834 → 0.4.836

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.
Files changed (64) hide show
  1. package/package.json +3 -2
  2. package/src/adapters/agent-adapters.d.ts +1 -1
  3. package/src/adapters/agent-adapters.js.map +1 -1
  4. package/src/adapters/agent-response.d.ts +2 -3
  5. package/src/adapters/agent-response.js +8 -54
  6. package/src/adapters/agent-response.js.map +1 -1
  7. package/src/adapters/claude-code-adapter.d.ts +1 -1
  8. package/src/adapters/claude-code-adapter.js +6 -6
  9. package/src/adapters/claude-code-adapter.js.map +1 -1
  10. package/src/adapters/codex-adapter.d.ts +1 -1
  11. package/src/adapters/codex-adapter.js +3 -3
  12. package/src/adapters/codex-adapter.js.map +1 -1
  13. package/src/adapters/codex-subagent-guard.d.ts +1 -1
  14. package/src/adapters/codex-subagent-guard.js.map +1 -1
  15. package/src/adapters/detect-ai.d.ts +1 -1
  16. package/src/adapters/detect-ai.js.map +1 -1
  17. package/src/adapters/guards-hook.js +6 -5
  18. package/src/adapters/guards-hook.js.map +1 -1
  19. package/src/adapters/hook-core.d.ts +2 -2
  20. package/src/adapters/hook-core.js +2 -2
  21. package/src/adapters/hook-core.js.map +1 -1
  22. package/src/adapters/hook-pipeline-evaluator.d.ts +5 -0
  23. package/src/adapters/hook-pipeline-evaluator.js +18 -0
  24. package/src/adapters/hook-pipeline-evaluator.js.map +1 -0
  25. package/src/adapters/review-identity-stamper.d.ts +1 -1
  26. package/src/adapters/review-identity-stamper.js.map +1 -1
  27. package/src/adapters/rules-hook.js +6 -5
  28. package/src/adapters/rules-hook.js.map +1 -1
  29. package/src/bin/hook-registration.d.ts +1 -1
  30. package/src/bin/hook-registration.js.map +1 -1
  31. package/src/bin/l0-decide.d.ts +1 -1
  32. package/src/bin/l0-decide.js.map +1 -1
  33. package/src/bin/l0-entry.d.ts +1 -1
  34. package/src/bin/l0-entry.js.map +1 -1
  35. package/src/bin/shim-audit-log.js +2 -2
  36. package/src/bin/shim-audit-log.js.map +1 -1
  37. package/src/core/ai-type-context.d.ts +1 -1
  38. package/src/core/ai-type-context.js +2 -2
  39. package/src/core/ai-type-context.js.map +1 -1
  40. package/src/core/apply-patch-parse.d.ts +1 -1
  41. package/src/core/apply-patch-parse.js +4 -4
  42. package/src/core/apply-patch-parse.js.map +1 -1
  43. package/src/core/runner.d.ts +1 -1
  44. package/src/core/runner.js.map +1 -1
  45. package/src/core/types.d.ts +2 -16
  46. package/src/core/types.js +5 -26
  47. package/src/core/types.js.map +1 -1
  48. package/src/core/version-sync.d.ts +1 -1
  49. package/src/core/version-sync.js.map +1 -1
  50. package/src/index.d.ts +1 -2
  51. package/src/index.js +1 -12
  52. package/src/index.js.map +1 -1
  53. package/src/adapters/hook-app.d.ts +0 -61
  54. package/src/adapters/hook-app.js +0 -110
  55. package/src/adapters/hook-app.js.map +0 -1
  56. package/src/adapters/hook-outcome.d.ts +0 -46
  57. package/src/adapters/hook-outcome.js +0 -60
  58. package/src/adapters/hook-outcome.js.map +0 -1
  59. package/src/adapters/hook-ports.d.ts +0 -57
  60. package/src/adapters/hook-ports.js +0 -90
  61. package/src/adapters/hook-ports.js.map +0 -1
  62. package/src/core/agent-event.d.ts +0 -81
  63. package/src/core/agent-event.js +0 -75
  64. package/src/core/agent-event.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"hook-core.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/adapters/hook-core.ts"],"names":[],"mappings":";;AAmOA,8DAKC;AAoFD,kCA6DC;;AAzXD,mDAA6B;AAE7B,2CAAuD;AACvD,iEAAsE;AACtE,yDAAuE;AACvE,uDAAkI;AAClI,iEAAmE;AACnE,qDAAsD;AACtD,0DAA8E;AAC9E,yCAA2G;AAE3G,+CAA2C;AAC3C,qDAAoE;AACpE,iDAA6D;AAC7D,mDAAmE;AACnE,qDAAiD;AACjD,2CAA2C;AAC3C,iEAA2F;AAC3F,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CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC;AACvE,CAAC;AAED;;;;;;;;;GASG;AACH,oLAAoL;AACpL,SAAS,YAAY,CAAC,KAAY,EAAE,KAA4B;IAC5D,IAAI,KAAK,YAAY,qBAAa,EAAE,CAAC;QACjC,OAAO,IAAA,4BAAW,EAAC,KAAK,EAAE,IAAA,kCAAmB,EAAC,KAAK,CAAC,EAAE,YAAY,CAAC,CAAC;IACxE,CAAC;IACD,IAAI,KAAK,YAAY,qBAAa,EAAE,CAAC;QACjC,OAAO,IAAA,4BAAW,EAAC,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE,qBAAqB,CAAC,CAAC;IACpE,CAAC;IACD,OAAO,IAAA,4BAAW,EAAC,KAAK,EAAE,0DAA0D,KAAK,CAAC,OAAO,EAAE,EAAE,YAAY,CAAC,CAAC;AACvH,CAAC","sourcesContent":["import * as path from 'path';\n\nimport { run, runBash, runRead } from '../core/runner';\nimport { branchStateHangTimeoutFor } from '../core/main-sync-timeout';\nimport { logRejection, extractRuleNames } from '../core/rejection-log';\nimport { logGuardDecision, GuardDecision, branchForLog, invocationLog, MATRIX_L0_BLOCK, matrixL2Row } from '../core/decision-log';\nimport { triggerMainSyncRefresh } from '../core/main-sync-refresh';\nimport { CONFIG_FILENAME } from '../core/load-config';\nimport { RepoRootFinder, renderRuleFailForAi } from '@webpieces/rules-config';\nimport { NormalizedToolInput, InformAiError, RuleFailError, HookMode, BlockedResult } from '../core/types';\nimport { AgentHookEvent, AiType, FileOperation } from '../core/agent-event';\nimport { toError } from '../core/to-error';\nimport { emitDeny, emitAllow, denyOutcome } from './agent-response';\nimport { HookOutcome, HookTerminated } from './hook-outcome';\nimport { AgentPayload, AgentPayloadParser } from './agent-payload';\nimport { AgentAdapters } from './agent-adapters';\nimport { detectAiType } from './detect-ai';\nimport { CodexSubagentSharedTreeGuard, CODEX_SUBAGENT_RULE } from './codex-subagent-guard';\nimport { ReviewIdentityStamper } from './review-identity-stamper';\nimport { governingShimRoot, isAllowed, installedShimRulesVersion } from '../bin/shim';\nimport { managedSurfaceDrift } from '../bin/hook-registration';\nimport { shimStaleDenyReason } from '../bin/shim-deny-reason';\nimport { writeGuardMatrixDoc, guardMatrixPointer } from '../core/l0-matrix';\nimport { logStream, StreamIdentity } from '../core/log-stream';\nimport { aiTypeContext } from '../core/ai-type-context';\nimport { L0_FAULT_SHIM_STALE, L0_FAULT_NONE } from '../core/l0-fault-codes';\n\n// Which category of rules this hook invocation runs. The hook is split into two independently\n// installable PreToolUse hooks; each runs ONE category (the runner filters by it), and both can\n// receive file AND bash payloads:\n// - 'rules' → code-style rules (file/edit scope). Bash payloads pass through (no code rules apply).\n// - 'guards' → hookGuards section: bash git/PR guards on Bash AND file guards (feature-branch-guard)\n// on Write/Edit, PLUS a log-and-allow audit of Read. Matcher is Write|Edit|MultiEdit|Bash|Read.\n// - 'all' → both categories, used by the openclaw plugin adapter (a single before_tool_call hook).\nexport type { HookMode };\n\nconst ADAPTERS = new AgentAdapters();\nconst SUBAGENT_GUARD = new CodexSubagentSharedTreeGuard();\nconst REVIEW_IDENTITY_STAMPER = new ReviewIdentityStamper();\n\n// The rule name for a block's audit line: the FIRST rule the report cites, or `fallback` when the\n// report opens with no `[rule]` header (a hand-written guard message). Comma-joined when a report\n// cites several, so `rule=` never silently drops one.\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction blockingRule(report: string, fallback: string): string {\n const names = extractRuleNames(report);\n return names.length > 0 ? names.join(',') : fallback;\n}\n\n// webpieces-disable no-function-outside-class -- sibling of handleRead()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction handleBash(event: AgentHookEvent, cwd: string, mode: HookMode): never {\n const command = event.bash === null ? '' : event.bash.command;\n if (command.trim() === '') { emitAllow(); }\n\n // READ PARITY, and it can only ever be reached from a Codex event: the adapter leaves `reads`\n // empty for Claude Code, which has a real `Read` tool and its own fast path. A Codex read arrives\n // as `Bash` running a pager, so without this the read guard and the `calls/` audit trail see none\n // of them. The command is STILL run through the bash guards below — this adds a verdict, it never\n // replaces one.\n for (const readPath of event.reads) {\n handleRead(event, readPath, cwd, mode);\n }\n\n // The HARNESS travels with the command. Fault C and fault Y are decided inside the runner, and\n // both consult the L0 allowlist — which since the gated entry exists cannot be asked without\n // knowing who is calling. `event.aiType` is the adapter's answer, the same one that routed this\n // call to the Codex read-parity loop above.\n const result = runBash(command, cwd, mode, event.aiType);\n if (!result) {\n // ALLOWED — so if this call submits a reviewer verdict, record who is submitting it before the\n // command runs. `wp-write-review` cannot learn that from its env (see ReviewIdentityStamper).\n REVIEW_IDENTITY_STAMPER.stamp(event, command, cwd);\n emitAllow();\n }\n // NO DECISION LINE HERE. This used to write a generic `bash-guard` line because a Bash deny once\n // had no audit trail at all — but every layer now records its own: L1 into `L1-location/` with its\n // row, L2's guards into `L2-decisions/` with their rule and cache, and emitDeny below stamps the\n // call-level outcome onto `calls/`. So this was the THIRD line for one block, and the worst of the\n // three: it re-resolved the root from `cwd` via RepoRootFinder, which is not necessarily the tree\n // the guard actually judged, so a `cd`-relocated command scattered one block across two different\n // `.webpieces` directories.\n //\n // Bash deny → the event's kind is 'Bash', so denyJson adds the ANSI-red systemMessage (the only\n // field a Bash deny shows the human; permissionDecisionReason is invisible on Bash). See\n // agent-response.ts.\n emitDeny(event, result.report, blockingRule(result.report, 'bash-guard'), result.fault);\n}\n\n/**\n * The read-scoped guard pass. Returns normally to ALLOW; only calls emitDeny when the guard fires.\n *\n * Wrapped in its own catch that swallows into an allow. Every other path in this hook fails CLOSED,\n * and that is right for edits and shell commands — but a crash here would block the agent from\n * READING, which includes reading webpieces.config.json to turn the offending guard off. So this one\n * path deliberately inverts the policy: a broken read-guard degrades to a no-op, never to a wedge.\n */\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction handleRead(event: AgentHookEvent, filePath: string, cwd: string, mode: HookMode): void {\n if (filePath === '') return;\n let result: BlockedResult | null = null;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n result = runRead(filePath, cwd, mode);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return; // fail OPEN — see the doc comment\n }\n if (!result) return;\n logRejection('Read', new NormalizedToolInput(filePath, []), result, cwd);\n emitDeny(event, result.report, blockingRule(result.report, 'read-guard'), result.fault);\n}\n\n/**\n * Read-only tools (Read): audit-log, warm the main-sync cache, then run the ONE read-scoped guard\n * (read-stale-guard) and allow. Runs BEFORE the general rule engine — no code-style rule ever sees a\n * Read, and the only way this path can deny is a stale `main`. The audit trail still records every\n * file the AI opened (see setup.ts).\n *\n * Returns normally ONLY when the event is not a Read; otherwise it ends the invocation.\n */\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction handleReadFastPath(event: AgentHookEvent, cwd: string, mode: HookMode): void {\n if (event.kind !== 'Read') return;\n const readPath = event.reads.length > 0 ? event.reads[0] : '';\n if (mode !== 'rules') {\n invocationLog.begin(cwd, event.rawToolName, readPath);\n // Reads vastly outnumber edits, so refreshing here is what actually keeps the shared\n // main-sync cache warm for feature-branch-guard. Detached; never slows the read.\n triggerMainSyncRefresh(cwd, branchStateHangTimeoutFor(cwd));\n }\n handleRead(event, readPath, cwd, mode);\n emitAllow();\n}\n\n/**\n * The file/edit pipeline, run once per file the call touches.\n *\n * `event.files` is a LIST because ONE Codex `apply_patch` carries many files with mixed operations.\n * A Claude Code event always has exactly one entry, so the loop runs once and the behaviour is the\n * single-file behaviour it has always had.\n */\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleRead() in this module; the adapter is module-scope functions by design\nfunction handleFileTool(event: AgentHookEvent, cwd: string, mode: HookMode): never {\n if (event.files.length === 0) { emitAllow(); }\n\n // A Codex SUBAGENT writing into the tree it shares with its coordinator. Returns null for every\n // Claude Code event — that harness can hand a subagent its own worktree, and does.\n const subagentBlock = SUBAGENT_GUARD.check(event, new RepoRootFinder().resolveRepoRoot(cwd));\n if (subagentBlock) {\n emitDeny(event, subagentBlock.report, CODEX_SUBAGENT_RULE, subagentBlock.fault);\n }\n\n for (const file of event.files) {\n handleOneFile(event, file, cwd, mode);\n }\n emitAllow();\n}\n\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction handleOneFile(event: AgentHookEvent, file: FileOperation, cwd: string, mode: HookMode): void {\n const input = file.input;\n\n // Always allow edits to webpieces.config.json — it's the fix target when the config is broken.\n // This returns BEFORE run(), so feature-branch-guard never sees a config edit; record that so the\n // audit trail explains why a config edit on a bad branch was not blocked (see decision-log.ts).\n if (path.basename(input.filePath) === CONFIG_FILENAME) {\n if (mode !== 'rules') {\n // `.webpieces/` (the decision log + sync cache these two calls write) lives at the repo\n // root, not the AI's cwd — resolve it so a config edit from a subdir doesn't create a\n // stray `<subdir>/.webpieces` tree.\n const root = new RepoRootFinder().resolveRepoRoot(cwd);\n logGuardDecision(\n root,\n new GuardDecision('feature-branch-guard', file.toolKind, input.filePath, branchForLog(root), 'ALLOW_EXEMPT', 'config-bypass (feature-branch-guard skipped)', '-', L0_FAULT_NONE, matrixL2Row('config-bypass (feature-branch-guard skipped)')),\n );\n // The guard's own refresh trigger lives inside its check(), which we skip here — so warm\n // the cache directly, otherwise a session that only edits webpieces.config.json never\n // refreshes the sync status. Fire-and-forget; never blocks the edit.\n triggerMainSyncRefresh(root, branchStateHangTimeoutFor(cwd));\n }\n return;\n }\n\n const result = run(file.toolKind, input, cwd, mode);\n if (!result) return;\n\n logRejection(file.toolKind, input, result, cwd);\n // File-tool deny → the event's kind is 'File', so denyJson omits systemMessage (the reason\n // already renders red natively for these tools). See agent-response.ts.\n emitDeny(event, result.report, blockingRule(result.report, 'file-guard'), result.fault);\n}\n\n// What a stale committed shim lets through — now a thin adapter over the ONE L0 allowlist (isAllowed in\n// ../bin/shim), not a list of its own. A stale shim must NEVER trap the actions needed to recover: the\n// original \"block everything but the cures\" version also shadowed the always-allowed\n// webpieces.config.json edit (handleFileTool) and blocked reads, so a repo that ALSO needed its config\n// fixed would deadlock — blocked from editing the one file whose edit is normally always allowed, and\n// blocked from reading it to know how.\n//\n// It used to carry its OWN narrower list (isShimCureCommand: the three shim cures only), and that\n// narrowness was a defect, not a safety property: `pnpm install` and `git pull` — the two commands that\n// resolve the version disagreement underneath a stale shim — were denied. Consulting the shared\n// allowlist fixes that by construction.\n//\n// What is NOT a defect, and must not be \"fixed\": those cures rewrite the committed shim from the\n// INSTALLED binary's renderShim(), overwriting whatever was there. That is the invariant, not\n// collateral damage. The shim (D/X/K, in POSIX sh, pre-binary) and this binary (S/C/Y, in JS) are two\n// halves of ONE L0 and they exchange assumptions — the shim parses file_path and carries ALLOW-READ /\n// ALLOW-CONFIG entries this binary relies on. Pair a binary with a shim rendered by a DIFFERENT\n// release and L0 acquires holes that nothing reports. So the rule is absolute: the committed shim\n// equals renderShim() of the binary in node_modules, and a cure that forces that is the cure working.\n// See healShim's header, which states the same invariant from the other side.\n//\n// Corollary for anyone regenerating the shim in a webpieces PR: commit `templates/ai-hook.sh` (source,\n// locked to renderShim() by unit test) and leave `.claude/webpieces/ai-hook.sh` (generated artifact)\n// alone. In THIS repo the local source runs ahead of the pinned node_modules, so committing a shim\n// rendered from local source produces a commit whose shim and whose @webpieces pin come from different\n// releases — precisely the mismatch above. The artifact heals on the next upgrade; that is its job.\n//\n// - 'allow-cure' → a Bash cure on the allowlist: emitAllow directly, bypassing the git guards.\n// - 'pass' → a recovery action the normal flow already permits, so fall THROUGH and let it: ANY\n// Read (you must read to know how to fix — see handleRead, which itself fails open),\n// or an edit to webpieces.config.json (the always-allowed recovery target).\n// - 'deny' → all OTHER work: blocked until the committed shim matches renderShim() again.\nexport type ShimStaleDecision = 'allow-cure' | 'pass' | 'deny';\n// webpieces-disable no-function-outside-class -- pure decision helper beside the adapter's other module-scope functions; exported for direct unit testing.\nexport function shimStaleRecoveryDecision(toolName: string, command: string, filePath: string, aiType: AiType): ShimStaleDecision {\n const allowed = isAllowed(toolName, command, filePath, aiType);\n if (allowed === 'pass') return 'pass';\n if (allowed === 'allow') return 'allow-cure';\n return 'deny';\n}\n\n// MANAGED-HOOK-SURFACE self-guard, moved here from the rendered shim (2026-07-24) and widened from one\n// file to three (2026-08-07). The committed\n// .claude/webpieces/ai-hook.sh is webpieces-MANAGED and generated from renderShim(); if it no longer\n// matches, it was reverted / hand-edited / predates this binary, so its OWN fail-closed logic can't be\n// trusted. We are the CURRENT binary from node_modules — the trustworthy party — so WE decide here\n// instead of the (possibly stale) shim. It used to `cmp` itself inside the shim: a double-edged trap,\n// since the check lived in the very file it guarded and a fix could only ship by regenerating that\n// file. Now we fail closed on all real WORK while always leaving the recovery path open (see\n// shimStaleRecoveryDecision): the whole L0 allowlist, any Read, and editing webpieces.config.json. We deny +\n// tell the AI; we do NOT silently rewrite the file under it. 'rules' hook skips it (guards owns the\n// shim). Returns normally (pass / nothing to do) or exits via emitAllow/emitDeny.\n//\n// It asks the allowlist about the RAW WIRE FIELDS, not about the normalized event, and that ordering is\n// deliberate: L0 has to hold on a tree too broken to trust anything above it, including the adapters.\n// The raw fields are the same key names in both harnesses (measured), so one reading serves both, and\n// the answer cannot change because a normalizer changed. `event` is here only to decorate the deny.\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction enforceCommittedShim(payload: AgentPayload, event: AgentHookEvent, cwd: string, mode: HookMode): void {\n // ONE root for the whole decision, resolved from the RUNNING MODULE (governingShimRoot), never from\n // `cwd`: the shim file we compare and the renderShim() we compare it TO must come from the same\n // install, or the check straddles two trees and can never converge (see governingShimRoot's header).\n // `cwd` still selects where the L0 matrix doc is dropped — that is a \"where does the AI read\" question,\n // not part of the judgement.\n const shimRoot = governingShimRoot();\n if (mode === 'rules') return;\n // WHICH of the managed things moved — ai-hook.sh, either harness's hook registration\n // (.claude/settings.json, .codex/hooks.json), or the Claude settings' managed env entry (the\n // Bash-cwd pin that keeps a guard's verdict independent of where an earlier `cd` left the shell;\n // see managed-env.ts). Nothing validated the registration before it joined this\n // fault, so a settings file left on a superseded form silently changed WHO GOVERNS, with no signal\n // anywhere — which is the whole reason the registration is a drift surface and not just an install\n // step.\n const drifted = managedSurfaceDrift(shimRoot);\n if (drifted.length === 0) return;\n // The harness comes from the RAW envelope too — `detectAiType` asks one question of one key, so it\n // is as trustworthy here as the wire fields beside it, and it is the PRECISE test the shim's sh half\n // can only approximate. Reading it off the normalized event instead would put a normalizer between\n // L0 and its decision, which is the coupling the paragraph above exists to refuse.\n const decision = shimStaleRecoveryDecision(\n payload.tool_name, payload.tool_input.command ?? '', payload.tool_input.file_path ?? '',\n detectAiType(payload));\n if (decision === 'pass') return;\n if (decision === 'allow-cure') emitAllow();\n // Drop the L0 matrix doc where the AI can read it and point the deny at it — a Read is entry 1 of\n // the same allowlist, so the pointer is always followable. Best-effort: no doc → no pointer.\n const root = new RepoRootFinder().resolveRepoRoot(cwd);\n const docPath = writeGuardMatrixDoc(root);\n // WRITE THE AUDIT LINE HERE. This block happens BEFORE invocationLog.begin() — it has to, since a\n // stale shim invalidates everything downstream — so emitDeny's flush finds nothing pending and an\n // `S` storm left NO trace at all: the one fault most likely to block twenty consecutive tool calls\n // was the one fault the trail could not show. A decision line is the fix that costs no reordering.\n const target = payload.tool_input.command ?? payload.tool_input.file_path ?? '';\n logGuardDecision(\n root,\n new GuardDecision('committed-shim-stale', payload.tool_name, target, branchForLog(root), 'BLOCK_AI_CURE', 'L0 fault S (committed shim != renderShim)', '-', L0_FAULT_SHIM_STALE, MATRIX_L0_BLOCK),\n );\n // L0 fault S in GUARD_MATRIX.md's codebook — named as the blocking rule so the invocation line\n // says WHAT stopped the call, not merely that something did, and stamped as `fault=S` so the same\n // grep finds it here as in the sh half's `L0-shim/` stream.\n // A subagent is discriminated by `agent_id`, which BOTH harnesses populate on stdin only off the\n // main loop (main falls back to the session id / leaves it empty). Its cure differs: the hooks\n // blocking it resolve through CLAUDE_PROJECT_DIR, which names the MAIN tree.\n const inSubagent = event.agentId !== '';\n emitDeny(event, shimStaleDenyReason(installedShimRulesVersion(), shimRoot ?? '', drifted, inSubagent) + guardMatrixPointer(docPath), 'committed-shim-stale', L0_FAULT_SHIM_STALE);\n}\n\n/**\n * THE PIPELINE, from raw stdin bytes to the decision — the whole of `parse -> adapter -> runner ->\n * emit`, as ONE function returning ONE value.\n *\n * `mode` selects which tool kinds to validate; payloads outside the mode's scope pass through\n * (emitAllow). A block is a PreToolUse `permissionDecision:\"deny\"` JSON on stdout with exit 0 — see\n * agent-response.ts. Fails CLOSED on any unexpected crash (returns a deny) so a broken hook never\n * silently lets an edit through, and the reason surfaces in the agent's UI instead of being hidden on\n * a stderr+exit-2 block.\n *\n * It reads NO stdin, writes NO stdout and calls NO exit: those three couplings are ports owned by\n * HookApp (see hook-ports.ts), which is what makes the composed pipeline drivable from a test. This\n * function is what `runMain` was; it is not a second spelling of it — `runMain` is deleted, and\n * `HookApp.run()` is the only entry point.\n */\n// webpieces-disable no-function-outside-class -- the module-scope hook body itself, sibling of handleBash()/handleFileTool(); the adapter is module-scope functions by design and must stay callable from a tree too broken to build a DI container\nexport function runPipeline(raw: string, mode: HookMode): HookOutcome {\n // Captured as soon as the ENVELOPE parses so the fail-closed catch below can tell denyJson which\n // kind of call it is denying — a crash on a Bash call still gets the visible red systemMessage, a\n // crash on a file tool does not. Null (before parse / malformed input) → treated as non-Bash.\n let event: AgentHookEvent | null = null;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const payload = new AgentPayloadParser().parse(raw);\n if (!payload) { emitAllow(); }\n // The envelope shape first: it reads only `tool_name` and the identity fields, so it cannot\n // fail, and it is what the crash path needs. The full normalization below reads `tool_input`\n // and CAN fail (a malformed Codex patch envelope denies rather than being half-understood).\n event = ADAPTERS.envelope(payload);\n\n // BEFORE enforceCommittedShim(), which can itself write a BLOCK line. See LogStream for why\n // all three of session/agent/hook are needed to keep concurrent writers off one file.\n logStream.identify(new StreamIdentity(event.sessionId, event.agentId, mode));\n // Same moment, same reason: every JS-side stream stamps `ai=`, and the fault-S line written\n // inside enforceCommittedShim() is one of them. See AiTypeContext for why the harness is a\n // process-wide holder rather than a parameter on four writers.\n aiTypeContext.identify(event.aiType);\n\n // Prefer the payload cwd (the AI's actual working dir, follows a persisted `cd`) over\n // process.cwd(); they match today, but the payload is the authoritative signal and stays\n // correct if the hook is ever invoked from a fixed dir (e.g. via $CLAUDE_PROJECT_DIR).\n const cwd = payload.cwd ?? process.cwd();\n\n // Committed-shim self-guard: blocks real work while the committed shim is stale, but keeps the\n // recovery path open (cures, reads, config edit). See enforceCommittedShim / shimStaleRecoveryDecision.\n enforceCommittedShim(payload, event, cwd, mode);\n\n event = ADAPTERS.toEvent(payload, cwd);\n\n // Read-only tools: their own fast path, which never returns when it applies.\n handleReadFastPath(event, cwd, mode);\n\n // Per-invocation guard log (the `calls/` stream): tool + command/file + live branch +\n // main-sync-status snapshot, on EVERY guards call, for later cleanup automation. Best-effort;\n // never blocks the call. (The committed shim is no longer silently healed here — a mismatch is\n // reported by the self-guard above, not rewritten out from under the AI.)\n if (mode !== 'rules') {\n invocationLog.begin(cwd, event.rawToolName, logTarget(event));\n }\n\n if (event.kind === 'Bash') {\n // No code-style rule is bash-scoped, so the rules hook ignores Bash.\n if (mode === 'rules') { emitAllow(); }\n handleBash(event, cwd, mode);\n }\n\n // File payloads run in 'rules' (code-style), 'guards' (file-scoped guards like\n // feature-branch-guard), and 'all'. The runner filters to the right category.\n handleFileTool(event, cwd, mode);\n } catch (err: unknown) {\n const error = toError(err);\n // The pipeline's own terminal control flow, not a failure: emitAllow/emitDeny threw the answer\n // out to here from wherever they were called. Treating it as a crash would turn every allow\n // into a deny, so this branch comes FIRST and returns the carried outcome verbatim.\n if (error instanceof HookTerminated) return error.outcome;\n return denyForCrash(error, event);\n }\n}\n\n// What the `calls/` audit line names as the call's target: the command for a shell call, else the first\n// file it touches. A Codex `apply_patch` touching several files names the first — the rejection log and\n// the decision log carry the rest, per file.\n// webpieces-disable no-function-outside-class -- sibling of the module-scope hook entry points in this adapter\nfunction logTarget(event: AgentHookEvent): string {\n if (event.kind === 'Bash') return event.bash === null ? '' : event.bash.command;\n return event.files.length > 0 ? event.files[0].input.filePath : '';\n}\n\n/**\n * The fail-closed boundary for anything that escaped the hook body. An escaped RuleFailError (a rule\n * that threw past the runner's per-rule catch) or an InformAiError (bad config/stdin, or a Codex patch\n * envelope this parser refuses to guess at) both carry an AI-readable message; anything else is an\n * unexpected bug. All three DENY and surface their reason, because a hook that crashed established\n * nothing and must never be read as an allow.\n *\n * It BUILDS the deny (denyOutcome) rather than throwing it (emitDeny), because it is already inside\n * the catch that the throw would land in — see HookTerminated. Same bytes either way.\n */\n// webpieces-disable no-function-outside-class -- sibling of the module-scope hook entry points in this adapter; a lone class for one terminal boundary would break the file's shape\nfunction denyForCrash(error: Error, event: AgentHookEvent | null): HookOutcome {\n if (error instanceof RuleFailError) {\n return denyOutcome(event, renderRuleFailForAi(error), 'rule-crash');\n }\n if (error instanceof InformAiError) {\n return denyOutcome(event, error.message, 'bad-config-or-stdin');\n }\n return denyOutcome(event, `[ai-hooks] hook crashed unexpectedly — failing closed: ${error.message}`, 'hook-crash');\n}\n"]}
1
+ {"version":3,"file":"hook-core.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/adapters/hook-core.ts"],"names":[],"mappings":";;AAmOA,8DAKC;AAoFD,kCA6DC;;AAzXD,mDAA6B;AAE7B,2CAAuD;AACvD,iEAAsE;AACtE,yDAAuE;AACvE,uDAAkI;AAClI,iEAAmE;AACnE,qDAAsD;AACtD,0DAA8E;AAC9E,yCAA2G;AAE3G,+CAA2C;AAC3C,qDAAoE;AACpE,0DAAsE;AACtE,mDAAmE;AACnE,qDAAiD;AACjD,2CAA2C;AAC3C,iEAA2F;AAC3F,uEAAkE;AAClE,sCAAsF;AACtF,gEAA+D;AAC/D,8DAA8D;AAC9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ED;;;;;;;;;GASG;AACH,oLAAoL;AACpL,SAAS,YAAY,CAAC,KAAY,EAAE,KAA4B;IAC5D,IAAI,KAAK,YAAY,qBAAa,EAAE,CAAC;QACjC,OAAO,IAAA,4BAAW,EAAC,KAAK,EAAE,IAAA,kCAAmB,EAAC,KAAK,CAAC,EAAE,YAAY,CAAC,CAAC;IACxE,CAAC;IACD,IAAI,KAAK,YAAY,qBAAa,EAAE,CAAC;QACjC,OAAO,IAAA,4BAAW,EAAC,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE,qBAAqB,CAAC,CAAC;IACpE,CAAC;IACD,OAAO,IAAA,4BAAW,EAAC,KAAK,EAAE,0DAA0D,KAAK,CAAC,OAAO,EAAE,EAAE,YAAY,CAAC,CAAC;AACvH,CAAC","sourcesContent":["import * as path from 'path';\n\nimport { run, runBash, runRead } from '../core/runner';\nimport { branchStateHangTimeoutFor } from '../core/main-sync-timeout';\nimport { logRejection, extractRuleNames } from '../core/rejection-log';\nimport { logGuardDecision, GuardDecision, branchForLog, invocationLog, MATRIX_L0_BLOCK, matrixL2Row } from '../core/decision-log';\nimport { triggerMainSyncRefresh } from '../core/main-sync-refresh';\nimport { CONFIG_FILENAME } from '../core/load-config';\nimport { RepoRootFinder, renderRuleFailForAi } from '@webpieces/rules-config';\nimport { NormalizedToolInput, InformAiError, RuleFailError, HookMode, BlockedResult } from '../core/types';\nimport { AgentHookEvent, AiType, FileOperation } from '@webpieces/hook-runtime';\nimport { toError } from '../core/to-error';\nimport { emitDeny, emitAllow, denyOutcome } from './agent-response';\nimport { HookOutcome, HookTerminated } from '@webpieces/hook-runtime';\nimport { AgentPayload, AgentPayloadParser } from './agent-payload';\nimport { AgentAdapters } from './agent-adapters';\nimport { detectAiType } from './detect-ai';\nimport { CodexSubagentSharedTreeGuard, CODEX_SUBAGENT_RULE } from './codex-subagent-guard';\nimport { ReviewIdentityStamper } from './review-identity-stamper';\nimport { governingShimRoot, isAllowed, installedShimRulesVersion } from '../bin/shim';\nimport { managedSurfaceDrift } from '../bin/hook-registration';\nimport { shimStaleDenyReason } from '../bin/shim-deny-reason';\nimport { writeGuardMatrixDoc, guardMatrixPointer } from '../core/l0-matrix';\nimport { logStream, StreamIdentity } from '../core/log-stream';\nimport { aiTypeContext } from '../core/ai-type-context';\nimport { L0_FAULT_SHIM_STALE, L0_FAULT_NONE } from '../core/l0-fault-codes';\n\n// Which category of rules this hook invocation runs. The hook is split into two independently\n// installable PreToolUse hooks; each runs ONE category (the runner filters by it), and both can\n// receive file AND bash payloads:\n// - 'rules' → code-style rules (file/edit scope). Bash payloads pass through (no code rules apply).\n// - 'guards' → hookGuards section: bash git/PR guards on Bash AND file guards (feature-branch-guard)\n// on Write/Edit, PLUS a log-and-allow audit of Read. Matcher is Write|Edit|MultiEdit|Bash|Read.\n// - 'all' → both categories, used by the openclaw plugin adapter (a single before_tool_call hook).\nexport type { HookMode };\n\nconst ADAPTERS = new AgentAdapters();\nconst SUBAGENT_GUARD = new CodexSubagentSharedTreeGuard();\nconst REVIEW_IDENTITY_STAMPER = new ReviewIdentityStamper();\n\n// The rule name for a block's audit line: the FIRST rule the report cites, or `fallback` when the\n// report opens with no `[rule]` header (a hand-written guard message). Comma-joined when a report\n// cites several, so `rule=` never silently drops one.\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction blockingRule(report: string, fallback: string): string {\n const names = extractRuleNames(report);\n return names.length > 0 ? names.join(',') : fallback;\n}\n\n// webpieces-disable no-function-outside-class -- sibling of handleRead()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction handleBash(event: AgentHookEvent, cwd: string, mode: HookMode): never {\n const command = event.bash === null ? '' : event.bash.command;\n if (command.trim() === '') { emitAllow(); }\n\n // READ PARITY, and it can only ever be reached from a Codex event: the adapter leaves `reads`\n // empty for Claude Code, which has a real `Read` tool and its own fast path. A Codex read arrives\n // as `Bash` running a pager, so without this the read guard and the `calls/` audit trail see none\n // of them. The command is STILL run through the bash guards below — this adds a verdict, it never\n // replaces one.\n for (const readPath of event.reads) {\n handleRead(event, readPath, cwd, mode);\n }\n\n // The HARNESS travels with the command. Fault C and fault Y are decided inside the runner, and\n // both consult the L0 allowlist — which since the gated entry exists cannot be asked without\n // knowing who is calling. `event.aiType` is the adapter's answer, the same one that routed this\n // call to the Codex read-parity loop above.\n const result = runBash(command, cwd, mode, event.aiType);\n if (!result) {\n // ALLOWED — so if this call submits a reviewer verdict, record who is submitting it before the\n // command runs. `wp-write-review` cannot learn that from its env (see ReviewIdentityStamper).\n REVIEW_IDENTITY_STAMPER.stamp(event, command, cwd);\n emitAllow();\n }\n // NO DECISION LINE HERE. This used to write a generic `bash-guard` line because a Bash deny once\n // had no audit trail at all — but every layer now records its own: L1 into `L1-location/` with its\n // row, L2's guards into `L2-decisions/` with their rule and cache, and emitDeny below stamps the\n // call-level outcome onto `calls/`. So this was the THIRD line for one block, and the worst of the\n // three: it re-resolved the root from `cwd` via RepoRootFinder, which is not necessarily the tree\n // the guard actually judged, so a `cd`-relocated command scattered one block across two different\n // `.webpieces` directories.\n //\n // Bash deny → the event's kind is 'Bash', so denyJson adds the ANSI-red systemMessage (the only\n // field a Bash deny shows the human; permissionDecisionReason is invisible on Bash). See\n // agent-response.ts.\n emitDeny(event, result.report, blockingRule(result.report, 'bash-guard'), result.fault);\n}\n\n/**\n * The read-scoped guard pass. Returns normally to ALLOW; only calls emitDeny when the guard fires.\n *\n * Wrapped in its own catch that swallows into an allow. Every other path in this hook fails CLOSED,\n * and that is right for edits and shell commands — but a crash here would block the agent from\n * READING, which includes reading webpieces.config.json to turn the offending guard off. So this one\n * path deliberately inverts the policy: a broken read-guard degrades to a no-op, never to a wedge.\n */\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction handleRead(event: AgentHookEvent, filePath: string, cwd: string, mode: HookMode): void {\n if (filePath === '') return;\n let result: BlockedResult | null = null;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n result = runRead(filePath, cwd, mode);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return; // fail OPEN — see the doc comment\n }\n if (!result) return;\n logRejection('Read', new NormalizedToolInput(filePath, []), result, cwd);\n emitDeny(event, result.report, blockingRule(result.report, 'read-guard'), result.fault);\n}\n\n/**\n * Read-only tools (Read): audit-log, warm the main-sync cache, then run the ONE read-scoped guard\n * (read-stale-guard) and allow. Runs BEFORE the general rule engine — no code-style rule ever sees a\n * Read, and the only way this path can deny is a stale `main`. The audit trail still records every\n * file the AI opened (see setup.ts).\n *\n * Returns normally ONLY when the event is not a Read; otherwise it ends the invocation.\n */\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction handleReadFastPath(event: AgentHookEvent, cwd: string, mode: HookMode): void {\n if (event.kind !== 'Read') return;\n const readPath = event.reads.length > 0 ? event.reads[0] : '';\n if (mode !== 'rules') {\n invocationLog.begin(cwd, event.rawToolName, readPath);\n // Reads vastly outnumber edits, so refreshing here is what actually keeps the shared\n // main-sync cache warm for feature-branch-guard. Detached; never slows the read.\n triggerMainSyncRefresh(cwd, branchStateHangTimeoutFor(cwd));\n }\n handleRead(event, readPath, cwd, mode);\n emitAllow();\n}\n\n/**\n * The file/edit pipeline, run once per file the call touches.\n *\n * `event.files` is a LIST because ONE Codex `apply_patch` carries many files with mixed operations.\n * A Claude Code event always has exactly one entry, so the loop runs once and the behaviour is the\n * single-file behaviour it has always had.\n */\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleRead() in this module; the adapter is module-scope functions by design\nfunction handleFileTool(event: AgentHookEvent, cwd: string, mode: HookMode): never {\n if (event.files.length === 0) { emitAllow(); }\n\n // A Codex SUBAGENT writing into the tree it shares with its coordinator. Returns null for every\n // Claude Code event — that harness can hand a subagent its own worktree, and does.\n const subagentBlock = SUBAGENT_GUARD.check(event, new RepoRootFinder().resolveRepoRoot(cwd));\n if (subagentBlock) {\n emitDeny(event, subagentBlock.report, CODEX_SUBAGENT_RULE, subagentBlock.fault);\n }\n\n for (const file of event.files) {\n handleOneFile(event, file, cwd, mode);\n }\n emitAllow();\n}\n\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction handleOneFile(event: AgentHookEvent, file: FileOperation, cwd: string, mode: HookMode): void {\n const input = file.input;\n\n // Always allow edits to webpieces.config.json — it's the fix target when the config is broken.\n // This returns BEFORE run(), so feature-branch-guard never sees a config edit; record that so the\n // audit trail explains why a config edit on a bad branch was not blocked (see decision-log.ts).\n if (path.basename(input.filePath) === CONFIG_FILENAME) {\n if (mode !== 'rules') {\n // `.webpieces/` (the decision log + sync cache these two calls write) lives at the repo\n // root, not the AI's cwd — resolve it so a config edit from a subdir doesn't create a\n // stray `<subdir>/.webpieces` tree.\n const root = new RepoRootFinder().resolveRepoRoot(cwd);\n logGuardDecision(\n root,\n new GuardDecision('feature-branch-guard', file.toolKind, input.filePath, branchForLog(root), 'ALLOW_EXEMPT', 'config-bypass (feature-branch-guard skipped)', '-', L0_FAULT_NONE, matrixL2Row('config-bypass (feature-branch-guard skipped)')),\n );\n // The guard's own refresh trigger lives inside its check(), which we skip here — so warm\n // the cache directly, otherwise a session that only edits webpieces.config.json never\n // refreshes the sync status. Fire-and-forget; never blocks the edit.\n triggerMainSyncRefresh(root, branchStateHangTimeoutFor(cwd));\n }\n return;\n }\n\n const result = run(file.toolKind, input, cwd, mode);\n if (!result) return;\n\n logRejection(file.toolKind, input, result, cwd);\n // File-tool deny → the event's kind is 'File', so denyJson omits systemMessage (the reason\n // already renders red natively for these tools). See agent-response.ts.\n emitDeny(event, result.report, blockingRule(result.report, 'file-guard'), result.fault);\n}\n\n// What a stale committed shim lets through — now a thin adapter over the ONE L0 allowlist (isAllowed in\n// ../bin/shim), not a list of its own. A stale shim must NEVER trap the actions needed to recover: the\n// original \"block everything but the cures\" version also shadowed the always-allowed\n// webpieces.config.json edit (handleFileTool) and blocked reads, so a repo that ALSO needed its config\n// fixed would deadlock — blocked from editing the one file whose edit is normally always allowed, and\n// blocked from reading it to know how.\n//\n// It used to carry its OWN narrower list (isShimCureCommand: the three shim cures only), and that\n// narrowness was a defect, not a safety property: `pnpm install` and `git pull` — the two commands that\n// resolve the version disagreement underneath a stale shim — were denied. Consulting the shared\n// allowlist fixes that by construction.\n//\n// What is NOT a defect, and must not be \"fixed\": those cures rewrite the committed shim from the\n// INSTALLED binary's renderShim(), overwriting whatever was there. That is the invariant, not\n// collateral damage. The shim (D/X/K, in POSIX sh, pre-binary) and this binary (S/C/Y, in JS) are two\n// halves of ONE L0 and they exchange assumptions — the shim parses file_path and carries ALLOW-READ /\n// ALLOW-CONFIG entries this binary relies on. Pair a binary with a shim rendered by a DIFFERENT\n// release and L0 acquires holes that nothing reports. So the rule is absolute: the committed shim\n// equals renderShim() of the binary in node_modules, and a cure that forces that is the cure working.\n// See healShim's header, which states the same invariant from the other side.\n//\n// Corollary for anyone regenerating the shim in a webpieces PR: commit `templates/ai-hook.sh` (source,\n// locked to renderShim() by unit test) and leave `.claude/webpieces/ai-hook.sh` (generated artifact)\n// alone. In THIS repo the local source runs ahead of the pinned node_modules, so committing a shim\n// rendered from local source produces a commit whose shim and whose @webpieces pin come from different\n// releases — precisely the mismatch above. The artifact heals on the next upgrade; that is its job.\n//\n// - 'allow-cure' → a Bash cure on the allowlist: emitAllow directly, bypassing the git guards.\n// - 'pass' → a recovery action the normal flow already permits, so fall THROUGH and let it: ANY\n// Read (you must read to know how to fix — see handleRead, which itself fails open),\n// or an edit to webpieces.config.json (the always-allowed recovery target).\n// - 'deny' → all OTHER work: blocked until the committed shim matches renderShim() again.\nexport type ShimStaleDecision = 'allow-cure' | 'pass' | 'deny';\n// webpieces-disable no-function-outside-class -- pure decision helper beside the adapter's other module-scope functions; exported for direct unit testing.\nexport function shimStaleRecoveryDecision(toolName: string, command: string, filePath: string, aiType: AiType): ShimStaleDecision {\n const allowed = isAllowed(toolName, command, filePath, aiType);\n if (allowed === 'pass') return 'pass';\n if (allowed === 'allow') return 'allow-cure';\n return 'deny';\n}\n\n// MANAGED-HOOK-SURFACE self-guard, moved here from the rendered shim (2026-07-24) and widened from one\n// file to three (2026-08-07). The committed\n// .claude/webpieces/ai-hook.sh is webpieces-MANAGED and generated from renderShim(); if it no longer\n// matches, it was reverted / hand-edited / predates this binary, so its OWN fail-closed logic can't be\n// trusted. We are the CURRENT binary from node_modules — the trustworthy party — so WE decide here\n// instead of the (possibly stale) shim. It used to `cmp` itself inside the shim: a double-edged trap,\n// since the check lived in the very file it guarded and a fix could only ship by regenerating that\n// file. Now we fail closed on all real WORK while always leaving the recovery path open (see\n// shimStaleRecoveryDecision): the whole L0 allowlist, any Read, and editing webpieces.config.json. We deny +\n// tell the AI; we do NOT silently rewrite the file under it. 'rules' hook skips it (guards owns the\n// shim). Returns normally (pass / nothing to do) or exits via emitAllow/emitDeny.\n//\n// It asks the allowlist about the RAW WIRE FIELDS, not about the normalized event, and that ordering is\n// deliberate: L0 has to hold on a tree too broken to trust anything above it, including the adapters.\n// The raw fields are the same key names in both harnesses (measured), so one reading serves both, and\n// the answer cannot change because a normalizer changed. `event` is here only to decorate the deny.\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction enforceCommittedShim(payload: AgentPayload, event: AgentHookEvent, cwd: string, mode: HookMode): void {\n // ONE root for the whole decision, resolved from the RUNNING MODULE (governingShimRoot), never from\n // `cwd`: the shim file we compare and the renderShim() we compare it TO must come from the same\n // install, or the check straddles two trees and can never converge (see governingShimRoot's header).\n // `cwd` still selects where the L0 matrix doc is dropped — that is a \"where does the AI read\" question,\n // not part of the judgement.\n const shimRoot = governingShimRoot();\n if (mode === 'rules') return;\n // WHICH of the managed things moved — ai-hook.sh, either harness's hook registration\n // (.claude/settings.json, .codex/hooks.json), or the Claude settings' managed env entry (the\n // Bash-cwd pin that keeps a guard's verdict independent of where an earlier `cd` left the shell;\n // see managed-env.ts). Nothing validated the registration before it joined this\n // fault, so a settings file left on a superseded form silently changed WHO GOVERNS, with no signal\n // anywhere — which is the whole reason the registration is a drift surface and not just an install\n // step.\n const drifted = managedSurfaceDrift(shimRoot);\n if (drifted.length === 0) return;\n // The harness comes from the RAW envelope too — `detectAiType` asks one question of one key, so it\n // is as trustworthy here as the wire fields beside it, and it is the PRECISE test the shim's sh half\n // can only approximate. Reading it off the normalized event instead would put a normalizer between\n // L0 and its decision, which is the coupling the paragraph above exists to refuse.\n const decision = shimStaleRecoveryDecision(\n payload.tool_name, payload.tool_input.command ?? '', payload.tool_input.file_path ?? '',\n detectAiType(payload));\n if (decision === 'pass') return;\n if (decision === 'allow-cure') emitAllow();\n // Drop the L0 matrix doc where the AI can read it and point the deny at it — a Read is entry 1 of\n // the same allowlist, so the pointer is always followable. Best-effort: no doc → no pointer.\n const root = new RepoRootFinder().resolveRepoRoot(cwd);\n const docPath = writeGuardMatrixDoc(root);\n // WRITE THE AUDIT LINE HERE. This block happens BEFORE invocationLog.begin() — it has to, since a\n // stale shim invalidates everything downstream — so emitDeny's flush finds nothing pending and an\n // `S` storm left NO trace at all: the one fault most likely to block twenty consecutive tool calls\n // was the one fault the trail could not show. A decision line is the fix that costs no reordering.\n const target = payload.tool_input.command ?? payload.tool_input.file_path ?? '';\n logGuardDecision(\n root,\n new GuardDecision('committed-shim-stale', payload.tool_name, target, branchForLog(root), 'BLOCK_AI_CURE', 'L0 fault S (committed shim != renderShim)', '-', L0_FAULT_SHIM_STALE, MATRIX_L0_BLOCK),\n );\n // L0 fault S in GUARD_MATRIX.md's codebook — named as the blocking rule so the invocation line\n // says WHAT stopped the call, not merely that something did, and stamped as `fault=S` so the same\n // grep finds it here as in the sh half's `L0-shim/` stream.\n // A subagent is discriminated by `agent_id`, which BOTH harnesses populate on stdin only off the\n // main loop (main falls back to the session id / leaves it empty). Its cure differs: the hooks\n // blocking it resolve through CLAUDE_PROJECT_DIR, which names the MAIN tree.\n const inSubagent = event.agentId !== '';\n emitDeny(event, shimStaleDenyReason(installedShimRulesVersion(), shimRoot ?? '', drifted, inSubagent) + guardMatrixPointer(docPath), 'committed-shim-stale', L0_FAULT_SHIM_STALE);\n}\n\n/**\n * THE PIPELINE, from raw stdin bytes to the decision — the whole of `parse -> adapter -> runner ->\n * emit`, as ONE function returning ONE value.\n *\n * `mode` selects which tool kinds to validate; payloads outside the mode's scope pass through\n * (emitAllow). A block is a PreToolUse `permissionDecision:\"deny\"` JSON on stdout with exit 0 — see\n * agent-response.ts. Fails CLOSED on any unexpected crash (returns a deny) so a broken hook never\n * silently lets an edit through, and the reason surfaces in the agent's UI instead of being hidden on\n * a stderr+exit-2 block.\n *\n * It reads NO stdin, writes NO stdout and calls NO exit: those three couplings are ports owned by\n * HookApp (see hook-ports.ts), which is what makes the composed pipeline drivable from a test. This\n * function is what `runMain` was; it is not a second spelling of it — `runMain` is deleted, and\n * `HookApp.run()` is the only entry point.\n */\n// webpieces-disable no-function-outside-class -- the module-scope hook body itself, sibling of handleBash()/handleFileTool(); the adapter is module-scope functions by design and must stay callable from a tree too broken to build a DI container\nexport function runPipeline(raw: string, mode: HookMode): HookOutcome {\n // Captured as soon as the ENVELOPE parses so the fail-closed catch below can tell denyJson which\n // kind of call it is denying — a crash on a Bash call still gets the visible red systemMessage, a\n // crash on a file tool does not. Null (before parse / malformed input) → treated as non-Bash.\n let event: AgentHookEvent | null = null;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const payload = new AgentPayloadParser().parse(raw);\n if (!payload) { emitAllow(); }\n // The envelope shape first: it reads only `tool_name` and the identity fields, so it cannot\n // fail, and it is what the crash path needs. The full normalization below reads `tool_input`\n // and CAN fail (a malformed Codex patch envelope denies rather than being half-understood).\n event = ADAPTERS.envelope(payload);\n\n // BEFORE enforceCommittedShim(), which can itself write a BLOCK line. See LogStream for why\n // all three of session/agent/hook are needed to keep concurrent writers off one file.\n logStream.identify(new StreamIdentity(event.sessionId, event.agentId, mode));\n // Same moment, same reason: every JS-side stream stamps `ai=`, and the fault-S line written\n // inside enforceCommittedShim() is one of them. See AiTypeContext for why the harness is a\n // process-wide holder rather than a parameter on four writers.\n aiTypeContext.identify(event.aiType);\n\n // Prefer the payload cwd (the AI's actual working dir, follows a persisted `cd`) over\n // process.cwd(); they match today, but the payload is the authoritative signal and stays\n // correct if the hook is ever invoked from a fixed dir (e.g. via $CLAUDE_PROJECT_DIR).\n const cwd = payload.cwd ?? process.cwd();\n\n // Committed-shim self-guard: blocks real work while the committed shim is stale, but keeps the\n // recovery path open (cures, reads, config edit). See enforceCommittedShim / shimStaleRecoveryDecision.\n enforceCommittedShim(payload, event, cwd, mode);\n\n event = ADAPTERS.toEvent(payload, cwd);\n\n // Read-only tools: their own fast path, which never returns when it applies.\n handleReadFastPath(event, cwd, mode);\n\n // Per-invocation guard log (the `calls/` stream): tool + command/file + live branch +\n // main-sync-status snapshot, on EVERY guards call, for later cleanup automation. Best-effort;\n // never blocks the call. (The committed shim is no longer silently healed here — a mismatch is\n // reported by the self-guard above, not rewritten out from under the AI.)\n if (mode !== 'rules') {\n invocationLog.begin(cwd, event.rawToolName, logTarget(event));\n }\n\n if (event.kind === 'Bash') {\n // No code-style rule is bash-scoped, so the rules hook ignores Bash.\n if (mode === 'rules') { emitAllow(); }\n handleBash(event, cwd, mode);\n }\n\n // File payloads run in 'rules' (code-style), 'guards' (file-scoped guards like\n // feature-branch-guard), and 'all'. The runner filters to the right category.\n handleFileTool(event, cwd, mode);\n } catch (err: unknown) {\n const error = toError(err);\n // The pipeline's own terminal control flow, not a failure: emitAllow/emitDeny threw the answer\n // out to here from wherever they were called. Treating it as a crash would turn every allow\n // into a deny, so this branch comes FIRST and returns the carried outcome verbatim.\n if (error instanceof HookTerminated) return error.outcome;\n return denyForCrash(error, event);\n }\n}\n\n// What the `calls/` audit line names as the call's target: the command for a shell call, else the first\n// file it touches. A Codex `apply_patch` touching several files names the first — the rejection log and\n// the decision log carry the rest, per file.\n// webpieces-disable no-function-outside-class -- sibling of the module-scope hook entry points in this adapter\nfunction logTarget(event: AgentHookEvent): string {\n if (event.kind === 'Bash') return event.bash === null ? '' : event.bash.command;\n return event.files.length > 0 ? event.files[0].input.filePath : '';\n}\n\n/**\n * The fail-closed boundary for anything that escaped the hook body. An escaped RuleFailError (a rule\n * that threw past the runner's per-rule catch) or an InformAiError (bad config/stdin, or a Codex patch\n * envelope this parser refuses to guess at) both carry an AI-readable message; anything else is an\n * unexpected bug. All three DENY and surface their reason, because a hook that crashed established\n * nothing and must never be read as an allow.\n *\n * It BUILDS the deny (denyOutcome) rather than throwing it (emitDeny), because it is already inside\n * the catch that the throw would land in — see HookTerminated. Same bytes either way.\n */\n// webpieces-disable no-function-outside-class -- sibling of the module-scope hook entry points in this adapter; a lone class for one terminal boundary would break the file's shape\nfunction denyForCrash(error: Error, event: AgentHookEvent | null): HookOutcome {\n if (error instanceof RuleFailError) {\n return denyOutcome(event, renderRuleFailForAi(error), 'rule-crash');\n }\n if (error instanceof InformAiError) {\n return denyOutcome(event, error.message, 'bad-config-or-stdin');\n }\n return denyOutcome(event, `[ai-hooks] hook crashed unexpectedly — failing closed: ${error.message}`, 'hook-crash');\n}\n"]}
@@ -0,0 +1,5 @@
1
+ import { HookArgs, HookEvaluator, HookOutcome } from '@webpieces/hook-runtime';
2
+ /** ai-hook-rules' rule/guard provider, injected into the protocol-only HookApp. */
3
+ export declare class HookPipelineEvaluator extends HookEvaluator {
4
+ evaluate(raw: string, args: HookArgs): HookOutcome;
5
+ }
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HookPipelineEvaluator = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const hook_runtime_1 = require("@webpieces/hook-runtime");
6
+ const inversify_1 = require("inversify");
7
+ const hook_core_1 = require("./hook-core");
8
+ /** ai-hook-rules' rule/guard provider, injected into the protocol-only HookApp. */
9
+ let HookPipelineEvaluator = class HookPipelineEvaluator extends hook_runtime_1.HookEvaluator {
10
+ evaluate(raw, args) {
11
+ return (0, hook_core_1.runPipeline)(raw, args.mode);
12
+ }
13
+ };
14
+ exports.HookPipelineEvaluator = HookPipelineEvaluator;
15
+ exports.HookPipelineEvaluator = HookPipelineEvaluator = tslib_1.__decorate([
16
+ (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton)
17
+ ], HookPipelineEvaluator);
18
+ //# sourceMappingURL=hook-pipeline-evaluator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hook-pipeline-evaluator.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/adapters/hook-pipeline-evaluator.ts"],"names":[],"mappings":";;;;AAAA,0DAA+E;AAC/E,yCAA2D;AAE3D,2CAA0C;AAE1C,mFAAmF;AAE5E,IAAM,qBAAqB,GAA3B,MAAM,qBAAsB,SAAQ,4BAAa;IAC3C,QAAQ,CAAC,GAAW,EAAE,IAAc;QACzC,OAAO,IAAA,uBAAW,EAAC,GAAG,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;IACvC,CAAC;CACJ,CAAA;AAJY,sDAAqB;gCAArB,qBAAqB;IADjC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;GAC5B,qBAAqB,CAIjC","sourcesContent":["import { HookArgs, HookEvaluator, HookOutcome } from '@webpieces/hook-runtime';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { runPipeline } from './hook-core';\n\n/** ai-hook-rules' rule/guard provider, injected into the protocol-only HookApp. */\n@injectable(bindingScopeValues.Singleton)\nexport class HookPipelineEvaluator extends HookEvaluator {\n override evaluate(raw: string, args: HookArgs): HookOutcome {\n return runPipeline(raw, args.mode);\n }\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { ReviewIdentityStampService } from '@webpieces/rules-config';
2
- import { AgentHookEvent } from '../core/agent-event';
2
+ import { AgentHookEvent } from '@webpieces/hook-runtime';
3
3
  /**
4
4
  * Tells `pnpm wp-write-review` WHO invoked it (issue #863).
5
5
  *
@@ -1 +1 @@
1
- {"version":3,"file":"review-identity-stamper.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/adapters/review-identity-stamper.ts"],"names":[],"mappings":";;;AAAA,0DAAgH;AAIhH;;;;;;;;;;;;GAYG;AACH,MAAa,qBAAqB;IACD;IAA7B,YAA6B,SAAqC,mCAAoB;QAAzD,WAAM,GAAN,MAAM,CAAmD;IAAG,CAAC;IAE1F,KAAK,CAAC,KAAqB,EAAE,OAAe,EAAE,GAAW;QACrD,MAAM,UAAU,GAAG,IAAI,CAAC,MAAM,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC;QAC1D,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO;QACpC,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;QACrC,KAAK,MAAM,WAAW,IAAI,UAAU,EAAE,CAAC;YACnC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,IAAI,kCAAmB,CAC1C,WAAW,EAAE,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,SAAS,EAAE,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,SAAS,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC;QAC/F,CAAC;IACL,CAAC;CACJ;AAZD,sDAYC","sourcesContent":["import { ReviewIdentityStamp, ReviewIdentityStampService, reviewIdentityStamps } from '@webpieces/rules-config';\n\nimport { AgentHookEvent } from '../core/agent-event';\n\n/**\n * Tells `pnpm wp-write-review` WHO invoked it (issue #863).\n *\n * The bin runs inside the Bash call, and a Bash child sees only its environment — which in neither harness\n * distinguishes a reviewer subagent from its coordinator (see ReviewIdentityStamp for the detail). This\n * hook, by contrast, is handed the harness's own `agent_id` for the very call that is about to run the bin.\n * So for every checklist a command submits, it writes one stamp the bin consumes a moment later. The bin\n * then REFUSES a stamp that names the coordinating agent — closing the forgery path a Codex coordinator\n * took on two merged PRs — and records the subagent's identity in the verdict's provenance.\n *\n * Called ONLY for a Bash call the guards have already ALLOWED: a denied command never runs the bin, and a\n * stamp it left behind would be an identity waiting to be borrowed.\n */\nexport class ReviewIdentityStamper {\n constructor(private readonly stamps: ReviewIdentityStampService = reviewIdentityStamps) {}\n\n stamp(event: AgentHookEvent, command: string, cwd: string): void {\n const checklists = this.stamps.invokedChecklists(command);\n if (checklists.length === 0) return;\n const now = new Date().toISOString();\n for (const checklistId of checklists) {\n this.stamps.write(cwd, new ReviewIdentityStamp(\n checklistId, event.aiType, event.sessionId, event.agentId, event.agentType, cwd, now));\n }\n }\n}\n"]}
1
+ {"version":3,"file":"review-identity-stamper.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/adapters/review-identity-stamper.ts"],"names":[],"mappings":";;;AAAA,0DAAgH;AAIhH;;;;;;;;;;;;GAYG;AACH,MAAa,qBAAqB;IACD;IAA7B,YAA6B,SAAqC,mCAAoB;QAAzD,WAAM,GAAN,MAAM,CAAmD;IAAG,CAAC;IAE1F,KAAK,CAAC,KAAqB,EAAE,OAAe,EAAE,GAAW;QACrD,MAAM,UAAU,GAAG,IAAI,CAAC,MAAM,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC;QAC1D,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO;QACpC,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;QACrC,KAAK,MAAM,WAAW,IAAI,UAAU,EAAE,CAAC;YACnC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,IAAI,kCAAmB,CAC1C,WAAW,EAAE,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,SAAS,EAAE,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,SAAS,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC;QAC/F,CAAC;IACL,CAAC;CACJ;AAZD,sDAYC","sourcesContent":["import { ReviewIdentityStamp, ReviewIdentityStampService, reviewIdentityStamps } from '@webpieces/rules-config';\n\nimport { AgentHookEvent } from '@webpieces/hook-runtime';\n\n/**\n * Tells `pnpm wp-write-review` WHO invoked it (issue #863).\n *\n * The bin runs inside the Bash call, and a Bash child sees only its environment — which in neither harness\n * distinguishes a reviewer subagent from its coordinator (see ReviewIdentityStamp for the detail). This\n * hook, by contrast, is handed the harness's own `agent_id` for the very call that is about to run the bin.\n * So for every checklist a command submits, it writes one stamp the bin consumes a moment later. The bin\n * then REFUSES a stamp that names the coordinating agent — closing the forgery path a Codex coordinator\n * took on two merged PRs — and records the subagent's identity in the verdict's provenance.\n *\n * Called ONLY for a Bash call the guards have already ALLOWED: a denied command never runs the bin, and a\n * stamp it left behind would be an identity waiting to be borrowed.\n */\nexport class ReviewIdentityStamper {\n constructor(private readonly stamps: ReviewIdentityStampService = reviewIdentityStamps) {}\n\n stamp(event: AgentHookEvent, command: string, cwd: string): void {\n const checklists = this.stamps.invokedChecklists(command);\n if (checklists.length === 0) return;\n const now = new Date().toISOString();\n for (const checklistId of checklists) {\n this.stamps.write(cwd, new ReviewIdentityStamp(\n checklistId, event.aiType, event.sessionId, event.agentId, event.agentType, cwd, now));\n }\n }\n}\n"]}
@@ -9,13 +9,14 @@ exports.main = main;
9
9
  // the two binaries is the HookArgs constructed here.
10
10
  require("reflect-metadata");
11
11
  const inversify_1 = require("inversify");
12
- const hook_app_1 = require("./hook-app");
13
- const hook_outcome_1 = require("./hook-outcome");
12
+ const hook_runtime_1 = require("@webpieces/hook-runtime");
13
+ const hook_pipeline_evaluator_1 = require("./hook-pipeline-evaluator");
14
14
  // webpieces-disable no-function-outside-class -- this IS the bin's process entry point, named in package.json `exports` as ./claude-code-guards / ./claude-code-rules; a class here would be a namespace around one call and could not be the module's callable entry.
15
15
  async function main() {
16
16
  const container = new inversify_1.Container({ autobind: true });
17
- const app = container.get(hook_app_1.HookApp);
18
- await app.run(new hook_outcome_1.HookArgs('rules'));
17
+ container.bind(hook_runtime_1.HookEvaluator).to(hook_pipeline_evaluator_1.HookPipelineEvaluator);
18
+ const app = container.get(hook_runtime_1.HookApp);
19
+ await app.run(new hook_runtime_1.HookArgs('rules'));
19
20
  }
20
21
  // `.catch` and not a bare `void main()`: a container that cannot be built throws BEFORE any HookApp
21
22
  // exists, and an unhandled rejection exits non-zero — which PreToolUse reads as a non-blocking error
@@ -23,6 +24,6 @@ async function main() {
23
24
  // arrives here as a rejection too.
24
25
  if (require.main === module) {
25
26
  // webpieces-disable no-any-unknown -- a rejection value is `unknown` by construction; HookBootFailure narrows it through toError(), which is the one place that job belongs
26
- void main().catch((err) => { new hook_app_1.HookBootFailure().report(err); });
27
+ void main().catch((err) => { new hook_runtime_1.HookBootFailure().report(err); });
27
28
  }
28
29
  //# sourceMappingURL=rules-hook.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"rules-hook.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/adapters/rules-hook.ts"],"names":[],"mappings":";;;AAaA,oBAIC;AAhBD,uGAAuG;AACvG,iGAAiG;AACjG,EAAE;AACF,oGAAoG;AACpG,qDAAqD;AACrD,4BAA0B;AAC1B,yCAAsC;AAEtC,yCAAsD;AACtD,iDAA0C;AAE1C,uQAAuQ;AAChQ,KAAK,UAAU,IAAI;IACtB,MAAM,SAAS,GAAG,IAAI,qBAAS,CAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC;IACpD,MAAM,GAAG,GAAG,SAAS,CAAC,GAAG,CAAC,kBAAO,CAAC,CAAC;IACnC,MAAM,GAAG,CAAC,GAAG,CAAC,IAAI,uBAAQ,CAAC,OAAO,CAAC,CAAC,CAAC;AACzC,CAAC;AAED,oGAAoG;AACpG,qGAAqG;AACrG,wGAAwG;AACxG,mCAAmC;AACnC,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;IAC1B,4KAA4K;IAC5K,KAAK,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,GAAY,EAAQ,EAAE,GAAG,IAAI,0BAAe,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACtF,CAAC","sourcesContent":["#!/usr/bin/env node\n// Claude Code / Codex PreToolUse adapter for the CODE-STYLE RULES hook (matcher Write|Edit|MultiEdit).\n// Bash payloads pass through untouched — branch/PR/merge protection is the separate guards hook.\n//\n// COMPOSITION ROOT, and deliberately nothing else — see guards-hook.ts. The only difference between\n// the two binaries is the HookArgs constructed here.\nimport 'reflect-metadata';\nimport { Container } from 'inversify';\n\nimport { HookApp, HookBootFailure } from './hook-app';\nimport { HookArgs } from './hook-outcome';\n\n// webpieces-disable no-function-outside-class -- this IS the bin's process entry point, named in package.json `exports` as ./claude-code-guards / ./claude-code-rules; a class here would be a namespace around one call and could not be the module's callable entry.\nexport async function main(): Promise<void> {\n const container = new Container({ autobind: true });\n const app = container.get(HookApp);\n await app.run(new HookArgs('rules'));\n}\n\n// `.catch` and not a bare `void main()`: a container that cannot be built throws BEFORE any HookApp\n// exists, and an unhandled rejection exits non-zero — which PreToolUse reads as a non-blocking error\n// and lets the tool call through. See HookBootFailure. `main` is async so a synchronous throw inside it\n// arrives here as a rejection too.\nif (require.main === module) {\n // webpieces-disable no-any-unknown -- a rejection value is `unknown` by construction; HookBootFailure narrows it through toError(), which is the one place that job belongs\n void main().catch((err: unknown): void => { new HookBootFailure().report(err); });\n}\n"]}
1
+ {"version":3,"file":"rules-hook.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/adapters/rules-hook.ts"],"names":[],"mappings":";;;AAaA,oBAKC;AAjBD,uGAAuG;AACvG,iGAAiG;AACjG,EAAE;AACF,oGAAoG;AACpG,qDAAqD;AACrD,4BAA0B;AAC1B,yCAAsC;AACtC,0DAA4F;AAE5F,uEAAkE;AAElE,uQAAuQ;AAChQ,KAAK,UAAU,IAAI;IACtB,MAAM,SAAS,GAAG,IAAI,qBAAS,CAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC;IACpD,SAAS,CAAC,IAAI,CAAC,4BAAa,CAAC,CAAC,EAAE,CAAC,+CAAqB,CAAC,CAAC;IACxD,MAAM,GAAG,GAAG,SAAS,CAAC,GAAG,CAAC,sBAAO,CAAC,CAAC;IACnC,MAAM,GAAG,CAAC,GAAG,CAAC,IAAI,uBAAQ,CAAC,OAAO,CAAC,CAAC,CAAC;AACzC,CAAC;AAED,oGAAoG;AACpG,qGAAqG;AACrG,wGAAwG;AACxG,mCAAmC;AACnC,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;IAC1B,4KAA4K;IAC5K,KAAK,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,GAAY,EAAQ,EAAE,GAAG,IAAI,8BAAe,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACtF,CAAC","sourcesContent":["#!/usr/bin/env node\n// Claude Code / Codex PreToolUse adapter for the CODE-STYLE RULES hook (matcher Write|Edit|MultiEdit).\n// Bash payloads pass through untouched — branch/PR/merge protection is the separate guards hook.\n//\n// COMPOSITION ROOT, and deliberately nothing else — see guards-hook.ts. The only difference between\n// the two binaries is the HookArgs constructed here.\nimport 'reflect-metadata';\nimport { Container } from 'inversify';\nimport { HookApp, HookArgs, HookBootFailure, HookEvaluator } from '@webpieces/hook-runtime';\n\nimport { HookPipelineEvaluator } from './hook-pipeline-evaluator';\n\n// webpieces-disable no-function-outside-class -- this IS the bin's process entry point, named in package.json `exports` as ./claude-code-guards / ./claude-code-rules; a class here would be a namespace around one call and could not be the module's callable entry.\nexport async function main(): Promise<void> {\n const container = new Container({ autobind: true });\n container.bind(HookEvaluator).to(HookPipelineEvaluator);\n const app = container.get(HookApp);\n await app.run(new HookArgs('rules'));\n}\n\n// `.catch` and not a bare `void main()`: a container that cannot be built throws BEFORE any HookApp\n// exists, and an unhandled rejection exits non-zero — which PreToolUse reads as a non-blocking error\n// and lets the tool call through. See HookBootFailure. `main` is async so a synchronous throw inside it\n// arrives here as a rejection too.\nif (require.main === module) {\n // webpieces-disable no-any-unknown -- a rejection value is `unknown` by construction; HookBootFailure narrows it through toError(), which is the one place that job belongs\n void main().catch((err: unknown): void => { new HookBootFailure().report(err); });\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { AiType } from '../core/agent-event';
1
+ import { AiType } from '@webpieces/hook-runtime';
2
2
  import type { ClaudeSettings } from './settings-shape';
3
3
  /**
4
4
  * THE INSTALLED HOOK SURFACE — two hooks per harness, all ABSOLUTE, and the ONE place their spelling is
@@ -1 +1 @@
1
- {"version":3,"file":"hook-registration.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/bin/hook-registration.ts"],"names":[],"mappings":";;;AAsRA,4CAEC;AASD,wCAQC;AAQD,wCAGC;AAUD,0CAEC;AAUD,8CAOC;AAID,gDAYC;AAID,oCAIC;AA0BD,4BAIC;AAaD,0CAOC;AAkBD,gDAcC;AAGD,oCAWC;AAGD,sCAGC;AAYD,sDAaC;AAcD,kDAUC;AAUD,gCAUC;AAkCD,oDAsBC;AAmCD,kDAeC;;AA9nBD,+CAAyB;AACzB,mDAA6B;AAE7B,+CAA2C;AAE3C,iCAAyD;AACzD,qDAA6E;AAC7E,uDAAwG;AAExG,+CAAqE;AAErE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsDG;AAEH;;;;;;;;GAQG;AACU,QAAA,4BAA4B,GAAG,qCAAqC,CAAC;AAElF;;;;;;;;;;GAUG;AACU,QAAA,0BAA0B,GAAG,YAAY,CAAC;AAEvD,+FAA+F;AAC/F,MAAa,qBAAqB;IAEjB;IACA;IAFb,YACa,OAAe,EACf,OAAe;QADf,YAAO,GAAP,OAAO,CAAQ;QACf,YAAO,GAAP,OAAO,CAAQ;IACzB,CAAC;IAEJ,MAAM,CAAC,KAA4B;QAC/B,OAAO,IAAI,CAAC,OAAO,KAAK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nimport { AiType } from '../core/agent-event';\nimport { SHIM_MARKER, committedShimStale } from './shim';\nimport { REVIEWER_AGENT_MARKER, reviewerAgentStale } from './reviewer-agent';\nimport { NEIGHBOUR_SURFACE_SUFFIX, anchorNeighbourHooks, neighbourHooksStale } from './neighbour-hooks';\nimport type { ClaudeSettings, HookCommand, HookEntry } from './settings-shape';\nimport { BASH_CWD_ENV_KEY, BASH_CWD_ENV_VALUE } from './managed-env';\n\n/**\n * THE INSTALLED HOOK SURFACE — two hooks per harness, all ABSOLUTE, and the ONE place their spelling is\n * defined. See `HarnessRegistration` below, which is what makes \"per harness\" data rather than four\n * module constants that were only ever true of Claude Code.\n *\n * ─── ONE GOVERNOR: the MAIN tree judges every tree ─────────────────────────────────────────────────\n *\n * Claude Code — .claude/settings.json\n * H1 sh \"$CLAUDE_PROJECT_DIR/.claude/webpieces/ai-hook.sh\" wp-ai-guards-hook Write|…|Bash|Read\n * H2 sh \"$CLAUDE_PROJECT_DIR/.claude/webpieces/ai-hook.sh\" wp-ai-rules-hook Write|Edit|MultiEdit\n * Codex — .codex/hooks.json (the SAME `hooks.PreToolUse` JSON shape, measured)\n * H1 sh \"$PWD/.claude/webpieces/ai-hook.sh\" wp-ai-guards-hook Bash|apply_patch\n * H2 sh \"$PWD/.claude/webpieces/ai-hook.sh\" wp-ai-rules-hook apply_patch\n *\n * ONE shim file serves all four: `.claude/` there is a path, not a claim about who is calling.\n *\n * This REPLACES a three-hook form in which these two were RELATIVE (`sh \".claude/webpieces/ai-hook.sh\"`)\n * and a third hook, L-1 `guarantee-root.sh`, existed solely to guarantee that relative path resolved.\n *\n * ─── Why the relative experiment was reversed ──────────────────────────────────────────────────────\n * Relative registration was adopted so each git tree would be governed by \"its own release, binary and\n * pin\". MEASURED 2026-08-10: it never delivered that. A linked worktree has NO `node_modules`, so\n * ai-hook.sh's upward walk executes the PRIMARY's binary — `readlink -f` resolved a worktree agent's bin\n * to `<primary>/node_modules/@webpieces/ai-hook-rules`. A worktree ran its own SCRIPT and its own\n * CONFIG; it never ran its own release. Governance was already the primary's, in every tree, the whole\n * time.\n *\n * The price of that fiction was an entire guard layer. A relative path only resolves at a tree root, and\n * a hook that cannot resolve exits 127 — per the hooks reference a NON-BLOCKING error, i.e. a SILENT\n * UNGUARDED ALLOW. So L-1 had to deny every `cd` into a project subdirectory. That denial produced the\n * force-to-root bug class, the reaped-worktree `cd` prescription, and a measured hard deadlock: L-1 told\n * a worktree-isolated agent to `cd` to the primary clone, which the harness refuses for an isolated\n * agent, leaving it unable to stay or to follow the cure.\n *\n * An absolute path resolves from ANY cwd. So the launch guarantee is structural, L-1 has no job left and\n * is deleted, and `cd` into a subdirectory is simply allowed. What used to be true only by policing the\n * shell is now true by construction.\n *\n * ─── What replaces the property that was lost ──────────────────────────────────────────────────────\n * Nothing is lost that was ever delivered — but the case relative registration WANTED to handle (a tree\n * that genuinely needs a different @webpieces) is now DETECTED instead of silently mis-governed:\n * `VersionSyncGuard` (L1 row 8) blocks when a worktree's pin disagrees with the main tree's, and\n * prescribes either aligning the pins (same git hash → same tracked pin → install in each tree that has\n * a node_modules) or using a separate CLONE, which — unlike a worktree — gets its own GOVERNANCE. Note\n * what that does NOT say: a worktree may perfectly well have its own node_modules, and usually does the\n * moment anything installs in it. What it may not have is a DIFFERENT @webpieces version.\n *\n * ─── Why the registration is a DRIFT SURFACE, not just an install step ─────────────────────────────\n * Nothing used to validate `.claude/settings.json` at all, so a settings file left on a superseded form\n * silently changed who governs. The installed surface is FOUR things (ai-hook.sh, the registration, the\n * managed `env` entry — see managed-env.ts — and the ANCHORING of the NEIGHBOUR hook commands the\n * consumer registers beside ours, see neighbour-hooks.ts), all four are compared against this release,\n * and `wp-upgrade-shim` repairs all four. A cure that fixes three of four is worse than no cure, because\n * it reports success.\n */\n\n/**\n * The RETIRED L-1 hook's committed path. Named here, in the one module that must still recognise it, and\n * matched ONLY by isManagedCommand() so repairRegistration() can delete the stale entry. There is no\n * guarantee-root.ts any more — this literal is all that remains of it, deliberately.\n *\n * It is a one-way RECOGNISER, not a shim: nothing emits it, `expectedEntries()` never returns it, and a\n * settings file carrying it is reported STALE. Its only job is to make the retired entry findable so it\n * can be REMOVED.\n */\nexport const LEGACY_GUARANTEE_ROOT_MARKER = '.claude/webpieces/guarantee-root.sh';\n\n/**\n * When this recogniser may be deleted, as a value rather than a comment nobody re-reads.\n *\n * A removal-only migration is still dead weight once no consumer can be carrying the old shape. The\n * hazard of deleting it EARLY is severe and silent — repair would stop stripping the retired entry, and\n * a hook registered against a deleted file exits 127, which the Claude Code hooks reference defines as a\n * NON-BLOCKING error, i.e. every `cd` unjudged while the cure reports success. So it gets a stated date\n * and a test that fails once the date passes, instead of an intention.\n *\n * `legacy-marker-expiry.spec.ts` reads this and fails after it, which is the reminder.\n */\nexport const LEGACY_MARKER_REMOVE_AFTER = '2026-12-01';\n\n/** One PreToolUse hook entry as webpieces registers it. Data-only → a class, per CLAUDE.md. */\nexport class HookRegistrationEntry {\n constructor(\n readonly matcher: string,\n readonly command: string,\n ) {}\n\n sameAs(other: HookRegistrationEntry): boolean {\n return this.matcher === other.matcher && this.command === other.command;\n }\n}\n\n/**\n * THE SETTINGS-FILE SHAPE lives in `./settings-shape`, a LEAF module, and is imported from THERE by\n * everything that needs it — this module included. It is deliberately NOT re-exported here: a second\n * import path for one type is the \"two spellings of one thing\" shim the compatibility policy rejects,\n * and it would keep advertising `hook-registration` as a source of the shape, which is precisely the\n * edge that has to stay broken (`neighbour-hooks.ts` needs the shape, this module imports the repairs\n * FROM it, and `validate-no-file-import-cycles` counts even a type-only edge back as a cycle).\n */\n\nexport const RULES_BIN = 'wp-ai-rules-hook';\nexport const GUARDS_BIN = 'wp-ai-guards-hook';\n\n/**\n * ONE HARNESS'S registration surface — where its hooks live, what they match, and how they name the\n * shim. Data-only → a class, per CLAUDE.md.\n *\n * ─── Why this exists ──────────────────────────────────────────────────────────────────────────────\n * The matchers and the shim command used to be four module constants written for Claude Code alone.\n * Applied to Codex they are wrong in both halves, and the way they are wrong is SILENT:\n *\n * - MATCHER. Codex's file-editing tool is `apply_patch` (MEASURED, codex-cli 0.151.0). A matcher of\n * `Write|Edit|MultiEdit` matches it never, so every file rule is unreachable while the settings file\n * looks perfectly installed. Its shell tool IS called `Bash` — Codex reuses Claude's name — which is\n * the trap: half the matcher works, so the hooks appear to be running.\n * - ANCHOR. `$CLAUDE_PROJECT_DIR` does not exist in a Codex hook's environment (measured: 46 vars, no\n * such key), so the command expands to `sh \"/.claude/webpieces/ai-hook.sh\"`, which dies — and per the\n * hooks protocol a non-2 non-zero exit is a NON-BLOCKING error, i.e. a silent unguarded allow.\n *\n * Both halves of that were live in real repos, written by a Codex Desktop sync that transliterated the\n * Claude setup. Making the registration per-harness DATA is what stops a future harness inheriting a\n * matcher that was never true for it.\n *\n * ─── ONE SHIM, both harnesses ─────────────────────────────────────────────────────────────────────\n * `SHIM_MARKER` is shared deliberately: `.claude/webpieces/ai-hook.sh` is the single fail-closed entry\n * point, and moving or duplicating it would double the L0 allowlist regexes, the drift surfaces and the\n * cures. The `.claude/` prefix is a path, not a claim about which agent is calling.\n */\nexport class HarnessRegistration {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n readonly aiType: AiType,\n /** How the installer and the drift report name this harness to a human. */\n readonly label: string,\n /** Which tool names the RULES hook (code-style, file-scoped) must see. */\n readonly rulesMatcher: string,\n /**\n * Which tool names the GUARDS hook must see. Wider than the rules matcher by the shell tool and,\n * for Claude Code, by `Read` — Read carries no guard, but the guards hook owns the\n * per-invocation audit log, so matching it records every file the AI opens (log-and-allow fast\n * path in hook-core.ts; a Read is never blocked). Codex has no Read tool at all: a read arrives\n * as `Bash` running a pager, which the shell matcher already covers and read-parity synthesizes.\n */\n readonly guardsMatcher: string,\n /** The settings files this harness's hooks can be installed into, relative to the repo root. */\n readonly settingsFiles: readonly string[],\n /**\n * THE PREFIX THE SHIM PATH IS ANCHORED ON, and the reason each harness needs its own.\n *\n * **BYTE-STABILITY IS A HARD CONSTRAINT ON THE CODEX VALUE.** Codex trusts a hook entry\n * TOFU — `~/.codex/config.toml` records a `trusted_hash` per entry — so ANY change to these bytes\n * invalidates that trust and re-prompts the human, whose third option is `Continue without\n * trusting (hooks won't run)`: one keystroke to a silently unguarded session. Changing this\n * string is therefore never a cosmetic edit. The hash is NOT reproducible from outside Codex\n * (16 encodings tried against a file we authored), so the installer can never repair trust for\n * itself — see ./codex-trust.ts, which REPORTS and never writes.\n */\n readonly shimAnchor: string,\n /**\n * True when this harness's settings file also carries the managed `env` block. Claude Code's\n * settings `env` is inherited by every subagent, which is what makes it the right home for the\n * Bash-cwd pin (see managed-env.ts). Codex has no equivalent surface — and needs none: its cwd\n * is MEASURED not to drift at all (`cd x && pwd` prints x, the next call is back at the repo\n * root, for the coordinator and for subagents alike).\n */\n readonly managesEnv: boolean,\n /** What `managedSurfaceDrift()` calls this harness's registration when it has moved. */\n readonly registrationSurface: string,\n ) {}\n\n /** Which matcher one guard bin registers under. */\n matcherFor(bin: string): string {\n return bin === RULES_BIN ? this.rulesMatcher : this.guardsMatcher;\n }\n\n /**\n * The guard-hook command — `sh \"<anchor>/.claude/webpieces/ai-hook.sh\" <bin>`.\n *\n * ABSOLUTE, in both harnesses. Claude's anchor replaced a RELATIVE spelling and that reversal is\n * documented at length in this file's header: relative resolves only at a tree root, a hook that\n * cannot resolve exits 127, and per the hooks reference that is a NON-BLOCKING error — a silent\n * unguarded allow. It also cost an entire guard layer (L-1) whose only job was to police the `cd`\n * that made the relative path resolvable.\n *\n * Invoked via `sh <file>` rather than executed directly so a missing executable bit on the\n * checked-in shim (fresh clone, a filesystem that drops the bit, git core.fileMode quirks) can never\n * break the hook with a raw `Permission denied` on every tool call. Quoted to survive spaces.\n */\n shimCommand(bin: string): string {\n return `sh \"${this.shimAnchor}/${SHIM_MARKER}\" ${bin}`;\n }\n\n /** The registration entry for one guard bin under this harness. */\n entryFor(bin: string): HookRegistrationEntry {\n return new HookRegistrationEntry(this.matcherFor(bin), this.shimCommand(bin));\n }\n\n /** This harness's settings files under one repo root, absolute. */\n settingsPaths(projectRoot: string): readonly string[] {\n return this.settingsFiles.map((file: string): string => path.join(projectRoot, ...file.split('/')));\n }\n\n /**\n * What `managedSurfaceDrift()` calls this harness's NEIGHBOUR hook commands — the entries a CONSUMER\n * repo registers in the same file — when one of them still carries a repo-RELATIVE entry path.\n *\n * DERIVED rather than a constructor field, unlike `registrationSurface` beside it, because there is\n * nothing here a harness could sensibly disagree about: it is the same file, said a second way. A\n * constructor param would be a second place to keep in step for no decision.\n */\n get neighbourSurface(): string {\n return `${this.settingsFiles[0]} ${NEIGHBOUR_SURFACE_SUFFIX}`;\n }\n}\n\nexport const CLAUDE_REGISTRATION = new HarnessRegistration(\n 'claude-code', 'Claude Code',\n 'Write|Edit|MultiEdit',\n 'Write|Edit|MultiEdit|Bash|Read',\n ['.claude/settings.json', '.claude/settings.local.json'],\n '$CLAUDE_PROJECT_DIR',\n true,\n '.claude/settings.json hook registration',\n);\n\n/**\n * Codex's registration, every value of it MEASURED against codex-cli 0.151.0 rather than assumed.\n *\n * `$PWD` is the anchor because there is no project-dir variable to use and none is needed: the payload\n * `cwd` and the hook process's own `PWD` are both the repo root on EVERY call — for the coordinator and\n * for subagents — and a `cd` inside one command never survives into the next. That was measured, not\n * hoped for, and it is the same effect Claude Code gets from the managed\n * `CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR` env entry. See `shimAnchor` for why these exact bytes are\n * not free to change.\n */\nexport const CODEX_REGISTRATION = new HarnessRegistration(\n 'codex', 'Codex',\n 'apply_patch',\n 'Bash|apply_patch',\n ['.codex/hooks.json'],\n '$PWD',\n false,\n '.codex/hooks.json hook registration',\n);\n\n/**\n * Every harness webpieces arms, in installer order.\n *\n * The drift check, the repair and the installer all iterate THIS, so a harness cannot be armed by the\n * installer and then left unvalidated — which is exactly the state `.codex/hooks.json` was in before it\n * was a managed surface: written by something else, silently wrong, and invisible to every check.\n */\nexport const HARNESS_REGISTRATIONS: readonly HarnessRegistration[] = [CLAUDE_REGISTRATION, CODEX_REGISTRATION];\n\n/**\n * True when this PreToolUse command is one webpieces owns — in ANY spelling it has ever shipped.\n *\n * THE SINGLE MOST IMPORTANT LINE IN THIS RELEASE. `LEGACY_GUARANTEE_ROOT_MARKER` is matched here and\n * NOWHERE else: it is how `repairRegistration()` finds and REMOVES the retired H1 entry from a settings\n * file written by an older release. Drop it and the repair silently leaves a live L-1 hook registered\n * against a file this release deletes — exit 127, which the Claude Code hooks reference defines as a\n * NON-BLOCKING error, so every `cd` goes unjudged while `wp-upgrade-shim` reports success and no drift\n * check can name it. Removal-only, never emitted: it appears in no `expectedEntries()` result, so it is\n * a one-way migration and not a second accepted spelling.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function isManagedCommand(command: string): boolean {\n return command.includes(SHIM_MARKER) || command.includes(LEGACY_GUARANTEE_ROOT_MARKER);\n}\n\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nfunction preToolUse(settings: ClaudeSettings): readonly HookEntry[] {\n return settings.hooks?.PreToolUse ?? [];\n}\n\n/** Every webpieces-managed entry of one settings file, flattened to matcher + command pairs. */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function managedEntries(settings: ClaudeSettings): readonly HookRegistrationEntry[] {\n const found: HookRegistrationEntry[] = [];\n for (const entry of preToolUse(settings)) {\n for (const hook of entry.hooks) {\n if (isManagedCommand(hook.command)) found.push(new HookRegistrationEntry(entry.matcher, hook.command));\n }\n }\n return found;\n}\n\n/**\n * Which guard bins this settings file registers, in installer order. A file registering NEITHER is not\n * a project (relative) install and is therefore never judged — a global/absolute install names the bin\n * path directly and carries no shim marker at all.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function registeredBins(settings: ClaudeSettings): readonly string[] {\n const commands = managedEntries(settings).map((e: HookRegistrationEntry): string => e.command);\n return [GUARDS_BIN, RULES_BIN].filter((bin: string): boolean => commands.some((c: string): boolean => c.includes(bin)));\n}\n\n/**\n * The exact set of entries THIS RELEASE expects in a settings file that registers `bins`.\n *\n * ONE entry per registered bin, and nothing else. There used to be a third, `guarantee-root.sh`, added\n * whenever the GUARDS bin was present; it is retired, and a settings file still carrying it is STALE —\n * `repairRegistration()` removes it via isManagedCommand()'s legacy marker.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as HarnessRegistration's siblings\nexport function expectedEntries(harness: HarnessRegistration, bins: readonly string[]): readonly HookRegistrationEntry[] {\n return bins.map((bin: string): HookRegistrationEntry => harness.entryFor(bin));\n}\n\n/**\n * True when a settings file registers webpieces hooks in a shape this release does not expect: a\n * RELATIVE shim command, a leftover guarantee-root entry, a stray duplicate, or a wrong matcher.\n *\n * Compared as a SET, not a sequence: Claude Code runs all matching hooks in parallel, so array order\n * carries no meaning and reordering must not read as drift.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function registrationStale(harness: HarnessRegistration, settings: ClaudeSettings): boolean {\n const bins = registeredBins(settings);\n if (bins.length === 0) return false;\n const have = managedEntries(settings);\n const want = expectedEntries(harness, bins);\n if (have.length !== want.length) return true;\n return want.some((w: HookRegistrationEntry): boolean => !have.some((h: HookRegistrationEntry): boolean => h.sameAs(w)));\n}\n\n/** Drop every webpieces-managed PreToolUse command; returns true if anything was removed. */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function dropManagedEntries(settings: ClaudeSettings): boolean {\n const entries = settings.hooks?.PreToolUse;\n if (!entries) return false;\n let changed = false;\n const kept: HookEntry[] = [];\n for (const entry of entries) {\n const hooks = entry.hooks.filter((h: HookCommand): boolean => !isManagedCommand(h.command));\n if (hooks.length !== entry.hooks.length) changed = true;\n if (hooks.length > 0) kept.push({ matcher: entry.matcher, hooks });\n }\n if (changed) settings.hooks!.PreToolUse = kept;\n return changed;\n}\n\n/** Append one PreToolUse entry. */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function addHookEntry(settings: ClaudeSettings, entry: HookRegistrationEntry): void {\n if (!settings.hooks) settings.hooks = {};\n if (!Array.isArray(settings.hooks.PreToolUse)) settings.hooks.PreToolUse = [];\n settings.hooks.PreToolUse.push({ matcher: entry.matcher, hooks: [{ type: 'command', command: entry.command }] });\n}\n\n/** The settings `env` block, or null when the file carries none (or carries junk in its place). */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nfunction settingsEnv(settings: ClaudeSettings): Record<string, string> | null {\n // webpieces-disable no-any-unknown -- settings.json is opaque consumer JSON; `env` is only typed after this check\n const env: unknown = settings.env;\n if (typeof env !== 'object' || env === null || Array.isArray(env)) return null;\n return env as Record<string, string>;\n}\n\n/**\n * True when a settings file that registers webpieces hooks is missing the managed `env` entry, or\n * carries any value other than the one required one.\n *\n * Gated on `registeredBins()` for the SAME reason `registrationStale()` is: a settings file that\n * registers no webpieces hooks is not a project install and is never judged — a global install names\n * the bin path directly and carries no shim marker at all, so there is nothing here to keep in step.\n *\n * NOTE what this entry is for NOW. It was originally justified by keeping the then-RELATIVE hook path\n * resolvable; that job is retired, because both hooks are absolute and resolve from any cwd. It is kept\n * for VERDICT STABILITY — a guard's answer must depend on the command, not on where an earlier `cd` left\n * the shell — and because settings `env` is inherited, every subagent shares that cwd and therefore that\n * verdict. See managed-env.ts, which states this at length.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function envStale(settings: ClaudeSettings): boolean {\n if (registeredBins(settings).length === 0) return false;\n const env = settingsEnv(settings);\n return env === null || env[BASH_CWD_ENV_KEY] !== BASH_CWD_ENV_VALUE;\n}\n\n/**\n * Set the managed `env` entry IN PLACE, whatever was there before. Returns true when it changed.\n *\n * A user-set `\"0\"` is BROUGHT TO `\"1\"`, not honoured: this is a managed surface, and \"webpieces sets it\n * unless you disagreed\" would be a second, invisible spelling of the decision. Turning it off means\n * uninstalling the hooks, exactly as it does for every other managed thing.\n *\n * UNGATED on purpose — the installer calls it for the file it is writing hooks into, and the gate lives\n * at the caller (repairRegistration / applyHook), so a file with no webpieces hooks is never touched.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function applyManagedEnv(settings: ClaudeSettings): boolean {\n const existing = settingsEnv(settings);\n if (existing !== null && existing[BASH_CWD_ENV_KEY] === BASH_CWD_ENV_VALUE) return false;\n const env = existing ?? {};\n env[BASH_CWD_ENV_KEY] = BASH_CWD_ENV_VALUE;\n settings.env = env;\n return true;\n}\n\n/**\n * Bring one settings object to the two-hook ABSOLUTE form AND the managed `env` entry IN PLACE. Returns\n * true when it changed anything.\n *\n * REMOVE-then-ADD for the hooks, never add-beside: two spellings of one registration is exactly the\n * compatibility shim the backwards-compat reviewer rejects, and leaving a RELATIVE entry beside the\n * absolute one would run two shims per call — the\n * straddle this whole change exists to delete.\n *\n * THE TWO REPAIRS ARE EVALUATED INDEPENDENTLY, and that is load-bearing rather than tidy: this used to\n * early-return on `!registrationStale(settings)`, so a repo whose hooks are already current but whose\n * `env` entry is missing — the state EVERY existing consumer is in the moment this release lands — would\n * have been reported as drifted by fault S and then left unrepaired by its own prescribed cure. A cure\n * that skips half the surface is the failure mode `upgrade-shim.ts`'s header exists to prevent.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function repairRegistration(harness: HarnessRegistration, settings: ClaudeSettings): boolean {\n const bins = registeredBins(settings);\n if (bins.length === 0) return false;\n let changed = false;\n if (registrationStale(harness, settings)) {\n dropManagedEntries(settings);\n for (const entry of expectedEntries(harness, bins)) addHookEntry(settings, entry);\n changed = true;\n }\n // Only where the harness HAS that surface. Codex's hooks.json has no `env` block to manage, and\n // inventing one there would write a key Codex does not read — a managed surface nothing consumes is\n // a surface that can drift with no consequence and no way to notice.\n if (harness.managesEnv && applyManagedEnv(settings)) changed = true;\n return changed;\n}\n\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function readSettings(settingsPath: string): ClaudeSettings {\n if (!fs.existsSync(settingsPath)) return {};\n const raw = fs.readFileSync(settingsPath, 'utf8');\n if (raw.trim() === '') return {};\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return JSON.parse(raw) as ClaudeSettings;\n } catch (err: unknown) {\n const error = toError(err);\n throw new Error(`${settingsPath} has invalid JSON — fix it, then retry: ${error.message}`, { cause: error });\n }\n}\n\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function writeSettings(settingsPath: string, settings: ClaudeSettings): void {\n fs.mkdirSync(path.dirname(settingsPath), { recursive: true });\n fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 4) + '\\n');\n}\n\n/**\n * True when any settings file ONE HARNESS owns under `root` carries a NEIGHBOUR hook — one the consumer\n * repo wrote — whose entry path is repo-RELATIVE and would therefore fail to resolve from any cwd but\n * the root. See neighbour-hooks.ts for the measured failure and why webpieces owns the repair.\n *\n * Judged ONLY where the file registers webpieces hooks, exactly like `registrationStaleAt` below: a\n * settings file with no webpieces hooks in it is not a webpieces install, and webpieces rewriting\n * somebody's unrelated hook lines there would be editing a file it was never given.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as HarnessRegistration's siblings\nexport function neighbourHooksStaleAt(harness: HarnessRegistration, root: string | null): boolean {\n if (root === null) return false;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return harness.settingsPaths(root).some((p: string): boolean => {\n const settings = readSettings(p);\n return registeredBins(settings).length > 0 && neighbourHooksStale(harness.shimAnchor, settings, root);\n });\n } catch (err: unknown) {\n const error = toError(err);\n void error; // best-effort: unreadable/invalid settings counts as \"not stale\" so it never wedges a call\n return false;\n }\n}\n\n/**\n * True when any settings file ONE HARNESS owns under `root` carries a stale registration.\n *\n * Per harness, not per repo, so the drift report can NAME which one moved — `.claude/settings.json` and\n * `.codex/hooks.json` have different cures, and a fault that says only \"the registration is stale\" sends\n * the reader to the wrong file half the time.\n *\n * A file that does not exist, or exists and registers no webpieces hooks, is never judged (see\n * `registrationStale`). That is what keeps a repo which has never armed Codex from suddenly faulting on\n * a `.codex/hooks.json` it does not have.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as HarnessRegistration's siblings\nexport function registrationStaleAt(harness: HarnessRegistration, root: string | null): boolean {\n if (root === null) return false;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return harness.settingsPaths(root).some((p: string): boolean => registrationStale(harness, readSettings(p)));\n } catch (err: unknown) {\n const error = toError(err);\n void error; // best-effort: unreadable/invalid settings counts as \"not stale\" so it never wedges a call\n return false;\n }\n}\n\n/**\n * True when either Claude project settings file under `root` is missing the managed `env` entry.\n *\n * CLAUDE-ONLY by construction, and stated as such rather than looped over the harnesses: `env` is a\n * Claude Code settings surface, Codex has no equivalent, and Codex's cwd is measured not to drift, which\n * is the whole thing the entry is for. See HarnessRegistration.managesEnv.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as HarnessRegistration's siblings\nexport function envStaleAt(root: string | null): boolean {\n if (root === null) return false;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return CLAUDE_REGISTRATION.settingsPaths(root).some((p: string): boolean => envStale(readSettings(p)));\n } catch (err: unknown) {\n const error = toError(err);\n void error; // best-effort: unreadable/invalid settings counts as \"not stale\" so it never wedges a call\n return false;\n }\n}\n\n/**\n * WHAT was rewritten in ONE settings file. Data-only → a class, per CLAUDE.md.\n *\n * Two independent flags rather than one path, because the cure has to be able to SAY which repair it\n * made: \"rewrote the hook registration\" printed for a file whose registration was already current and\n * whose `env` entry was the only thing missing is a cure lying about its own work.\n */\nexport class SettingsRepair {\n constructor(\n readonly settingsPath: string,\n readonly registration: boolean,\n readonly env: boolean,\n /**\n * The NEW spelling of every NEIGHBOUR hook command this repair anchored — the consumer's own\n * entries, which webpieces rewrites but does not author.\n *\n * The commands themselves rather than a count or a flag, because this is the one repair that\n * edits lines webpieces did not write: the cure has to be able to show the consumer exactly what\n * it changed in their file, or it is a silent edit to somebody else's hooks.\n */\n readonly anchoredNeighbours: readonly string[],\n ) {}\n}\n\n/**\n * Rewrite every stale settings file under `root`, for EVERY harness; returns what changed, per file.\n *\n * Existing files only — this never CREATES a registration. Arming a harness is the installer's decision\n * (`wp-install-ai-hooks`); this is the cure for one that has already been armed and has drifted, so a\n * repo that has never armed Codex is left exactly as it was.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as HarnessRegistration's siblings\nexport function repairRegistrationAt(root: string): readonly SettingsRepair[] {\n const repairs: SettingsRepair[] = [];\n for (const harness of HARNESS_REGISTRATIONS) {\n for (const settingsPath of harness.settingsPaths(root)) {\n if (!fs.existsSync(settingsPath)) continue;\n const settings = readSettings(settingsPath);\n const neededRegistration = registrationStale(harness, settings);\n const neededEnv = harness.managesEnv && envStale(settings);\n const changedManaged = repairRegistration(harness, settings);\n // AFTER the managed repair, never before: repairRegistration() removes the retired\n // guarantee-root entry and rewrites the two managed commands, so by the time the neighbour\n // pass runs there is nothing webpieces-owned left for it to look at. Gated on\n // registeredBins() for the same reason every other judgement here is — a settings file that\n // registers no webpieces hooks is not a webpieces install, and rewriting somebody's\n // unrelated hook lines in it would be webpieces editing a file it was never given.\n const anchored = registeredBins(settings).length === 0 ? [] : anchorNeighbourHooks(harness.shimAnchor, settings, root);\n if (!changedManaged && anchored.length === 0) continue;\n writeSettings(settingsPath, settings);\n repairs.push(new SettingsRepair(settingsPath, neededRegistration, neededEnv, anchored));\n }\n }\n return repairs;\n}\n\n/**\n * The names the drift check reports, so a deny can say WHICH surface moved.\n *\n * There were four, then three, and there are now FOUR again — but the fourth is not the one that was\n * deleted. `GUARANTEE_ROOT_SURFACE` went with L-1 itself: an absolutely-registered shim resolves from\n * any cwd, so there is no launch guarantee left to police and no second .sh file to keep byte-locked. A\n * settings file still carrying the retired H1 entry is not its own surface — it is ordinary REGISTRATION\n * drift, which `registrationStaleAt()` reports and `repairRegistration()` fixes by removing it.\n *\n * The new fourth is `.codex/hooks.json`, and it is here because of what happened while it was NOT a\n * managed surface: something else wrote it, with a matcher that matched no Codex file tool and a shim\n * path anchored on a variable Codex does not set, and no check in this package could see it. A file the\n * guards depend on and nothing validates is the exact shape of that incident.\n *\n * Each harness's registration surface is its own name, from HarnessRegistration.registrationSurface, so\n * the deny sends the reader to the file that actually moved.\n */\nexport const SHIM_SURFACE = SHIM_MARKER;\nexport const REGISTRATION_SURFACE = CLAUDE_REGISTRATION.registrationSurface;\nexport const CODEX_REGISTRATION_SURFACE = CODEX_REGISTRATION.registrationSurface;\nexport const ENV_SURFACE = `.claude/settings.json env.${BASH_CWD_ENV_KEY}`;\n// The generic PR-gate reviewer agent (issue #938): committed, generated, byte-stable — the same contract as\n// the shim, so the same check and the same cure.\nexport const REVIEWER_AGENT_SURFACE = REVIEWER_AGENT_MARKER;\n\n/**\n * WHICH of the managed surfaces disagree with this release — the input to fault S.\n *\n * All of them are checked against the SAME root, resolved from the RUNNING MODULE (governingShimRoot),\n * never from cwd and never from `$CLAUDE_PROJECT_DIR`: the files we compare and the renderers we\n * compare them TO must come from one install, or the check straddles two trees and can never converge.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as HarnessRegistration's siblings\nexport function managedSurfaceDrift(root: string | null): readonly string[] {\n const drifted: string[] = [];\n if (committedShimStale(root)) drifted.push(SHIM_SURFACE);\n for (const harness of HARNESS_REGISTRATIONS) {\n if (registrationStaleAt(harness, root)) drifted.push(harness.registrationSurface);\n // A neighbour hook registered with a RELATIVE entry path dies from any cwd but the root, and per\n // the hooks reference that non-zero exit is a NON-BLOCKING error — a SILENT UNGUARDED ALLOW. It\n // is a drift surface for exactly the reason the managed registration is one: nothing else in\n // this repo can see it, and the way it fails looks like a guard that PASSED. See\n // neighbour-hooks.ts, and issue #852 where it silently disarmed three security guards.\n if (neighbourHooksStaleAt(harness, root)) drifted.push(harness.neighbourSurface);\n }\n if (envStaleAt(root)) drifted.push(ENV_SURFACE);\n if (reviewerAgentStale(root)) drifted.push(REVIEWER_AGENT_SURFACE);\n return drifted;\n}\n"]}
1
+ {"version":3,"file":"hook-registration.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/bin/hook-registration.ts"],"names":[],"mappings":";;;AAsRA,4CAEC;AASD,wCAQC;AAQD,wCAGC;AAUD,0CAEC;AAUD,8CAOC;AAID,gDAYC;AAID,oCAIC;AA0BD,4BAIC;AAaD,0CAOC;AAkBD,gDAcC;AAGD,oCAWC;AAGD,sCAGC;AAYD,sDAaC;AAcD,kDAUC;AAUD,gCAUC;AAkCD,oDAsBC;AAmCD,kDAeC;;AA9nBD,+CAAyB;AACzB,mDAA6B;AAE7B,+CAA2C;AAE3C,iCAAyD;AACzD,qDAA6E;AAC7E,uDAAwG;AAExG,+CAAqE;AAErE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsDG;AAEH;;;;;;;;GAQG;AACU,QAAA,4BAA4B,GAAG,qCAAqC,CAAC;AAElF;;;;;;;;;;GAUG;AACU,QAAA,0BAA0B,GAAG,YAAY,CAAC;AAEvD,+FAA+F;AAC/F,MAAa,qBAAqB;IAEjB;IACA;IAFb,YACa,OAAe,EACf,OAAe;QADf,YAAO,GAAP,OAAO,CAAQ;QACf,YAAO,GAAP,OAAO,CAAQ;IACzB,CAAC;IAEJ,MAAM,CAAC,KAA4B;QAC/B,OAAO,IAAI,CAAC,OAAO,KAAK,KAAK,CAAC,OAAO,IAAI,IAAI,CAAC,OAAO,KAAK,KAAK,CAAC,OAAO,CAAC;IAC5E,CAAC;CACJ;AATD,sDASC;AAED;;;;;;;GAOG;AAEU,QAAA,SAAS,GAAG,kBAAkB,CAAC;AAC/B,QAAA,UAAU,GAAG,mBAAmB,CAAC;AAE9C;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,MAA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AC,mBAAmB,CAAC;AACpE,QAAA,WAAW,GAAG,6BAA6B,8BAAgB,EAAE,CAAC;AAC3E,4GAA4G;AAC5G,iDAAiD;AACpC,QAAA,sBAAsB,GAAG,sCAAqB,CAAC;AAE5D;;;;;;GAMG;AACH,oIAAoI;AACpI,SAAgB,mBAAmB,CAAC,IAAmB;IACnD,MAAM,OAAO,GAAa,EAAE,CAAC;IAC7B,IAAI,IAAA,yBAAkB,EAAC,IAAI,CAAC;QAAE,OAAO,CAAC,IAAI,CAAC,oBAAY,CAAC,CAAC;IACzD,KAAK,MAAM,OAAO,IAAI,6BAAqB,EAAE,CAAC;QAC1C,IAAI,mBAAmB,CAAC,OAAO,EAAE,IAAI,CAAC;YAAE,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,mBAAmB,CAAC,CAAC;QAClF,iGAAiG;QACjG,gGAAgG;QAChG,6FAA6F;QAC7F,iFAAiF;QACjF,uFAAuF;QACvF,IAAI,qBAAqB,CAAC,OAAO,EAAE,IAAI,CAAC;YAAE,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,gBAAgB,CAAC,CAAC;IACrF,CAAC;IACD,IAAI,UAAU,CAAC,IAAI,CAAC;QAAE,OAAO,CAAC,IAAI,CAAC,mBAAW,CAAC,CAAC;IAChD,IAAI,IAAA,mCAAkB,EAAC,IAAI,CAAC;QAAE,OAAO,CAAC,IAAI,CAAC,8BAAsB,CAAC,CAAC;IACnE,OAAO,OAAO,CAAC;AACnB,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\n\nimport { toError } from '../core/to-error';\nimport { AiType } from '@webpieces/hook-runtime';\nimport { SHIM_MARKER, committedShimStale } from './shim';\nimport { REVIEWER_AGENT_MARKER, reviewerAgentStale } from './reviewer-agent';\nimport { NEIGHBOUR_SURFACE_SUFFIX, anchorNeighbourHooks, neighbourHooksStale } from './neighbour-hooks';\nimport type { ClaudeSettings, HookCommand, HookEntry } from './settings-shape';\nimport { BASH_CWD_ENV_KEY, BASH_CWD_ENV_VALUE } from './managed-env';\n\n/**\n * THE INSTALLED HOOK SURFACE — two hooks per harness, all ABSOLUTE, and the ONE place their spelling is\n * defined. See `HarnessRegistration` below, which is what makes \"per harness\" data rather than four\n * module constants that were only ever true of Claude Code.\n *\n * ─── ONE GOVERNOR: the MAIN tree judges every tree ─────────────────────────────────────────────────\n *\n * Claude Code — .claude/settings.json\n * H1 sh \"$CLAUDE_PROJECT_DIR/.claude/webpieces/ai-hook.sh\" wp-ai-guards-hook Write|…|Bash|Read\n * H2 sh \"$CLAUDE_PROJECT_DIR/.claude/webpieces/ai-hook.sh\" wp-ai-rules-hook Write|Edit|MultiEdit\n * Codex — .codex/hooks.json (the SAME `hooks.PreToolUse` JSON shape, measured)\n * H1 sh \"$PWD/.claude/webpieces/ai-hook.sh\" wp-ai-guards-hook Bash|apply_patch\n * H2 sh \"$PWD/.claude/webpieces/ai-hook.sh\" wp-ai-rules-hook apply_patch\n *\n * ONE shim file serves all four: `.claude/` there is a path, not a claim about who is calling.\n *\n * This REPLACES a three-hook form in which these two were RELATIVE (`sh \".claude/webpieces/ai-hook.sh\"`)\n * and a third hook, L-1 `guarantee-root.sh`, existed solely to guarantee that relative path resolved.\n *\n * ─── Why the relative experiment was reversed ──────────────────────────────────────────────────────\n * Relative registration was adopted so each git tree would be governed by \"its own release, binary and\n * pin\". MEASURED 2026-08-10: it never delivered that. A linked worktree has NO `node_modules`, so\n * ai-hook.sh's upward walk executes the PRIMARY's binary — `readlink -f` resolved a worktree agent's bin\n * to `<primary>/node_modules/@webpieces/ai-hook-rules`. A worktree ran its own SCRIPT and its own\n * CONFIG; it never ran its own release. Governance was already the primary's, in every tree, the whole\n * time.\n *\n * The price of that fiction was an entire guard layer. A relative path only resolves at a tree root, and\n * a hook that cannot resolve exits 127 — per the hooks reference a NON-BLOCKING error, i.e. a SILENT\n * UNGUARDED ALLOW. So L-1 had to deny every `cd` into a project subdirectory. That denial produced the\n * force-to-root bug class, the reaped-worktree `cd` prescription, and a measured hard deadlock: L-1 told\n * a worktree-isolated agent to `cd` to the primary clone, which the harness refuses for an isolated\n * agent, leaving it unable to stay or to follow the cure.\n *\n * An absolute path resolves from ANY cwd. So the launch guarantee is structural, L-1 has no job left and\n * is deleted, and `cd` into a subdirectory is simply allowed. What used to be true only by policing the\n * shell is now true by construction.\n *\n * ─── What replaces the property that was lost ──────────────────────────────────────────────────────\n * Nothing is lost that was ever delivered — but the case relative registration WANTED to handle (a tree\n * that genuinely needs a different @webpieces) is now DETECTED instead of silently mis-governed:\n * `VersionSyncGuard` (L1 row 8) blocks when a worktree's pin disagrees with the main tree's, and\n * prescribes either aligning the pins (same git hash → same tracked pin → install in each tree that has\n * a node_modules) or using a separate CLONE, which — unlike a worktree — gets its own GOVERNANCE. Note\n * what that does NOT say: a worktree may perfectly well have its own node_modules, and usually does the\n * moment anything installs in it. What it may not have is a DIFFERENT @webpieces version.\n *\n * ─── Why the registration is a DRIFT SURFACE, not just an install step ─────────────────────────────\n * Nothing used to validate `.claude/settings.json` at all, so a settings file left on a superseded form\n * silently changed who governs. The installed surface is FOUR things (ai-hook.sh, the registration, the\n * managed `env` entry — see managed-env.ts — and the ANCHORING of the NEIGHBOUR hook commands the\n * consumer registers beside ours, see neighbour-hooks.ts), all four are compared against this release,\n * and `wp-upgrade-shim` repairs all four. A cure that fixes three of four is worse than no cure, because\n * it reports success.\n */\n\n/**\n * The RETIRED L-1 hook's committed path. Named here, in the one module that must still recognise it, and\n * matched ONLY by isManagedCommand() so repairRegistration() can delete the stale entry. There is no\n * guarantee-root.ts any more — this literal is all that remains of it, deliberately.\n *\n * It is a one-way RECOGNISER, not a shim: nothing emits it, `expectedEntries()` never returns it, and a\n * settings file carrying it is reported STALE. Its only job is to make the retired entry findable so it\n * can be REMOVED.\n */\nexport const LEGACY_GUARANTEE_ROOT_MARKER = '.claude/webpieces/guarantee-root.sh';\n\n/**\n * When this recogniser may be deleted, as a value rather than a comment nobody re-reads.\n *\n * A removal-only migration is still dead weight once no consumer can be carrying the old shape. The\n * hazard of deleting it EARLY is severe and silent — repair would stop stripping the retired entry, and\n * a hook registered against a deleted file exits 127, which the Claude Code hooks reference defines as a\n * NON-BLOCKING error, i.e. every `cd` unjudged while the cure reports success. So it gets a stated date\n * and a test that fails once the date passes, instead of an intention.\n *\n * `legacy-marker-expiry.spec.ts` reads this and fails after it, which is the reminder.\n */\nexport const LEGACY_MARKER_REMOVE_AFTER = '2026-12-01';\n\n/** One PreToolUse hook entry as webpieces registers it. Data-only → a class, per CLAUDE.md. */\nexport class HookRegistrationEntry {\n constructor(\n readonly matcher: string,\n readonly command: string,\n ) {}\n\n sameAs(other: HookRegistrationEntry): boolean {\n return this.matcher === other.matcher && this.command === other.command;\n }\n}\n\n/**\n * THE SETTINGS-FILE SHAPE lives in `./settings-shape`, a LEAF module, and is imported from THERE by\n * everything that needs it — this module included. It is deliberately NOT re-exported here: a second\n * import path for one type is the \"two spellings of one thing\" shim the compatibility policy rejects,\n * and it would keep advertising `hook-registration` as a source of the shape, which is precisely the\n * edge that has to stay broken (`neighbour-hooks.ts` needs the shape, this module imports the repairs\n * FROM it, and `validate-no-file-import-cycles` counts even a type-only edge back as a cycle).\n */\n\nexport const RULES_BIN = 'wp-ai-rules-hook';\nexport const GUARDS_BIN = 'wp-ai-guards-hook';\n\n/**\n * ONE HARNESS'S registration surface — where its hooks live, what they match, and how they name the\n * shim. Data-only → a class, per CLAUDE.md.\n *\n * ─── Why this exists ──────────────────────────────────────────────────────────────────────────────\n * The matchers and the shim command used to be four module constants written for Claude Code alone.\n * Applied to Codex they are wrong in both halves, and the way they are wrong is SILENT:\n *\n * - MATCHER. Codex's file-editing tool is `apply_patch` (MEASURED, codex-cli 0.151.0). A matcher of\n * `Write|Edit|MultiEdit` matches it never, so every file rule is unreachable while the settings file\n * looks perfectly installed. Its shell tool IS called `Bash` — Codex reuses Claude's name — which is\n * the trap: half the matcher works, so the hooks appear to be running.\n * - ANCHOR. `$CLAUDE_PROJECT_DIR` does not exist in a Codex hook's environment (measured: 46 vars, no\n * such key), so the command expands to `sh \"/.claude/webpieces/ai-hook.sh\"`, which dies — and per the\n * hooks protocol a non-2 non-zero exit is a NON-BLOCKING error, i.e. a silent unguarded allow.\n *\n * Both halves of that were live in real repos, written by a Codex Desktop sync that transliterated the\n * Claude setup. Making the registration per-harness DATA is what stops a future harness inheriting a\n * matcher that was never true for it.\n *\n * ─── ONE SHIM, both harnesses ─────────────────────────────────────────────────────────────────────\n * `SHIM_MARKER` is shared deliberately: `.claude/webpieces/ai-hook.sh` is the single fail-closed entry\n * point, and moving or duplicating it would double the L0 allowlist regexes, the drift surfaces and the\n * cures. The `.claude/` prefix is a path, not a claim about which agent is calling.\n */\nexport class HarnessRegistration {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n readonly aiType: AiType,\n /** How the installer and the drift report name this harness to a human. */\n readonly label: string,\n /** Which tool names the RULES hook (code-style, file-scoped) must see. */\n readonly rulesMatcher: string,\n /**\n * Which tool names the GUARDS hook must see. Wider than the rules matcher by the shell tool and,\n * for Claude Code, by `Read` — Read carries no guard, but the guards hook owns the\n * per-invocation audit log, so matching it records every file the AI opens (log-and-allow fast\n * path in hook-core.ts; a Read is never blocked). Codex has no Read tool at all: a read arrives\n * as `Bash` running a pager, which the shell matcher already covers and read-parity synthesizes.\n */\n readonly guardsMatcher: string,\n /** The settings files this harness's hooks can be installed into, relative to the repo root. */\n readonly settingsFiles: readonly string[],\n /**\n * THE PREFIX THE SHIM PATH IS ANCHORED ON, and the reason each harness needs its own.\n *\n * **BYTE-STABILITY IS A HARD CONSTRAINT ON THE CODEX VALUE.** Codex trusts a hook entry\n * TOFU — `~/.codex/config.toml` records a `trusted_hash` per entry — so ANY change to these bytes\n * invalidates that trust and re-prompts the human, whose third option is `Continue without\n * trusting (hooks won't run)`: one keystroke to a silently unguarded session. Changing this\n * string is therefore never a cosmetic edit. The hash is NOT reproducible from outside Codex\n * (16 encodings tried against a file we authored), so the installer can never repair trust for\n * itself — see ./codex-trust.ts, which REPORTS and never writes.\n */\n readonly shimAnchor: string,\n /**\n * True when this harness's settings file also carries the managed `env` block. Claude Code's\n * settings `env` is inherited by every subagent, which is what makes it the right home for the\n * Bash-cwd pin (see managed-env.ts). Codex has no equivalent surface — and needs none: its cwd\n * is MEASURED not to drift at all (`cd x && pwd` prints x, the next call is back at the repo\n * root, for the coordinator and for subagents alike).\n */\n readonly managesEnv: boolean,\n /** What `managedSurfaceDrift()` calls this harness's registration when it has moved. */\n readonly registrationSurface: string,\n ) {}\n\n /** Which matcher one guard bin registers under. */\n matcherFor(bin: string): string {\n return bin === RULES_BIN ? this.rulesMatcher : this.guardsMatcher;\n }\n\n /**\n * The guard-hook command — `sh \"<anchor>/.claude/webpieces/ai-hook.sh\" <bin>`.\n *\n * ABSOLUTE, in both harnesses. Claude's anchor replaced a RELATIVE spelling and that reversal is\n * documented at length in this file's header: relative resolves only at a tree root, a hook that\n * cannot resolve exits 127, and per the hooks reference that is a NON-BLOCKING error — a silent\n * unguarded allow. It also cost an entire guard layer (L-1) whose only job was to police the `cd`\n * that made the relative path resolvable.\n *\n * Invoked via `sh <file>` rather than executed directly so a missing executable bit on the\n * checked-in shim (fresh clone, a filesystem that drops the bit, git core.fileMode quirks) can never\n * break the hook with a raw `Permission denied` on every tool call. Quoted to survive spaces.\n */\n shimCommand(bin: string): string {\n return `sh \"${this.shimAnchor}/${SHIM_MARKER}\" ${bin}`;\n }\n\n /** The registration entry for one guard bin under this harness. */\n entryFor(bin: string): HookRegistrationEntry {\n return new HookRegistrationEntry(this.matcherFor(bin), this.shimCommand(bin));\n }\n\n /** This harness's settings files under one repo root, absolute. */\n settingsPaths(projectRoot: string): readonly string[] {\n return this.settingsFiles.map((file: string): string => path.join(projectRoot, ...file.split('/')));\n }\n\n /**\n * What `managedSurfaceDrift()` calls this harness's NEIGHBOUR hook commands — the entries a CONSUMER\n * repo registers in the same file — when one of them still carries a repo-RELATIVE entry path.\n *\n * DERIVED rather than a constructor field, unlike `registrationSurface` beside it, because there is\n * nothing here a harness could sensibly disagree about: it is the same file, said a second way. A\n * constructor param would be a second place to keep in step for no decision.\n */\n get neighbourSurface(): string {\n return `${this.settingsFiles[0]} ${NEIGHBOUR_SURFACE_SUFFIX}`;\n }\n}\n\nexport const CLAUDE_REGISTRATION = new HarnessRegistration(\n 'claude-code', 'Claude Code',\n 'Write|Edit|MultiEdit',\n 'Write|Edit|MultiEdit|Bash|Read',\n ['.claude/settings.json', '.claude/settings.local.json'],\n '$CLAUDE_PROJECT_DIR',\n true,\n '.claude/settings.json hook registration',\n);\n\n/**\n * Codex's registration, every value of it MEASURED against codex-cli 0.151.0 rather than assumed.\n *\n * `$PWD` is the anchor because there is no project-dir variable to use and none is needed: the payload\n * `cwd` and the hook process's own `PWD` are both the repo root on EVERY call — for the coordinator and\n * for subagents — and a `cd` inside one command never survives into the next. That was measured, not\n * hoped for, and it is the same effect Claude Code gets from the managed\n * `CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR` env entry. See `shimAnchor` for why these exact bytes are\n * not free to change.\n */\nexport const CODEX_REGISTRATION = new HarnessRegistration(\n 'codex', 'Codex',\n 'apply_patch',\n 'Bash|apply_patch',\n ['.codex/hooks.json'],\n '$PWD',\n false,\n '.codex/hooks.json hook registration',\n);\n\n/**\n * Every harness webpieces arms, in installer order.\n *\n * The drift check, the repair and the installer all iterate THIS, so a harness cannot be armed by the\n * installer and then left unvalidated — which is exactly the state `.codex/hooks.json` was in before it\n * was a managed surface: written by something else, silently wrong, and invisible to every check.\n */\nexport const HARNESS_REGISTRATIONS: readonly HarnessRegistration[] = [CLAUDE_REGISTRATION, CODEX_REGISTRATION];\n\n/**\n * True when this PreToolUse command is one webpieces owns — in ANY spelling it has ever shipped.\n *\n * THE SINGLE MOST IMPORTANT LINE IN THIS RELEASE. `LEGACY_GUARANTEE_ROOT_MARKER` is matched here and\n * NOWHERE else: it is how `repairRegistration()` finds and REMOVES the retired H1 entry from a settings\n * file written by an older release. Drop it and the repair silently leaves a live L-1 hook registered\n * against a file this release deletes — exit 127, which the Claude Code hooks reference defines as a\n * NON-BLOCKING error, so every `cd` goes unjudged while `wp-upgrade-shim` reports success and no drift\n * check can name it. Removal-only, never emitted: it appears in no `expectedEntries()` result, so it is\n * a one-way migration and not a second accepted spelling.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function isManagedCommand(command: string): boolean {\n return command.includes(SHIM_MARKER) || command.includes(LEGACY_GUARANTEE_ROOT_MARKER);\n}\n\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nfunction preToolUse(settings: ClaudeSettings): readonly HookEntry[] {\n return settings.hooks?.PreToolUse ?? [];\n}\n\n/** Every webpieces-managed entry of one settings file, flattened to matcher + command pairs. */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function managedEntries(settings: ClaudeSettings): readonly HookRegistrationEntry[] {\n const found: HookRegistrationEntry[] = [];\n for (const entry of preToolUse(settings)) {\n for (const hook of entry.hooks) {\n if (isManagedCommand(hook.command)) found.push(new HookRegistrationEntry(entry.matcher, hook.command));\n }\n }\n return found;\n}\n\n/**\n * Which guard bins this settings file registers, in installer order. A file registering NEITHER is not\n * a project (relative) install and is therefore never judged — a global/absolute install names the bin\n * path directly and carries no shim marker at all.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function registeredBins(settings: ClaudeSettings): readonly string[] {\n const commands = managedEntries(settings).map((e: HookRegistrationEntry): string => e.command);\n return [GUARDS_BIN, RULES_BIN].filter((bin: string): boolean => commands.some((c: string): boolean => c.includes(bin)));\n}\n\n/**\n * The exact set of entries THIS RELEASE expects in a settings file that registers `bins`.\n *\n * ONE entry per registered bin, and nothing else. There used to be a third, `guarantee-root.sh`, added\n * whenever the GUARDS bin was present; it is retired, and a settings file still carrying it is STALE —\n * `repairRegistration()` removes it via isManagedCommand()'s legacy marker.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as HarnessRegistration's siblings\nexport function expectedEntries(harness: HarnessRegistration, bins: readonly string[]): readonly HookRegistrationEntry[] {\n return bins.map((bin: string): HookRegistrationEntry => harness.entryFor(bin));\n}\n\n/**\n * True when a settings file registers webpieces hooks in a shape this release does not expect: a\n * RELATIVE shim command, a leftover guarantee-root entry, a stray duplicate, or a wrong matcher.\n *\n * Compared as a SET, not a sequence: Claude Code runs all matching hooks in parallel, so array order\n * carries no meaning and reordering must not read as drift.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function registrationStale(harness: HarnessRegistration, settings: ClaudeSettings): boolean {\n const bins = registeredBins(settings);\n if (bins.length === 0) return false;\n const have = managedEntries(settings);\n const want = expectedEntries(harness, bins);\n if (have.length !== want.length) return true;\n return want.some((w: HookRegistrationEntry): boolean => !have.some((h: HookRegistrationEntry): boolean => h.sameAs(w)));\n}\n\n/** Drop every webpieces-managed PreToolUse command; returns true if anything was removed. */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function dropManagedEntries(settings: ClaudeSettings): boolean {\n const entries = settings.hooks?.PreToolUse;\n if (!entries) return false;\n let changed = false;\n const kept: HookEntry[] = [];\n for (const entry of entries) {\n const hooks = entry.hooks.filter((h: HookCommand): boolean => !isManagedCommand(h.command));\n if (hooks.length !== entry.hooks.length) changed = true;\n if (hooks.length > 0) kept.push({ matcher: entry.matcher, hooks });\n }\n if (changed) settings.hooks!.PreToolUse = kept;\n return changed;\n}\n\n/** Append one PreToolUse entry. */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function addHookEntry(settings: ClaudeSettings, entry: HookRegistrationEntry): void {\n if (!settings.hooks) settings.hooks = {};\n if (!Array.isArray(settings.hooks.PreToolUse)) settings.hooks.PreToolUse = [];\n settings.hooks.PreToolUse.push({ matcher: entry.matcher, hooks: [{ type: 'command', command: entry.command }] });\n}\n\n/** The settings `env` block, or null when the file carries none (or carries junk in its place). */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nfunction settingsEnv(settings: ClaudeSettings): Record<string, string> | null {\n // webpieces-disable no-any-unknown -- settings.json is opaque consumer JSON; `env` is only typed after this check\n const env: unknown = settings.env;\n if (typeof env !== 'object' || env === null || Array.isArray(env)) return null;\n return env as Record<string, string>;\n}\n\n/**\n * True when a settings file that registers webpieces hooks is missing the managed `env` entry, or\n * carries any value other than the one required one.\n *\n * Gated on `registeredBins()` for the SAME reason `registrationStale()` is: a settings file that\n * registers no webpieces hooks is not a project install and is never judged — a global install names\n * the bin path directly and carries no shim marker at all, so there is nothing here to keep in step.\n *\n * NOTE what this entry is for NOW. It was originally justified by keeping the then-RELATIVE hook path\n * resolvable; that job is retired, because both hooks are absolute and resolve from any cwd. It is kept\n * for VERDICT STABILITY — a guard's answer must depend on the command, not on where an earlier `cd` left\n * the shell — and because settings `env` is inherited, every subagent shares that cwd and therefore that\n * verdict. See managed-env.ts, which states this at length.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function envStale(settings: ClaudeSettings): boolean {\n if (registeredBins(settings).length === 0) return false;\n const env = settingsEnv(settings);\n return env === null || env[BASH_CWD_ENV_KEY] !== BASH_CWD_ENV_VALUE;\n}\n\n/**\n * Set the managed `env` entry IN PLACE, whatever was there before. Returns true when it changed.\n *\n * A user-set `\"0\"` is BROUGHT TO `\"1\"`, not honoured: this is a managed surface, and \"webpieces sets it\n * unless you disagreed\" would be a second, invisible spelling of the decision. Turning it off means\n * uninstalling the hooks, exactly as it does for every other managed thing.\n *\n * UNGATED on purpose — the installer calls it for the file it is writing hooks into, and the gate lives\n * at the caller (repairRegistration / applyHook), so a file with no webpieces hooks is never touched.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function applyManagedEnv(settings: ClaudeSettings): boolean {\n const existing = settingsEnv(settings);\n if (existing !== null && existing[BASH_CWD_ENV_KEY] === BASH_CWD_ENV_VALUE) return false;\n const env = existing ?? {};\n env[BASH_CWD_ENV_KEY] = BASH_CWD_ENV_VALUE;\n settings.env = env;\n return true;\n}\n\n/**\n * Bring one settings object to the two-hook ABSOLUTE form AND the managed `env` entry IN PLACE. Returns\n * true when it changed anything.\n *\n * REMOVE-then-ADD for the hooks, never add-beside: two spellings of one registration is exactly the\n * compatibility shim the backwards-compat reviewer rejects, and leaving a RELATIVE entry beside the\n * absolute one would run two shims per call — the\n * straddle this whole change exists to delete.\n *\n * THE TWO REPAIRS ARE EVALUATED INDEPENDENTLY, and that is load-bearing rather than tidy: this used to\n * early-return on `!registrationStale(settings)`, so a repo whose hooks are already current but whose\n * `env` entry is missing — the state EVERY existing consumer is in the moment this release lands — would\n * have been reported as drifted by fault S and then left unrepaired by its own prescribed cure. A cure\n * that skips half the surface is the failure mode `upgrade-shim.ts`'s header exists to prevent.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function repairRegistration(harness: HarnessRegistration, settings: ClaudeSettings): boolean {\n const bins = registeredBins(settings);\n if (bins.length === 0) return false;\n let changed = false;\n if (registrationStale(harness, settings)) {\n dropManagedEntries(settings);\n for (const entry of expectedEntries(harness, bins)) addHookEntry(settings, entry);\n changed = true;\n }\n // Only where the harness HAS that surface. Codex's hooks.json has no `env` block to manage, and\n // inventing one there would write a key Codex does not read — a managed surface nothing consumes is\n // a surface that can drift with no consequence and no way to notice.\n if (harness.managesEnv && applyManagedEnv(settings)) changed = true;\n return changed;\n}\n\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function readSettings(settingsPath: string): ClaudeSettings {\n if (!fs.existsSync(settingsPath)) return {};\n const raw = fs.readFileSync(settingsPath, 'utf8');\n if (raw.trim() === '') return {};\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return JSON.parse(raw) as ClaudeSettings;\n } catch (err: unknown) {\n const error = toError(err);\n throw new Error(`${settingsPath} has invalid JSON — fix it, then retry: ${error.message}`, { cause: error });\n }\n}\n\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as shimCommand above\nexport function writeSettings(settingsPath: string, settings: ClaudeSettings): void {\n fs.mkdirSync(path.dirname(settingsPath), { recursive: true });\n fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 4) + '\\n');\n}\n\n/**\n * True when any settings file ONE HARNESS owns under `root` carries a NEIGHBOUR hook — one the consumer\n * repo wrote — whose entry path is repo-RELATIVE and would therefore fail to resolve from any cwd but\n * the root. See neighbour-hooks.ts for the measured failure and why webpieces owns the repair.\n *\n * Judged ONLY where the file registers webpieces hooks, exactly like `registrationStaleAt` below: a\n * settings file with no webpieces hooks in it is not a webpieces install, and webpieces rewriting\n * somebody's unrelated hook lines there would be editing a file it was never given.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as HarnessRegistration's siblings\nexport function neighbourHooksStaleAt(harness: HarnessRegistration, root: string | null): boolean {\n if (root === null) return false;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return harness.settingsPaths(root).some((p: string): boolean => {\n const settings = readSettings(p);\n return registeredBins(settings).length > 0 && neighbourHooksStale(harness.shimAnchor, settings, root);\n });\n } catch (err: unknown) {\n const error = toError(err);\n void error; // best-effort: unreadable/invalid settings counts as \"not stale\" so it never wedges a call\n return false;\n }\n}\n\n/**\n * True when any settings file ONE HARNESS owns under `root` carries a stale registration.\n *\n * Per harness, not per repo, so the drift report can NAME which one moved — `.claude/settings.json` and\n * `.codex/hooks.json` have different cures, and a fault that says only \"the registration is stale\" sends\n * the reader to the wrong file half the time.\n *\n * A file that does not exist, or exists and registers no webpieces hooks, is never judged (see\n * `registrationStale`). That is what keeps a repo which has never armed Codex from suddenly faulting on\n * a `.codex/hooks.json` it does not have.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as HarnessRegistration's siblings\nexport function registrationStaleAt(harness: HarnessRegistration, root: string | null): boolean {\n if (root === null) return false;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return harness.settingsPaths(root).some((p: string): boolean => registrationStale(harness, readSettings(p)));\n } catch (err: unknown) {\n const error = toError(err);\n void error; // best-effort: unreadable/invalid settings counts as \"not stale\" so it never wedges a call\n return false;\n }\n}\n\n/**\n * True when either Claude project settings file under `root` is missing the managed `env` entry.\n *\n * CLAUDE-ONLY by construction, and stated as such rather than looped over the harnesses: `env` is a\n * Claude Code settings surface, Codex has no equivalent, and Codex's cwd is measured not to drift, which\n * is the whole thing the entry is for. See HarnessRegistration.managesEnv.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as HarnessRegistration's siblings\nexport function envStaleAt(root: string | null): boolean {\n if (root === null) return false;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return CLAUDE_REGISTRATION.settingsPaths(root).some((p: string): boolean => envStale(readSettings(p)));\n } catch (err: unknown) {\n const error = toError(err);\n void error; // best-effort: unreadable/invalid settings counts as \"not stale\" so it never wedges a call\n return false;\n }\n}\n\n/**\n * WHAT was rewritten in ONE settings file. Data-only → a class, per CLAUDE.md.\n *\n * Two independent flags rather than one path, because the cure has to be able to SAY which repair it\n * made: \"rewrote the hook registration\" printed for a file whose registration was already current and\n * whose `env` entry was the only thing missing is a cure lying about its own work.\n */\nexport class SettingsRepair {\n constructor(\n readonly settingsPath: string,\n readonly registration: boolean,\n readonly env: boolean,\n /**\n * The NEW spelling of every NEIGHBOUR hook command this repair anchored — the consumer's own\n * entries, which webpieces rewrites but does not author.\n *\n * The commands themselves rather than a count or a flag, because this is the one repair that\n * edits lines webpieces did not write: the cure has to be able to show the consumer exactly what\n * it changed in their file, or it is a silent edit to somebody else's hooks.\n */\n readonly anchoredNeighbours: readonly string[],\n ) {}\n}\n\n/**\n * Rewrite every stale settings file under `root`, for EVERY harness; returns what changed, per file.\n *\n * Existing files only — this never CREATES a registration. Arming a harness is the installer's decision\n * (`wp-install-ai-hooks`); this is the cure for one that has already been armed and has drifted, so a\n * repo that has never armed Codex is left exactly as it was.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as HarnessRegistration's siblings\nexport function repairRegistrationAt(root: string): readonly SettingsRepair[] {\n const repairs: SettingsRepair[] = [];\n for (const harness of HARNESS_REGISTRATIONS) {\n for (const settingsPath of harness.settingsPaths(root)) {\n if (!fs.existsSync(settingsPath)) continue;\n const settings = readSettings(settingsPath);\n const neededRegistration = registrationStale(harness, settings);\n const neededEnv = harness.managesEnv && envStale(settings);\n const changedManaged = repairRegistration(harness, settings);\n // AFTER the managed repair, never before: repairRegistration() removes the retired\n // guarantee-root entry and rewrites the two managed commands, so by the time the neighbour\n // pass runs there is nothing webpieces-owned left for it to look at. Gated on\n // registeredBins() for the same reason every other judgement here is — a settings file that\n // registers no webpieces hooks is not a webpieces install, and rewriting somebody's\n // unrelated hook lines in it would be webpieces editing a file it was never given.\n const anchored = registeredBins(settings).length === 0 ? [] : anchorNeighbourHooks(harness.shimAnchor, settings, root);\n if (!changedManaged && anchored.length === 0) continue;\n writeSettings(settingsPath, settings);\n repairs.push(new SettingsRepair(settingsPath, neededRegistration, neededEnv, anchored));\n }\n }\n return repairs;\n}\n\n/**\n * The names the drift check reports, so a deny can say WHICH surface moved.\n *\n * There were four, then three, and there are now FOUR again — but the fourth is not the one that was\n * deleted. `GUARANTEE_ROOT_SURFACE` went with L-1 itself: an absolutely-registered shim resolves from\n * any cwd, so there is no launch guarantee left to police and no second .sh file to keep byte-locked. A\n * settings file still carrying the retired H1 entry is not its own surface — it is ordinary REGISTRATION\n * drift, which `registrationStaleAt()` reports and `repairRegistration()` fixes by removing it.\n *\n * The new fourth is `.codex/hooks.json`, and it is here because of what happened while it was NOT a\n * managed surface: something else wrote it, with a matcher that matched no Codex file tool and a shim\n * path anchored on a variable Codex does not set, and no check in this package could see it. A file the\n * guards depend on and nothing validates is the exact shape of that incident.\n *\n * Each harness's registration surface is its own name, from HarnessRegistration.registrationSurface, so\n * the deny sends the reader to the file that actually moved.\n */\nexport const SHIM_SURFACE = SHIM_MARKER;\nexport const REGISTRATION_SURFACE = CLAUDE_REGISTRATION.registrationSurface;\nexport const CODEX_REGISTRATION_SURFACE = CODEX_REGISTRATION.registrationSurface;\nexport const ENV_SURFACE = `.claude/settings.json env.${BASH_CWD_ENV_KEY}`;\n// The generic PR-gate reviewer agent (issue #938): committed, generated, byte-stable — the same contract as\n// the shim, so the same check and the same cure.\nexport const REVIEWER_AGENT_SURFACE = REVIEWER_AGENT_MARKER;\n\n/**\n * WHICH of the managed surfaces disagree with this release — the input to fault S.\n *\n * All of them are checked against the SAME root, resolved from the RUNNING MODULE (governingShimRoot),\n * never from cwd and never from `$CLAUDE_PROJECT_DIR`: the files we compare and the renderers we\n * compare them TO must come from one install, or the check straddles two trees and can never converge.\n */\n// webpieces-disable no-function-outside-class -- module-scope for the same dependency-free reason as HarnessRegistration's siblings\nexport function managedSurfaceDrift(root: string | null): readonly string[] {\n const drifted: string[] = [];\n if (committedShimStale(root)) drifted.push(SHIM_SURFACE);\n for (const harness of HARNESS_REGISTRATIONS) {\n if (registrationStaleAt(harness, root)) drifted.push(harness.registrationSurface);\n // A neighbour hook registered with a RELATIVE entry path dies from any cwd but the root, and per\n // the hooks reference that non-zero exit is a NON-BLOCKING error — a SILENT UNGUARDED ALLOW. It\n // is a drift surface for exactly the reason the managed registration is one: nothing else in\n // this repo can see it, and the way it fails looks like a guard that PASSED. See\n // neighbour-hooks.ts, and issue #852 where it silently disarmed three security guards.\n if (neighbourHooksStaleAt(harness, root)) drifted.push(harness.neighbourSurface);\n }\n if (envStaleAt(root)) drifted.push(ENV_SURFACE);\n if (reviewerAgentStale(root)) drifted.push(REVIEWER_AGENT_SURFACE);\n return drifted;\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { AiType } from '../core/agent-event';
1
+ import { AiType } from '@webpieces/hook-runtime';
2
2
  /**
3
3
  * THE DECISION — `isAllowed()`, the ONE question sh and JS both ask, and the two tool-shaped facts it
4
4
  * needs that no regex can express.
@@ -1 +1 @@
1
- {"version":3,"file":"l0-decide.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/bin/l0-decide.ts"],"names":[],"mappings":";;;AAmDA,8BAcC;AAmBD,wCASC;;AA7FD,+CAAyB;AACzB,mDAA6B;AAE7B,0DAA0D;AAG1D,iDAAiE;AACjE,mDAAoD;AACpD,yDAAsD;AAEtD;;;;;;;;;;;;GAYG;AACH,4FAA4F;AAC5F,EAAE;AACF,2FAA2F;AAC3F,uGAAuG;AACvG,oGAAoG;AACpG,wGAAwG;AACxG,uGAAuG;AACvG,yFAAyF;AAC5E,QAAA,UAAU,GAAwB,IAAI,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;AAEjE;;;;;;;;;;;;;;;;GAgBG;AACH,iMAAiM;AACjM,SAAgB,SAAS,CAAC,QAAgB,EAAE,OAAe,EAAE,QAAgB,EAAE,MAAc;IACzF,IAAI,kBAAU,CAAC,GAAG,CAAC,QAAQ,CAAC;QAAE,OAAO,MAAM,CAAC;IAC5C,oGAAoG;IACpG,qEAAqE;IACrE,IAAI,mCAAgB,CAAC,GAAG,CAAC,QAAQ,CAAC;QAAE,OAAO,MAAM,CAAC;IAClD,IAAI,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,KAAK,8BAAe;QAAE,OAAO,MAAM,CAAC;IAC/D,IAAI,cAAc,CAAC,QAAQ,CAAC;QAAE,OAAO,MAAM,CAAC;IAC5C,IAAI,0BAAW,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC;QAAE,OAAO,OAAO,CAAC;IACrD,oGAAoG;IACpG,qGAAqG;IACrG,qGAAqG;IACrG,gGAAgG;IAChG,IAAI,MAAM,KAAK,OAAO,IAAI,iCAAiB,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC;QAAE,OAAO,MAAM,CAAC;IAChF,OAAO,IAAI,CAAC;AAChB,CAAC;AAED;;;;;;;;;;;;;;;GAeG;AACH,4HAA4H;AAC5H,SAAgB,cAAc,CAAC,QAAgB;IAC3C,IAAI,CAAC,iCAAkB,CAAC,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;QAAE,OAAO,KAAK,CAAC;IACnE,8DAA8D;IAC9D,IAAI,CAAC;QACD,OAAO,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,8BAAe,CAAC,CAAC,CAAC;IAC7E,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,+FAA+F;QAC/F,OAAO,KAAK,CAAC;IACjB,CAAC;AACL,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\n\nimport { CONFIG_FILENAME } from '@webpieces/rules-config';\n\nimport { AiType } from '../core/agent-event';\nimport { L0_ALLOW_JS, MANIFEST_FILENAMES } from './l0-allowlist';\nimport { L0_CODEX_ALLOW_JS } from './l0-codex-read';\nimport { L0_IGNORED_TOOLS } from './l0-ignored-tools';\n\n/**\n * THE DECISION — `isAllowed()`, the ONE question sh and JS both ask, and the two tool-shaped facts it\n * needs that no regex can express.\n *\n * Split out of ./l0-allowlist.ts (which was over the file-size limit) along the seam that was already\n * there: that module is the VOCABULARY — the named cure patterns and the one union built from them —\n * and this is what CONSULTS it. `shim.ts` re-exports both, so there is still ONE name to import L0 by\n * and every existing `from './shim'` import keeps working.\n *\n * The direction of the dependency is the reason for the split: this module imports the allowlist, the\n * allowlist imports nothing from here, and neither imports the rule engine — L0 must decide on a tree\n * too broken to load it.\n */\n// The non-Bash half of the same list, kept here so sh and JS answer the identical question.\n//\n// `Read` is on the list because you must be able to READ to know how to fix — the original\n// block-everything-but-the-cures version deadlocked a repo that also needed its config fixed. Note the\n// asymmetry this creates and why it is accepted: under S/C/Y the bin IS running, so an allowed Read\n// falls THROUGH to read-stale-guard and stale-main protection still holds; under D/X/K the bin is never\n// executed, so there is nothing to fall through to and the Read is genuinely unguarded. Narrowing this\n// entry to a path pattern is the fix for that, and is deliberately left for a follow-up.\nexport const READ_TOOLS: ReadonlySet<string> = new Set(['Read']);\n\n/**\n * `isAllowed(call)` — THE L0 allowlist, with no fault parameter. See the block comment above.\n *\n * Returns the OUTCOME KIND, because the two are not the same thing:\n * - 'pass' → L0 has no objection; fall THROUGH so L1/L2 still judge this call (Read, config edit).\n * - 'allow' → terminal; bypass everything, because a cure must stay reachable even when a downstream\n * guard would block it.\n * - null → not on the list.\n *\n * `CONFIG_FILENAME` stays a basename match on purpose — one per tree; narrowing it is its own question.\n *\n * `aiType` is REQUIRED, and there is no default. The harness is a fact of the call, not a preference,\n * and every caller already has it: the shim scrapes it in POSIX sh (AI_TYPE_SH) and the binary reads it\n * off the raw envelope (detectAiType). A default here would be a second spelling of \"which harness?\" —\n * the one that silently answers `claude-code` for a Codex call and re-creates the deadlock the gated\n * entry exists to remove.\n */\n// webpieces-disable no-function-outside-class -- pure predicate over the exported allowlist data, in the dependency-free shim module (it must load on a corrupt tree, so it cannot depend on DI)\nexport function isAllowed(toolName: string, command: string, filePath: string, aiType: AiType): 'pass' | 'allow' | null {\n if (READ_TOOLS.has(toolName)) return 'pass';\n // Nothing to judge — see L0_IGNORED_TOOLS. `pass`, never `allow`: L0 declines to be terminal, so on\n // a healthy tree the call still falls through to whatever runs next.\n if (L0_IGNORED_TOOLS.has(toolName)) return 'pass';\n if (path.basename(filePath) === CONFIG_FILENAME) return 'pass';\n if (isRootManifest(filePath)) return 'pass';\n if (L0_ALLOW_JS.test(command.trim())) return 'allow';\n // The HARNESS-GATED tail of the list, and the only place `aiType` is consulted. Codex has no `Read`\n // tool, so a read arrives here as a Bash command; without this it is denied under every L0 fault and\n // a Codex session cannot read the deny that is telling it what to run. `pass`, exactly like the Read\n // entry it twins — see the L0_CODEX_ALLOW_ERE header for why this union is anchored on its own.\n if (aiType === 'codex' && L0_CODEX_ALLOW_JS.test(command.trim())) return 'pass';\n return null;\n}\n\n/**\n * Is `filePath` the `package.json` / `pnpm-workspace.yaml` at the ROOT OF A GOVERNED TREE — the only two\n * files the version cure ever edits?\n *\n * AS WIDE AS THE CURE AND NO WIDER. A basename match would put EVERY project, app and library\n * `package.json` on the L0 allowlist, and at L0 that is worse than it sounds: the sh half treats a hit\n * as TERMINAL (`exit 0`, the guard bin never runs), so each of those would be editable under fault\n * D/X/U/K with nothing downstream judging it. BUT IT MUST ADMIT EVERY TREE, not one — a worktree\n * agent's cure edits ITS OWN root manifest, and the shim's `$ROOT` names whichever tree supplied the\n * shim (governingShimRoot's straddle), so neither a basename nor a fixed root is the right test.\n *\n * The test is: its own directory must ALSO hold a `webpieces.config.json`. That file is TRACKED, so the\n * main clone has one and every linked worktree has its own — the same definition `runner.ts` uses\n * (`dirname(configPath)`), without knowing which tree you stand in. A project manifest deep under\n * `packages/` has no config beside it and is excluded. The sh twin is one `[ -f ... ]` test.\n */\n// webpieces-disable no-function-outside-class -- pure fs+path predicate beside isAllowed in the dependency-free shim module\nexport function isRootManifest(filePath: string): boolean {\n if (!MANIFEST_FILENAMES.has(path.basename(filePath))) return false;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return fs.existsSync(path.join(path.dirname(filePath), CONFIG_FILENAME));\n } catch (err: unknown) {\n //const error = toError(err); best-effort on a blocking path: unreadable is NOT a root manifest\n return false;\n }\n}\n"]}
1
+ {"version":3,"file":"l0-decide.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/bin/l0-decide.ts"],"names":[],"mappings":";;;AAmDA,8BAcC;AAmBD,wCASC;;AA7FD,+CAAyB;AACzB,mDAA6B;AAE7B,0DAA0D;AAG1D,iDAAiE;AACjE,mDAAoD;AACpD,yDAAsD;AAEtD;;;;;;;;;;;;GAYG;AACH,4FAA4F;AAC5F,EAAE;AACF,2FAA2F;AAC3F,uGAAuG;AACvG,oGAAoG;AACpG,wGAAwG;AACxG,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E,CAAC;QACpB,+FAA+F;QAC/F,OAAO,KAAK,CAAC;IACjB,CAAC;AACL,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\n\nimport { CONFIG_FILENAME } from '@webpieces/rules-config';\n\nimport { AiType } from '@webpieces/hook-runtime';\nimport { L0_ALLOW_JS, MANIFEST_FILENAMES } from './l0-allowlist';\nimport { L0_CODEX_ALLOW_JS } from './l0-codex-read';\nimport { L0_IGNORED_TOOLS } from './l0-ignored-tools';\n\n/**\n * THE DECISION — `isAllowed()`, the ONE question sh and JS both ask, and the two tool-shaped facts it\n * needs that no regex can express.\n *\n * Split out of ./l0-allowlist.ts (which was over the file-size limit) along the seam that was already\n * there: that module is the VOCABULARY — the named cure patterns and the one union built from them —\n * and this is what CONSULTS it. `shim.ts` re-exports both, so there is still ONE name to import L0 by\n * and every existing `from './shim'` import keeps working.\n *\n * The direction of the dependency is the reason for the split: this module imports the allowlist, the\n * allowlist imports nothing from here, and neither imports the rule engine — L0 must decide on a tree\n * too broken to load it.\n */\n// The non-Bash half of the same list, kept here so sh and JS answer the identical question.\n//\n// `Read` is on the list because you must be able to READ to know how to fix — the original\n// block-everything-but-the-cures version deadlocked a repo that also needed its config fixed. Note the\n// asymmetry this creates and why it is accepted: under S/C/Y the bin IS running, so an allowed Read\n// falls THROUGH to read-stale-guard and stale-main protection still holds; under D/X/K the bin is never\n// executed, so there is nothing to fall through to and the Read is genuinely unguarded. Narrowing this\n// entry to a path pattern is the fix for that, and is deliberately left for a follow-up.\nexport const READ_TOOLS: ReadonlySet<string> = new Set(['Read']);\n\n/**\n * `isAllowed(call)` — THE L0 allowlist, with no fault parameter. See the block comment above.\n *\n * Returns the OUTCOME KIND, because the two are not the same thing:\n * - 'pass' → L0 has no objection; fall THROUGH so L1/L2 still judge this call (Read, config edit).\n * - 'allow' → terminal; bypass everything, because a cure must stay reachable even when a downstream\n * guard would block it.\n * - null → not on the list.\n *\n * `CONFIG_FILENAME` stays a basename match on purpose — one per tree; narrowing it is its own question.\n *\n * `aiType` is REQUIRED, and there is no default. The harness is a fact of the call, not a preference,\n * and every caller already has it: the shim scrapes it in POSIX sh (AI_TYPE_SH) and the binary reads it\n * off the raw envelope (detectAiType). A default here would be a second spelling of \"which harness?\" —\n * the one that silently answers `claude-code` for a Codex call and re-creates the deadlock the gated\n * entry exists to remove.\n */\n// webpieces-disable no-function-outside-class -- pure predicate over the exported allowlist data, in the dependency-free shim module (it must load on a corrupt tree, so it cannot depend on DI)\nexport function isAllowed(toolName: string, command: string, filePath: string, aiType: AiType): 'pass' | 'allow' | null {\n if (READ_TOOLS.has(toolName)) return 'pass';\n // Nothing to judge — see L0_IGNORED_TOOLS. `pass`, never `allow`: L0 declines to be terminal, so on\n // a healthy tree the call still falls through to whatever runs next.\n if (L0_IGNORED_TOOLS.has(toolName)) return 'pass';\n if (path.basename(filePath) === CONFIG_FILENAME) return 'pass';\n if (isRootManifest(filePath)) return 'pass';\n if (L0_ALLOW_JS.test(command.trim())) return 'allow';\n // The HARNESS-GATED tail of the list, and the only place `aiType` is consulted. Codex has no `Read`\n // tool, so a read arrives here as a Bash command; without this it is denied under every L0 fault and\n // a Codex session cannot read the deny that is telling it what to run. `pass`, exactly like the Read\n // entry it twins — see the L0_CODEX_ALLOW_ERE header for why this union is anchored on its own.\n if (aiType === 'codex' && L0_CODEX_ALLOW_JS.test(command.trim())) return 'pass';\n return null;\n}\n\n/**\n * Is `filePath` the `package.json` / `pnpm-workspace.yaml` at the ROOT OF A GOVERNED TREE — the only two\n * files the version cure ever edits?\n *\n * AS WIDE AS THE CURE AND NO WIDER. A basename match would put EVERY project, app and library\n * `package.json` on the L0 allowlist, and at L0 that is worse than it sounds: the sh half treats a hit\n * as TERMINAL (`exit 0`, the guard bin never runs), so each of those would be editable under fault\n * D/X/U/K with nothing downstream judging it. BUT IT MUST ADMIT EVERY TREE, not one — a worktree\n * agent's cure edits ITS OWN root manifest, and the shim's `$ROOT` names whichever tree supplied the\n * shim (governingShimRoot's straddle), so neither a basename nor a fixed root is the right test.\n *\n * The test is: its own directory must ALSO hold a `webpieces.config.json`. That file is TRACKED, so the\n * main clone has one and every linked worktree has its own — the same definition `runner.ts` uses\n * (`dirname(configPath)`), without knowing which tree you stand in. A project manifest deep under\n * `packages/` has no config beside it and is excluded. The sh twin is one `[ -f ... ]` test.\n */\n// webpieces-disable no-function-outside-class -- pure fs+path predicate beside isAllowed in the dependency-free shim module\nexport function isRootManifest(filePath: string): boolean {\n if (!MANIFEST_FILENAMES.has(path.basename(filePath))) return false;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return fs.existsSync(path.join(path.dirname(filePath), CONFIG_FILENAME));\n } catch (err: unknown) {\n //const error = toError(err); best-effort on a blocking path: unreadable is NOT a root manifest\n return false;\n }\n}\n"]}
@@ -9,7 +9,7 @@
9
9
  * NOT re-exported from here onward — `./shim` is the ONE name that gathers L0, and it stars this
10
10
  * module alongside the others.
11
11
  */
12
- import { AiType } from '../core/agent-event';
12
+ import { AiType } from '@webpieces/hook-runtime';
13
13
  /**
14
14
  * The token an L0 entry uses to say it serves EVERY harness — SAID OUT LOUD.
15
15
  *