@webpieces/ai-hook-rules 0.4.584 → 0.4.587
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -1
- package/package.json +2 -2
- package/src/adapters/hook-core.js +21 -12
- package/src/adapters/hook-core.js.map +1 -1
- package/src/bin/guarantee-root.d.ts +90 -0
- package/src/bin/guarantee-root.js +271 -0
- package/src/bin/guarantee-root.js.map +1 -0
- package/src/bin/l0-allowlist.js +1 -1
- package/src/bin/l0-allowlist.js.map +1 -1
- package/src/bin/shim-audit-log.js +21 -4
- package/src/bin/shim-audit-log.js.map +1 -1
- package/src/bin/shim.js +22 -2
- package/src/bin/shim.js.map +1 -1
- package/src/core/decision-log.d.ts +6 -2
- package/src/core/decision-log.js +12 -7
- package/src/core/decision-log.js.map +1 -1
- package/src/core/log-stream.d.ts +72 -0
- package/src/core/log-stream.js +104 -0
- package/src/core/log-stream.js.map +1 -0
- package/src/core/main-sync-log.d.ts +2 -1
- package/src/core/main-sync-log.js +9 -5
- package/src/core/main-sync-log.js.map +1 -1
- package/src/core/main-sync-refresh.d.ts +2 -1
- package/src/core/main-sync-refresh.js +2 -1
- package/src/core/main-sync-refresh.js.map +1 -1
- package/src/core/rejection-log.js +3 -2
- package/src/core/rejection-log.js.map +1 -1
- package/templates/ai-hook.sh +21 -4
- package/templates/guarantee-root.sh +110 -0
package/README.md
CHANGED
|
@@ -40,7 +40,8 @@ openclaw plugins enable @webpieces/ai-hook-rules
|
|
|
40
40
|
- `wp-ai-guards-hook` — matcher `Write|Edit|MultiEdit|Bash|Read`. Runs the git/PR/branch guards
|
|
41
41
|
(`hookGuards` section): bash git/PR guards on `Bash`, and file guards like
|
|
42
42
|
`feature-branch-guard` on `Write|Edit|MultiEdit`. `Read` carries no guard — it is a
|
|
43
|
-
log-and-allow fast path that records every file the AI opens in
|
|
43
|
+
log-and-allow fast path that records every file the AI opens in
|
|
44
|
+
`.webpieces/logs/<session>-<agent>-<hook>-guard-invocations.log`
|
|
44
45
|
(never blocked), so you can see whether the AI read a project's `design.json` before editing it.
|
|
45
46
|
|
|
46
47
|
For each hook the setup command prompts for a target: project `.claude/settings.json`,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webpieces/ai-hook-rules",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.587",
|
|
4
4
|
"description": "Pluggable write-time validation framework for AI coding agents (@webpieces/ai-hook-rules). Claude Code PreToolUse + openclaw before_tool_call adapters share one rule engine.",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"main": "./src/index.js",
|
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
"directory": "packages/tooling/ai-hook-rules"
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@webpieces/rules-config": "0.4.
|
|
28
|
+
"@webpieces/rules-config": "0.4.587"
|
|
29
29
|
},
|
|
30
30
|
"publishConfig": {
|
|
31
31
|
"access": "public"
|
|
@@ -16,6 +16,7 @@ const to_error_1 = require("../core/to-error");
|
|
|
16
16
|
const claude_code_response_1 = require("./claude-code-response");
|
|
17
17
|
const shim_1 = require("../bin/shim");
|
|
18
18
|
const l0_matrix_1 = require("../core/l0-matrix");
|
|
19
|
+
const log_stream_1 = require("../core/log-stream");
|
|
19
20
|
const HANDLED_FILE_TOOLS = new Set(['Write', 'Edit', 'MultiEdit']);
|
|
20
21
|
// Read-only tools carry NO guard or code rule, but the guards hook owns the per-invocation audit log
|
|
21
22
|
// (guard-invocations.log). When the guards matcher includes these (see setup.ts GUARDS_HOOK), a
|
|
@@ -227,6 +228,9 @@ async function runMain(mode) {
|
|
|
227
228
|
(0, claude_code_response_1.emitAllow)();
|
|
228
229
|
}
|
|
229
230
|
toolName = payload.tool_name;
|
|
231
|
+
// BEFORE enforceCommittedShim(), which can itself write a BLOCK line. See LogStream for why
|
|
232
|
+
// all three of session/agent/hook are needed to keep concurrent writers off one file.
|
|
233
|
+
log_stream_1.logStream.identify(payload.session_id ?? '', payload.agent_id ?? '', mode);
|
|
230
234
|
// Prefer the payload cwd (the AI's actual working dir, follows a persisted `cd`) over
|
|
231
235
|
// process.cwd(); they match today, but the payload is the authoritative signal and stays
|
|
232
236
|
// correct if the hook is ever invoked from a fixed dir (e.g. via $CLAUDE_PROJECT_DIR).
|
|
@@ -271,18 +275,23 @@ async function runMain(mode) {
|
|
|
271
275
|
}
|
|
272
276
|
catch (err) {
|
|
273
277
|
const error = (0, to_error_1.toError)(err);
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
278
|
+
denyForCrash(error, toolName);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* The fail-closed boundary for anything that escaped the hook body. An escaped RuleFailError (a rule
|
|
283
|
+
* that threw past the runner's per-rule catch) or an InformAiError (bad config/stdin) both carry an
|
|
284
|
+
* AI-readable message; anything else is an unexpected bug. All three DENY and surface their reason,
|
|
285
|
+
* because a hook that crashed established nothing and must never be read as an allow.
|
|
286
|
+
*/
|
|
287
|
+
// 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
|
|
288
|
+
function denyForCrash(error, toolName) {
|
|
289
|
+
if (error instanceof types_1.RuleFailError) {
|
|
290
|
+
(0, claude_code_response_1.emitDeny)(error.aiMessage, toolName, 'rule-crash');
|
|
291
|
+
}
|
|
292
|
+
if (error instanceof types_1.InformAiError) {
|
|
293
|
+
(0, claude_code_response_1.emitDeny)(error.message, toolName, 'bad-config-or-stdin');
|
|
286
294
|
}
|
|
295
|
+
(0, claude_code_response_1.emitDeny)(`[ai-hooks] hook crashed unexpectedly — failing closed: ${error.message}`, toolName, 'hook-crash');
|
|
287
296
|
}
|
|
288
297
|
//# sourceMappingURL=hook-core.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hook-core.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/adapters/hook-core.ts"],"names":[],"mappings":";;AA2OA,8DAKC;AAuCD,0BAqEC;;AA5VD,mDAA6B;AAE7B,2CAAuD;AACvD,uEAA6D;AAC7D,yDAAuE;AACvE,uDAAoG;AACpG,iEAAmE;AACnE,qDAAsD;AACtD,0DAAyD;AACzD,yCAAqI;AACrI,+CAA2C;AAC3C,iEAA6D;AAC7D,sCAA+H;AAC/H,iDAA4E;AAW5E,MAAM,kBAAkB,GAAG,IAAI,GAAG,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC;AAEnE,qGAAqG;AACrG,gGAAgG;AAChG,oGAAoG;AACpG,kGAAkG;AAClG,mDAAmD;AACnD,MAAM,eAAe,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;AA4B1C,SAAS,SAAS;IACd,OAAO,IAAI,OAAO,CAAC,CAAC,OAAgC,EAAE,EAAE;QACpD,IAAI,IAAI,GAAG,EAAE,CAAC;QACd,OAAO,CAAC,KAAK,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;QAClC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,KAAa,EAAE,EAAE,GAAG,IAAI,IAAI,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;QAChE,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC;QAC7C,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC;QAC7C,IAAI,OAAO,CAAC,KAAK,CAAC,KAAK;YAAE,OAAO,CAAC,EAAE,CAAC,CAAC;IACzC,C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AA0F;QAC1F,mFAAmF;QACnF,IAAI,KAAK,YAAY,qBAAa,EAAE,CAAC;YACjC,IAAA,+BAAQ,EAAC,KAAK,CAAC,SAAS,EAAE,QAAQ,EAAE,YAAY,CAAC,CAAC;QACtD,CAAC;aAAM,IAAI,KAAK,YAAY,qBAAa,EAAE,CAAC;YACxC,IAAA,+BAAQ,EAAC,KAAK,CAAC,OAAO,EAAE,QAAQ,EAAE,qBAAqB,CAAC,CAAC;QAC7D,CAAC;aAAM,CAAC;YACJ,IAAA,+BAAQ,EAAC,0DAA0D,KAAK,CAAC,OAAO,EAAE,EAAE,QAAQ,EAAE,YAAY,CAAC,CAAC;QAChH,CAAC;IACL,CAAC;AACL,CAAC","sourcesContent":["import * as path from 'path';\n\nimport { run, runBash, runRead } from '../core/runner';\nimport { AgentIdentity } from '../core/coordinator-worktree';\nimport { logRejection, extractRuleNames } from '../core/rejection-log';\nimport { logGuardDecision, GuardDecision, branchForLog, invocationLog } from '../core/decision-log';\nimport { triggerMainSyncRefresh } from '../core/main-sync-refresh';\nimport { CONFIG_FILENAME } from '../core/load-config';\nimport { RepoRootFinder } from '@webpieces/rules-config';\nimport { NormalizedToolInput, NormalizedEdit, ToolKind, InformAiError, RuleFailError, HookMode, BlockedResult } from '../core/types';\nimport { toError } from '../core/to-error';\nimport { emitDeny, emitAllow } from './claude-code-response';\nimport { committedShimStale, governingShimRoot, isAllowed, shimStaleDenyReason, installedShimRulesVersion } from '../bin/shim';\nimport { writeGuardMatrixDoc, guardMatrixPointer } from '../core/l0-matrix';\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 HANDLED_FILE_TOOLS = new Set(['Write', 'Edit', 'MultiEdit']);\n\n// Read-only tools carry NO guard or code rule, but the guards hook owns the per-invocation audit log\n// (guard-invocations.log). When the guards matcher includes these (see setup.ts GUARDS_HOOK), a\n// log-and-allow fast path records every file the AI opens — so a human can later inspect whether it\n// read a project's design.json BEFORE editing the project. Never blocked. Scoped to Read for now;\n// widen (Grep/Glob/NotebookRead) later if desired.\nconst READ_ONLY_TOOLS = new Set(['Read']);\n\ninterface ClaudeCodePayload {\n tool_name: string;\n tool_input: ClaudeCodeToolInput;\n // Claude Code sends the session's current working directory (follows a persisted `cd`). Used to\n // scope guards to the git repo the AI is actually in — see runner git-repo-boundary governance.\n cwd?: string;\n // Present ONLY when the hook fires inside a SUBAGENT. Absent = the coordinator (the main agent\n // loop) — there is no positive coordinator field to read. See AgentIdentity.\n agent_id?: string;\n agent_type?: string;\n}\n\ninterface ClaudeCodeToolInput {\n file_path?: string;\n content?: string;\n old_string?: string;\n new_string?: string;\n edits?: ClaudeCodeEditEntry[];\n command?: string;\n}\n\ninterface ClaudeCodeEditEntry {\n old_string?: string;\n new_string?: string;\n}\n\nfunction readStdin(): Promise<string> {\n return new Promise((resolve: (value: string) => void) => {\n let data = '';\n process.stdin.setEncoding('utf8');\n process.stdin.on('data', (chunk: string) => { data += chunk; });\n process.stdin.on('end', () => resolve(data));\n process.stdin.on('error', () => resolve(''));\n if (process.stdin.isTTY) resolve('');\n });\n}\n\nfunction safeParse(raw: string): ClaudeCodePayload | null {\n if (!raw || raw.trim() === '') return null;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return JSON.parse(raw) as ClaudeCodePayload;\n } catch (err: unknown) {\n const error = toError(err);\n throw new InformAiError(`Malformed hook input from Claude Code stdin: ${error.message}`, { cause: error });\n }\n}\n\nfunction normalizeToolKind(toolName: string): ToolKind | null {\n if (HANDLED_FILE_TOOLS.has(toolName)) return toolName as ToolKind;\n return null;\n}\n\nfunction normalizeToolInput(toolKind: ToolKind, toolInput: ClaudeCodeToolInput): NormalizedToolInput | null {\n const filePath = toolInput.file_path;\n if (!filePath) return null;\n\n if (toolKind === 'Write') {\n return new NormalizedToolInput(filePath, [\n new NormalizedEdit('', toolInput.content || ''),\n ]);\n }\n if (toolKind === 'Edit') {\n return new NormalizedToolInput(filePath, [\n new NormalizedEdit(toolInput.old_string || '', toolInput.new_string || ''),\n ]);\n }\n if (toolKind === 'MultiEdit') {\n const raw = Array.isArray(toolInput.edits) ? toolInput.edits : [];\n const edits = raw.map((e: ClaudeCodeEditEntry) => new NormalizedEdit(e.old_string || '', e.new_string || ''));\n return new NormalizedToolInput(filePath, edits);\n }\n return null;\n}\n\n// The caller behind this payload. Both fields are sent only inside a subagent, so BOTH absent (or\n// empty) is the coordinator — the one distinction CoordinatorWorktreeGuard turns on.\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction agentIdentityOf(payload: ClaudeCodePayload): AgentIdentity {\n return new AgentIdentity(payload.agent_id ?? '', payload.agent_type ?? '');\n}\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\nfunction handleBash(payload: ClaudeCodePayload, cwd: string, mode: HookMode): void {\n const command = payload.tool_input.command;\n if (!command || command.trim() === '') { emitAllow(); }\n const result = runBash(command, cwd, mode, agentIdentityOf(payload));\n if (!result) { emitAllow(); }\n // Persist the block + WHY. File-tool denies go to hook-rejection.log via logRejection, but a Bash\n // deny had no audit trail — record it in guard-sync-decisions.log so \"blocked and why\" is complete\n // for Bash too. `.webpieces` lives at the repo root, resolved from cwd. Best-effort; never blocks.\n const root = new RepoRootFinder().resolveRepoRoot(cwd);\n logGuardDecision(root, new GuardDecision('bash-guard', 'Bash', command ?? '', branchForLog(root), 'BLOCK', result.report));\n // Bash deny → pass 'Bash' so denyJson adds the ANSI-red systemMessage (the only field a Bash deny\n // shows the human; permissionDecisionReason is invisible on Bash). See claude-code-response.ts.\n emitDeny(result.report, 'Bash', blockingRule(result.report, 'bash-guard'));\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(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(result.report, 'Read', blockingRule(result.report, 'read-guard'));\n}\n\nfunction handleFileTool(payload: ClaudeCodePayload, cwd: string, mode: HookMode): void {\n const toolKind = normalizeToolKind(payload.tool_name);\n if (!toolKind) { emitAllow(); }\n\n const input = normalizeToolInput(toolKind, payload.tool_input);\n if (!input) { emitAllow(); }\n\n // Always allow edits to webpieces.config.json — it's the fix target when the config is broken.\n // This exits 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', toolKind, input.filePath, branchForLog(root), 'ALLOW', '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);\n }\n emitAllow();\n }\n\n const result = run(toolKind, input, cwd, mode);\n if (!result) { emitAllow(); }\n\n logRejection(toolKind, input, result, cwd);\n // File-tool deny → pass the Write/Edit/MultiEdit kind so denyJson omits systemMessage (the reason\n // already renders red natively for these tools). See claude-code-response.ts.\n emitDeny(result.report, toolKind, blockingRule(result.report, 'file-guard'));\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): ShimStaleDecision {\n const allowed = isAllowed(toolName, command, filePath);\n if (allowed === 'pass') return 'pass';\n if (allowed === 'allow') return 'allow-cure';\n return 'deny';\n}\n\n// Committed-shim self-guard, moved here from the rendered shim (2026-07-24). 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// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction enforceCommittedShim(payload: ClaudeCodePayload, 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' || !committedShimStale(shimRoot)) return;\n const decision = shimStaleRecoveryDecision(payload.tool_name, payload.tool_input.command ?? '', payload.tool_input.file_path ?? '');\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 docPath = writeGuardMatrixDoc(new RepoRootFinder().resolveRepoRoot(cwd));\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.\n emitDeny(shimStaleDenyReason(installedShimRulesVersion(), shimRoot ?? '') + guardMatrixPointer(docPath), payload.tool_name, 'committed-shim-stale');\n}\n\n/**\n * Shared entry point for all three Claude Code PreToolUse adapters. `mode` selects which tool kinds\n * to validate; payloads outside the mode's scope pass through (emitAllow). Blocks by emitting a\n * PreToolUse `permissionDecision:\"deny\"` JSON on stdout (exit 0) — see claude-code-response.ts. Fails\n * CLOSED on any unexpected crash (emits a deny) so a broken hook never silently lets an edit through,\n * and the reason now surfaces in the Claude Code UI instead of being hidden on a stderr+exit-2 block.\n */\nexport async function runMain(mode: HookMode): Promise<void> {\n // Captured from the payload as soon as it parses so the fail-closed catch below can tell denyJson\n // which tool it is denying — a crash on a Bash call still gets the visible red systemMessage, a\n // crash on a file tool does not. Empty (before parse / malformed input) → treated as non-Bash.\n let toolName = '';\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const raw = await readStdin();\n const payload = safeParse(raw);\n if (!payload) { emitAllow(); }\n toolName = payload.tool_name;\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, cwd, mode);\n\n // Read-only tools (Read): audit-log, warm the main-sync cache, then run the ONE read-scoped\n // guard (read-stale-guard) and allow. Runs BEFORE the general rule engine — no code-style rule\n // ever sees a Read, and the only way this path can deny is a stale `main`.\n // The audit trail still records every file the AI opened (see setup.ts).\n if (READ_ONLY_TOOLS.has(payload.tool_name)) {\n const readPath = payload.tool_input.file_path ?? '';\n if (mode !== 'rules') {\n invocationLog.begin(cwd, payload.tool_name, 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);\n }\n handleRead(readPath, cwd, mode);\n emitAllow();\n }\n\n // Per-invocation guard log (guard-invocations.log): 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 const target = payload.tool_name === 'Bash' ? (payload.tool_input.command ?? '') : (payload.tool_input.file_path ?? '');\n invocationLog.begin(cwd, payload.tool_name, target);\n }\n\n if (payload.tool_name === 'Bash') {\n // No code-style rule is bash-scoped, so the rules hook ignores Bash.\n if (mode === 'rules') { emitAllow(); }\n handleBash(payload, cwd, mode);\n return;\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(payload, cwd, mode);\n } catch (err: unknown) {\n const error = toError(err);\n // An escaped RuleFailError (a rule that threw past the runner's per-rule catch) or an\n // InformAiError (bad config/stdin) both carry an AI-readable message; anything else is an\n // unexpected bug. All three deny (fail closed) and surface their reason to the AI.\n if (error instanceof RuleFailError) {\n emitDeny(error.aiMessage, toolName, 'rule-crash');\n } else if (error instanceof InformAiError) {\n emitDeny(error.message, toolName, 'bad-config-or-stdin');\n } else {\n emitDeny(`[ai-hooks] hook crashed unexpectedly — failing closed: ${error.message}`, toolName, 'hook-crash');\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"hook-core.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/adapters/hook-core.ts"],"names":[],"mappings":";;AA6OA,8DAKC;AAuCD,0BAgEC;;AAzVD,mDAA6B;AAE7B,2CAAuD;AACvD,uEAA6D;AAC7D,yDAAuE;AACvE,uDAAoG;AACpG,iEAAmE;AACnE,qDAAsD;AACtD,0DAAyD;AACzD,yCAAqI;AACrI,+CAA2C;AAC3C,iEAA6D;AAC7D,sCAA+H;AAC/H,iDAA4E;AAC5E,mDAA+C;AAW/C,MAAM,kBAAkB,GAAG,IAAI,GAAG,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC;AAEnE,qGAAqG;AACrG,gGAAgG;AAChG,oGAAoG;AACpG,kGAAkG;AAClG,mDAAmD;AACnD,MAAM,eAAe,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;AA6B1C,SAAS,SAAS;IACd,OAAO,IAAI,OAAO,CAAC,CAAC,OAAgC,EAAE,EAAE;QACpD,IAAI,IAAI,GAAG,EAAE,CAAC;QACd,OAAO,CAAC,KAAK,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;QAClC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,KAAa,EAAE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AG,EAAE,OAAO,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC;QACxD,CAAC;QAED,IAAI,OAAO,CAAC,SAAS,KAAK,MAAM,EAAE,CAAC;YAC/B,qEAAqE;YACrE,IAAI,IAAI,KAAK,OAAO,EAAE,CAAC;gBAAC,IAAA,gCAAS,GAAE,CAAC;YAAC,CAAC;YACtC,UAAU,CAAC,OAAO,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC;YAC/B,OAAO;QACX,CAAC;QAED,+EAA+E;QAC/E,8EAA8E;QAC9E,cAAc,CAAC,OAAO,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC;IACvC,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,YAAY,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;IAClC,CAAC;AACL,CAAC;AAED;;;;;GAKG;AACH,oLAAoL;AACpL,SAAS,YAAY,CAAC,KAAY,EAAE,QAAgB;IAChD,IAAI,KAAK,YAAY,qBAAa,EAAE,CAAC;QACjC,IAAA,+BAAQ,EAAC,KAAK,CAAC,SAAS,EAAE,QAAQ,EAAE,YAAY,CAAC,CAAC;IACtD,CAAC;IACD,IAAI,KAAK,YAAY,qBAAa,EAAE,CAAC;QACjC,IAAA,+BAAQ,EAAC,KAAK,CAAC,OAAO,EAAE,QAAQ,EAAE,qBAAqB,CAAC,CAAC;IAC7D,CAAC;IACD,IAAA,+BAAQ,EAAC,0DAA0D,KAAK,CAAC,OAAO,EAAE,EAAE,QAAQ,EAAE,YAAY,CAAC,CAAC;AAChH,CAAC","sourcesContent":["import * as path from 'path';\n\nimport { run, runBash, runRead } from '../core/runner';\nimport { AgentIdentity } from '../core/coordinator-worktree';\nimport { logRejection, extractRuleNames } from '../core/rejection-log';\nimport { logGuardDecision, GuardDecision, branchForLog, invocationLog } from '../core/decision-log';\nimport { triggerMainSyncRefresh } from '../core/main-sync-refresh';\nimport { CONFIG_FILENAME } from '../core/load-config';\nimport { RepoRootFinder } from '@webpieces/rules-config';\nimport { NormalizedToolInput, NormalizedEdit, ToolKind, InformAiError, RuleFailError, HookMode, BlockedResult } from '../core/types';\nimport { toError } from '../core/to-error';\nimport { emitDeny, emitAllow } from './claude-code-response';\nimport { committedShimStale, governingShimRoot, isAllowed, shimStaleDenyReason, installedShimRulesVersion } from '../bin/shim';\nimport { writeGuardMatrixDoc, guardMatrixPointer } from '../core/l0-matrix';\nimport { logStream } from '../core/log-stream';\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 HANDLED_FILE_TOOLS = new Set(['Write', 'Edit', 'MultiEdit']);\n\n// Read-only tools carry NO guard or code rule, but the guards hook owns the per-invocation audit log\n// (guard-invocations.log). When the guards matcher includes these (see setup.ts GUARDS_HOOK), a\n// log-and-allow fast path records every file the AI opens — so a human can later inspect whether it\n// read a project's design.json BEFORE editing the project. Never blocked. Scoped to Read for now;\n// widen (Grep/Glob/NotebookRead) later if desired.\nconst READ_ONLY_TOOLS = new Set(['Read']);\n\ninterface ClaudeCodePayload {\n tool_name: string;\n tool_input: ClaudeCodeToolInput;\n // Claude Code sends the session's current working directory (follows a persisted `cd`). Used to\n // scope guards to the git repo the AI is actually in — see runner git-repo-boundary governance.\n cwd?: string;\n // Present ONLY when the hook fires inside a SUBAGENT. Absent = the coordinator (the main agent\n // loop) — there is no positive coordinator field to read. See AgentIdentity.\n session_id?: string;\n agent_id?: string;\n agent_type?: string;\n}\n\ninterface ClaudeCodeToolInput {\n file_path?: string;\n content?: string;\n old_string?: string;\n new_string?: string;\n edits?: ClaudeCodeEditEntry[];\n command?: string;\n}\n\ninterface ClaudeCodeEditEntry {\n old_string?: string;\n new_string?: string;\n}\n\nfunction readStdin(): Promise<string> {\n return new Promise((resolve: (value: string) => void) => {\n let data = '';\n process.stdin.setEncoding('utf8');\n process.stdin.on('data', (chunk: string) => { data += chunk; });\n process.stdin.on('end', () => resolve(data));\n process.stdin.on('error', () => resolve(''));\n if (process.stdin.isTTY) resolve('');\n });\n}\n\nfunction safeParse(raw: string): ClaudeCodePayload | null {\n if (!raw || raw.trim() === '') return null;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return JSON.parse(raw) as ClaudeCodePayload;\n } catch (err: unknown) {\n const error = toError(err);\n throw new InformAiError(`Malformed hook input from Claude Code stdin: ${error.message}`, { cause: error });\n }\n}\n\nfunction normalizeToolKind(toolName: string): ToolKind | null {\n if (HANDLED_FILE_TOOLS.has(toolName)) return toolName as ToolKind;\n return null;\n}\n\nfunction normalizeToolInput(toolKind: ToolKind, toolInput: ClaudeCodeToolInput): NormalizedToolInput | null {\n const filePath = toolInput.file_path;\n if (!filePath) return null;\n\n if (toolKind === 'Write') {\n return new NormalizedToolInput(filePath, [\n new NormalizedEdit('', toolInput.content || ''),\n ]);\n }\n if (toolKind === 'Edit') {\n return new NormalizedToolInput(filePath, [\n new NormalizedEdit(toolInput.old_string || '', toolInput.new_string || ''),\n ]);\n }\n if (toolKind === 'MultiEdit') {\n const raw = Array.isArray(toolInput.edits) ? toolInput.edits : [];\n const edits = raw.map((e: ClaudeCodeEditEntry) => new NormalizedEdit(e.old_string || '', e.new_string || ''));\n return new NormalizedToolInput(filePath, edits);\n }\n return null;\n}\n\n// The caller behind this payload. Both fields are sent only inside a subagent, so BOTH absent (or\n// empty) is the coordinator — the one distinction CoordinatorWorktreeGuard turns on.\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction agentIdentityOf(payload: ClaudeCodePayload): AgentIdentity {\n return new AgentIdentity(payload.agent_id ?? '', payload.agent_type ?? '');\n}\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\nfunction handleBash(payload: ClaudeCodePayload, cwd: string, mode: HookMode): void {\n const command = payload.tool_input.command;\n if (!command || command.trim() === '') { emitAllow(); }\n const result = runBash(command, cwd, mode, agentIdentityOf(payload));\n if (!result) { emitAllow(); }\n // Persist the block + WHY. File-tool denies go to hook-rejection.log via logRejection, but a Bash\n // deny had no audit trail — record it in guard-sync-decisions.log so \"blocked and why\" is complete\n // for Bash too. `.webpieces` lives at the repo root, resolved from cwd. Best-effort; never blocks.\n const root = new RepoRootFinder().resolveRepoRoot(cwd);\n logGuardDecision(root, new GuardDecision('bash-guard', 'Bash', command ?? '', branchForLog(root), 'BLOCK', result.report));\n // Bash deny → pass 'Bash' so denyJson adds the ANSI-red systemMessage (the only field a Bash deny\n // shows the human; permissionDecisionReason is invisible on Bash). See claude-code-response.ts.\n emitDeny(result.report, 'Bash', blockingRule(result.report, 'bash-guard'));\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(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(result.report, 'Read', blockingRule(result.report, 'read-guard'));\n}\n\nfunction handleFileTool(payload: ClaudeCodePayload, cwd: string, mode: HookMode): void {\n const toolKind = normalizeToolKind(payload.tool_name);\n if (!toolKind) { emitAllow(); }\n\n const input = normalizeToolInput(toolKind, payload.tool_input);\n if (!input) { emitAllow(); }\n\n // Always allow edits to webpieces.config.json — it's the fix target when the config is broken.\n // This exits 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', toolKind, input.filePath, branchForLog(root), 'ALLOW', '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);\n }\n emitAllow();\n }\n\n const result = run(toolKind, input, cwd, mode);\n if (!result) { emitAllow(); }\n\n logRejection(toolKind, input, result, cwd);\n // File-tool deny → pass the Write/Edit/MultiEdit kind so denyJson omits systemMessage (the reason\n // already renders red natively for these tools). See claude-code-response.ts.\n emitDeny(result.report, toolKind, blockingRule(result.report, 'file-guard'));\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): ShimStaleDecision {\n const allowed = isAllowed(toolName, command, filePath);\n if (allowed === 'pass') return 'pass';\n if (allowed === 'allow') return 'allow-cure';\n return 'deny';\n}\n\n// Committed-shim self-guard, moved here from the rendered shim (2026-07-24). 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// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction enforceCommittedShim(payload: ClaudeCodePayload, 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' || !committedShimStale(shimRoot)) return;\n const decision = shimStaleRecoveryDecision(payload.tool_name, payload.tool_input.command ?? '', payload.tool_input.file_path ?? '');\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 docPath = writeGuardMatrixDoc(new RepoRootFinder().resolveRepoRoot(cwd));\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.\n emitDeny(shimStaleDenyReason(installedShimRulesVersion(), shimRoot ?? '') + guardMatrixPointer(docPath), payload.tool_name, 'committed-shim-stale');\n}\n\n/**\n * Shared entry point for all three Claude Code PreToolUse adapters. `mode` selects which tool kinds\n * to validate; payloads outside the mode's scope pass through (emitAllow). Blocks by emitting a\n * PreToolUse `permissionDecision:\"deny\"` JSON on stdout (exit 0) — see claude-code-response.ts. Fails\n * CLOSED on any unexpected crash (emits a deny) so a broken hook never silently lets an edit through,\n * and the reason now surfaces in the Claude Code UI instead of being hidden on a stderr+exit-2 block.\n */\nexport async function runMain(mode: HookMode): Promise<void> {\n // Captured from the payload as soon as it parses so the fail-closed catch below can tell denyJson\n // which tool it is denying — a crash on a Bash call still gets the visible red systemMessage, a\n // crash on a file tool does not. Empty (before parse / malformed input) → treated as non-Bash.\n let toolName = '';\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const raw = await readStdin();\n const payload = safeParse(raw);\n if (!payload) { emitAllow(); }\n toolName = payload.tool_name;\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(payload.session_id ?? '', payload.agent_id ?? '', mode);\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, cwd, mode);\n\n // Read-only tools (Read): audit-log, warm the main-sync cache, then run the ONE read-scoped\n // guard (read-stale-guard) and allow. Runs BEFORE the general rule engine — no code-style rule\n // ever sees a Read, and the only way this path can deny is a stale `main`.\n // The audit trail still records every file the AI opened (see setup.ts).\n if (READ_ONLY_TOOLS.has(payload.tool_name)) {\n const readPath = payload.tool_input.file_path ?? '';\n if (mode !== 'rules') {\n invocationLog.begin(cwd, payload.tool_name, 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);\n }\n handleRead(readPath, cwd, mode);\n emitAllow();\n }\n\n // Per-invocation guard log (guard-invocations.log): 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 const target = payload.tool_name === 'Bash' ? (payload.tool_input.command ?? '') : (payload.tool_input.file_path ?? '');\n invocationLog.begin(cwd, payload.tool_name, target);\n }\n\n if (payload.tool_name === 'Bash') {\n // No code-style rule is bash-scoped, so the rules hook ignores Bash.\n if (mode === 'rules') { emitAllow(); }\n handleBash(payload, cwd, mode);\n return;\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(payload, cwd, mode);\n } catch (err: unknown) {\n const error = toError(err);\n denyForCrash(error, toolName);\n }\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) both carry an\n * AI-readable message; anything else is an unexpected bug. All three DENY and surface their reason,\n * because a hook that crashed established nothing and must never be read as an allow.\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, toolName: string): never {\n if (error instanceof RuleFailError) {\n emitDeny(error.aiMessage, toolName, 'rule-crash');\n }\n if (error instanceof InformAiError) {\n emitDeny(error.message, toolName, 'bad-config-or-stdin');\n }\n emitDeny(`[ai-hooks] hook crashed unexpectedly — failing closed: ${error.message}`, toolName, 'hook-crash');\n}\n"]}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* L-1 — the layer BELOW L0: guarantee the shell stays somewhere the RELATIVE guard hooks can launch.
|
|
3
|
+
*
|
|
4
|
+
* ─── Why a layer below L0 exists at all ────────────────────────────────────────────────────────────
|
|
5
|
+
* From the Claude Code hooks reference: exit 2 is the blocking channel, exit 0 carries the JSON
|
|
6
|
+
* decision, and ANY OTHER exit is a "non-blocking error. Execution continues; the action proceeds" —
|
|
7
|
+
* including "File missing or not executable: Error logged; tool proceeds."
|
|
8
|
+
*
|
|
9
|
+
* A HOOK THAT FAILS TO LAUNCH IS A SILENT ALLOW. Not a block, not an error the AI sees.
|
|
10
|
+
*
|
|
11
|
+
* Every layer L0-L4 assumes the hook process ran at all. This file is what makes that assumption true.
|
|
12
|
+
*
|
|
13
|
+
* ─── Why the guard hooks become RELATIVE ───────────────────────────────────────────────────────────
|
|
14
|
+
* `.claude/settings.json` registers hooks as `sh "$CLAUDE_PROJECT_DIR/.claude/webpieces/ai-hook.sh"`,
|
|
15
|
+
* and `$CLAUDE_PROJECT_DIR` NEVER moves — proven from four separate worktrees' own logs, every line
|
|
16
|
+
* reading `root=<worktree> projectDir=<primary>`. So every tree is governed by the PRIMARY's shim and
|
|
17
|
+
* the PRIMARY's binary, forever: a worktree can never be judged by the release its own branch pins, and
|
|
18
|
+
* measuring one tree while running another's binary is the non-convergent "two-tree straddle" recorded
|
|
19
|
+
* in shim.ts (an agent gave up after four cures).
|
|
20
|
+
*
|
|
21
|
+
* The fix is to re-root the WHOLE hook, not to measure differently. The hooks reference says "the hook
|
|
22
|
+
* runs in the cwd value from the JSON input", so a RELATIVE command resolves against the tool call's
|
|
23
|
+
* own tree — each tree runs its own shim, its own binary, its own pin. One version, one tree.
|
|
24
|
+
*
|
|
25
|
+
* That is only safe if the relative path is guaranteed to resolve. Hence this file.
|
|
26
|
+
*
|
|
27
|
+
* ─── Why this is a SEPARATE checked-in file from ai-hook.sh ────────────────────────────────────────
|
|
28
|
+
* 1. It is the ONE file that must stay $CLAUDE_PROJECT_DIR-anchored, so it is the one file that cannot
|
|
29
|
+
* be upgraded per-tree. Its surface is therefore kept minimal: a path check. No drift scraper, no
|
|
30
|
+
* allowlist, no config load, no binary — nothing that needs to change often.
|
|
31
|
+
* 2. Its stability profile is the OPPOSITE of ai-hook.sh's. The shim changes most releases; a `cd`
|
|
32
|
+
* validator should converge and stop. Sharing one file forces the stable half to inherit the
|
|
33
|
+
* volatile half's churn — which is today's problem, one level up.
|
|
34
|
+
* 3. A NEW FILE IS INVISIBLE TO OLD RELEASES; A NEW FLAG BREAKS THEM. Measured 2026-08-06: registering
|
|
35
|
+
* `ai-hook.sh --force-root` made the installed shim read `--force-root` as a BIN NAME, fail to find
|
|
36
|
+
* it, and emit fault U — denying `ls` and the very `cd` that would have fixed it:
|
|
37
|
+
* 16:32:20 --force-root Bash tree=primary fault=U DENY-UNDECLARED ls
|
|
38
|
+
* A separate file is simply not registered until a release that ships it, so old releases are safe.
|
|
39
|
+
*
|
|
40
|
+
* ─── The invariant, maintained inductively ─────────────────────────────────────────────────────────
|
|
41
|
+
* A session always starts at a tree root (primary for the coordinator, the worktree for a subagent).
|
|
42
|
+
* The only thing that moves the shell is a `cd`, and (measured 2026-08-02, effective-tree.ts) a `cd`
|
|
43
|
+
* that stays INSIDE the workspace PERSISTS to later calls, while a `cd` that LEAVES it is RESET by the
|
|
44
|
+
* harness before the next call.
|
|
45
|
+
*
|
|
46
|
+
* If every `cd` that would leave a tree root is refused, "the shell is at a tree root" is an
|
|
47
|
+
* INDUCTIVE INVARIANT — so this hook never inspects cwd as a state, only the command.
|
|
48
|
+
*
|
|
49
|
+
* That is also why it is registered for Bash ALONE: no other tool can move the shell.
|
|
50
|
+
*
|
|
51
|
+
* ─── The predicate, in three tests ─────────────────────────────────────────────────────────────────
|
|
52
|
+
* 1. destination holds `.git` → ALLOW. Complete by construction: the primary clone has a .git DIR,
|
|
53
|
+
* every linked worktree (nested or sibling) has a .git FILE, and a nested foreign clone under
|
|
54
|
+
* repositories/** has its own .git DIR. The first two are where the relative hooks launch; the
|
|
55
|
+
* third is a tree we deliberately do not govern.
|
|
56
|
+
* 2. destination is OUTSIDE $CLAUDE_PROJECT_DIR → ALLOW. The harness resets it before the next call,
|
|
57
|
+
* so at most ONE call runs at a path we do not govern — and there is nothing there to guard.
|
|
58
|
+
* 3. otherwise (inside a governed tree, no .git — `tools/`, `dataform/`, `packages/…`) → DENY. This
|
|
59
|
+
* is the only region that is both STICKY and UNGUARDED.
|
|
60
|
+
*
|
|
61
|
+
* It reads NO config. `excludePaths` governs which FILES are enforced, not whether the hook may run,
|
|
62
|
+
* and it cannot be parsed here anyway (this is sh, pre-config, pre-binary). The one measured divergence
|
|
63
|
+
* is `tools/**`: exempt by excludePaths, denied here — correctly, because the real hooks genuinely
|
|
64
|
+
* cannot launch there and we genuinely want them to. Cost: 4 calls in a 2,236-call sample.
|
|
65
|
+
*
|
|
66
|
+
* ─── Nothing to recover from ───────────────────────────────────────────────────────────────────────
|
|
67
|
+
* A denied `cd` NEVER EXECUTES — PreToolUse denies the whole tool call before the shell moves — so the
|
|
68
|
+
* shell is still at a root. There is no bad state and no cure command that needs allowlisting, which is
|
|
69
|
+
* what keeps this hook from ever being able to wedge a session.
|
|
70
|
+
*
|
|
71
|
+
* Measured cost of the deny: 47 of 2,236 real Bash calls (2.10%), or 9.7% of all `cd` commands.
|
|
72
|
+
*/
|
|
73
|
+
export declare const GUARANTEE_ROOT_MARKER = ".claude/webpieces/guarantee-root.sh";
|
|
74
|
+
export declare function guaranteeRootPath(projectRoot: string): string;
|
|
75
|
+
/**
|
|
76
|
+
* The POSIX-sh source. Byte-identical to `templates/guarantee-root.sh`, locked by a unit test, exactly
|
|
77
|
+
* as renderShim()/templates/ai-hook.sh are — so the file a consumer commits and the file this release
|
|
78
|
+
* expects can never silently diverge.
|
|
79
|
+
*/
|
|
80
|
+
export declare function renderGuaranteeRoot(): string;
|
|
81
|
+
/**
|
|
82
|
+
* True when a committed guarantee-root.sh EXISTS but no longer equals renderGuaranteeRoot(). Missing
|
|
83
|
+
* file → false: a repo that has not adopted L-1 yet is not "stale", it is simply still on the two-hook
|
|
84
|
+
* registration, and `wp-install-ai-hooks` is what moves it forward.
|
|
85
|
+
*
|
|
86
|
+
* `root` is the tree whose committed copy this BINARY governs — resolved from the running module's own
|
|
87
|
+
* location by governingShimRoot(), never from cwd and never from $CLAUDE_PROJECT_DIR, for the same
|
|
88
|
+
* reason the shim's own check is anchored that way: it makes the two-tree straddle unconstructible.
|
|
89
|
+
*/
|
|
90
|
+
export declare function committedGuaranteeRootStale(root: string | null): boolean;
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.GUARANTEE_ROOT_MARKER = void 0;
|
|
4
|
+
exports.guaranteeRootPath = guaranteeRootPath;
|
|
5
|
+
exports.renderGuaranteeRoot = renderGuaranteeRoot;
|
|
6
|
+
exports.committedGuaranteeRootStale = committedGuaranteeRootStale;
|
|
7
|
+
const tslib_1 = require("tslib");
|
|
8
|
+
const fs = tslib_1.__importStar(require("fs"));
|
|
9
|
+
const path = tslib_1.__importStar(require("path"));
|
|
10
|
+
const to_error_1 = require("../core/to-error");
|
|
11
|
+
/**
|
|
12
|
+
* L-1 — the layer BELOW L0: guarantee the shell stays somewhere the RELATIVE guard hooks can launch.
|
|
13
|
+
*
|
|
14
|
+
* ─── Why a layer below L0 exists at all ────────────────────────────────────────────────────────────
|
|
15
|
+
* From the Claude Code hooks reference: exit 2 is the blocking channel, exit 0 carries the JSON
|
|
16
|
+
* decision, and ANY OTHER exit is a "non-blocking error. Execution continues; the action proceeds" —
|
|
17
|
+
* including "File missing or not executable: Error logged; tool proceeds."
|
|
18
|
+
*
|
|
19
|
+
* A HOOK THAT FAILS TO LAUNCH IS A SILENT ALLOW. Not a block, not an error the AI sees.
|
|
20
|
+
*
|
|
21
|
+
* Every layer L0-L4 assumes the hook process ran at all. This file is what makes that assumption true.
|
|
22
|
+
*
|
|
23
|
+
* ─── Why the guard hooks become RELATIVE ───────────────────────────────────────────────────────────
|
|
24
|
+
* `.claude/settings.json` registers hooks as `sh "$CLAUDE_PROJECT_DIR/.claude/webpieces/ai-hook.sh"`,
|
|
25
|
+
* and `$CLAUDE_PROJECT_DIR` NEVER moves — proven from four separate worktrees' own logs, every line
|
|
26
|
+
* reading `root=<worktree> projectDir=<primary>`. So every tree is governed by the PRIMARY's shim and
|
|
27
|
+
* the PRIMARY's binary, forever: a worktree can never be judged by the release its own branch pins, and
|
|
28
|
+
* measuring one tree while running another's binary is the non-convergent "two-tree straddle" recorded
|
|
29
|
+
* in shim.ts (an agent gave up after four cures).
|
|
30
|
+
*
|
|
31
|
+
* The fix is to re-root the WHOLE hook, not to measure differently. The hooks reference says "the hook
|
|
32
|
+
* runs in the cwd value from the JSON input", so a RELATIVE command resolves against the tool call's
|
|
33
|
+
* own tree — each tree runs its own shim, its own binary, its own pin. One version, one tree.
|
|
34
|
+
*
|
|
35
|
+
* That is only safe if the relative path is guaranteed to resolve. Hence this file.
|
|
36
|
+
*
|
|
37
|
+
* ─── Why this is a SEPARATE checked-in file from ai-hook.sh ────────────────────────────────────────
|
|
38
|
+
* 1. It is the ONE file that must stay $CLAUDE_PROJECT_DIR-anchored, so it is the one file that cannot
|
|
39
|
+
* be upgraded per-tree. Its surface is therefore kept minimal: a path check. No drift scraper, no
|
|
40
|
+
* allowlist, no config load, no binary — nothing that needs to change often.
|
|
41
|
+
* 2. Its stability profile is the OPPOSITE of ai-hook.sh's. The shim changes most releases; a `cd`
|
|
42
|
+
* validator should converge and stop. Sharing one file forces the stable half to inherit the
|
|
43
|
+
* volatile half's churn — which is today's problem, one level up.
|
|
44
|
+
* 3. A NEW FILE IS INVISIBLE TO OLD RELEASES; A NEW FLAG BREAKS THEM. Measured 2026-08-06: registering
|
|
45
|
+
* `ai-hook.sh --force-root` made the installed shim read `--force-root` as a BIN NAME, fail to find
|
|
46
|
+
* it, and emit fault U — denying `ls` and the very `cd` that would have fixed it:
|
|
47
|
+
* 16:32:20 --force-root Bash tree=primary fault=U DENY-UNDECLARED ls
|
|
48
|
+
* A separate file is simply not registered until a release that ships it, so old releases are safe.
|
|
49
|
+
*
|
|
50
|
+
* ─── The invariant, maintained inductively ─────────────────────────────────────────────────────────
|
|
51
|
+
* A session always starts at a tree root (primary for the coordinator, the worktree for a subagent).
|
|
52
|
+
* The only thing that moves the shell is a `cd`, and (measured 2026-08-02, effective-tree.ts) a `cd`
|
|
53
|
+
* that stays INSIDE the workspace PERSISTS to later calls, while a `cd` that LEAVES it is RESET by the
|
|
54
|
+
* harness before the next call.
|
|
55
|
+
*
|
|
56
|
+
* If every `cd` that would leave a tree root is refused, "the shell is at a tree root" is an
|
|
57
|
+
* INDUCTIVE INVARIANT — so this hook never inspects cwd as a state, only the command.
|
|
58
|
+
*
|
|
59
|
+
* That is also why it is registered for Bash ALONE: no other tool can move the shell.
|
|
60
|
+
*
|
|
61
|
+
* ─── The predicate, in three tests ─────────────────────────────────────────────────────────────────
|
|
62
|
+
* 1. destination holds `.git` → ALLOW. Complete by construction: the primary clone has a .git DIR,
|
|
63
|
+
* every linked worktree (nested or sibling) has a .git FILE, and a nested foreign clone under
|
|
64
|
+
* repositories/** has its own .git DIR. The first two are where the relative hooks launch; the
|
|
65
|
+
* third is a tree we deliberately do not govern.
|
|
66
|
+
* 2. destination is OUTSIDE $CLAUDE_PROJECT_DIR → ALLOW. The harness resets it before the next call,
|
|
67
|
+
* so at most ONE call runs at a path we do not govern — and there is nothing there to guard.
|
|
68
|
+
* 3. otherwise (inside a governed tree, no .git — `tools/`, `dataform/`, `packages/…`) → DENY. This
|
|
69
|
+
* is the only region that is both STICKY and UNGUARDED.
|
|
70
|
+
*
|
|
71
|
+
* It reads NO config. `excludePaths` governs which FILES are enforced, not whether the hook may run,
|
|
72
|
+
* and it cannot be parsed here anyway (this is sh, pre-config, pre-binary). The one measured divergence
|
|
73
|
+
* is `tools/**`: exempt by excludePaths, denied here — correctly, because the real hooks genuinely
|
|
74
|
+
* cannot launch there and we genuinely want them to. Cost: 4 calls in a 2,236-call sample.
|
|
75
|
+
*
|
|
76
|
+
* ─── Nothing to recover from ───────────────────────────────────────────────────────────────────────
|
|
77
|
+
* A denied `cd` NEVER EXECUTES — PreToolUse denies the whole tool call before the shell moves — so the
|
|
78
|
+
* shell is still at a root. There is no bad state and no cure command that needs allowlisting, which is
|
|
79
|
+
* what keeps this hook from ever being able to wedge a session.
|
|
80
|
+
*
|
|
81
|
+
* Measured cost of the deny: 47 of 2,236 real Bash calls (2.10%), or 9.7% of all `cd` commands.
|
|
82
|
+
*/
|
|
83
|
+
exports.GUARANTEE_ROOT_MARKER = '.claude/webpieces/guarantee-root.sh';
|
|
84
|
+
// webpieces-disable no-function-outside-class -- L-1 sibling of shim.ts's shimPath(); this module is deliberately dependency-free module-scope functions so it stays callable from a tree too broken to build a DI container
|
|
85
|
+
function guaranteeRootPath(projectRoot) {
|
|
86
|
+
return path.join(projectRoot, '.claude', 'webpieces', 'guarantee-root.sh');
|
|
87
|
+
}
|
|
88
|
+
// Deny REASON constraint, inherited from the shim: the text is interpolated into a `REASON="…"` shell
|
|
89
|
+
// assignment and then printf'd into a JSON string, so it may contain NO double quotes and NO
|
|
90
|
+
// backslashes. Single quotes only — do not "improve" them.
|
|
91
|
+
const DENY_NOT_LITERAL = 'This cd target is not a literal path, so the guards cannot tell where the shell will end up. '
|
|
92
|
+
+ 'Use a literal absolute path: cd /abs/path && <your command>. '
|
|
93
|
+
+ 'A $VAR, ~, $(...) or backtick is never expanded by the guard.';
|
|
94
|
+
const DENY_NO_TARGET = 'A bare cd (or cd -) moves the shell somewhere the guards cannot predict - a bare cd goes to '
|
|
95
|
+
+ 'your home directory, where the webpieces hooks do not exist and every later tool call would '
|
|
96
|
+
+ 'run UNGUARDED. Name the directory: cd /abs/path && <your command>.';
|
|
97
|
+
// `%s` is the destination, then the project root. Kept to one short paragraph on purpose: L0 already
|
|
98
|
+
// ran a message diet and these denies regress straight back to a wall of text if each one argues.
|
|
99
|
+
const DENY_SUBDIR = 'The webpieces guard hooks are registered RELATIVE (.claude/webpieces/ai-hook.sh) so that each '
|
|
100
|
+
+ 'git tree is governed by its own release. %s has no .claude/webpieces/ai-hook.sh, so a shell '
|
|
101
|
+
+ 'parked there launches NO hooks at all and every later tool call runs UNGUARDED - and a cd that '
|
|
102
|
+
+ 'stays inside the project PERSISTS to your next call. Run it from the tree root instead: '
|
|
103
|
+
+ 'cd %s && <your command>. Tools that take their own directory (git -C, pnpm -C, pnpm --filter, '
|
|
104
|
+
+ 'nx) need no cd at all.';
|
|
105
|
+
/**
|
|
106
|
+
* The cd audit trail. A THIRD parallel writer joins guards+rules on every Bash call, so it gets its
|
|
107
|
+
* own file under the same session/agent/hook key LogStream uses — one writer per directory, so an
|
|
108
|
+
* append can never interleave with another's (macOS PIPE_BUF is 512 bytes and real log lines exceed it).
|
|
109
|
+
*
|
|
110
|
+
* Unlike the shim's RESOLVE_LOG_DIR_SH this needs NO worktree resolution: H1 is $CLAUDE_PROJECT_DIR-
|
|
111
|
+
* anchored by definition, so the primary clone's `.webpieces` is always the right home. That is the one
|
|
112
|
+
* upside of being the hook that cannot follow the tree.
|
|
113
|
+
*
|
|
114
|
+
* Every write is swallowed and nothing ever reaches stdout — stdout is the PreToolUse decision channel
|
|
115
|
+
* and a stray byte there would corrupt allow/deny.
|
|
116
|
+
*/
|
|
117
|
+
const CD_AUDIT_SH = `# --- cd audit (best-effort; never blocks, never touches stdout) --------------------------------
|
|
118
|
+
SID="$(printf '%s' "$PAYLOAD" | sed -n 's/.*"session_id"[[:space:]]*:[[:space:]]*"\\([^"\\\\]*\\)".*/\\1/p')"
|
|
119
|
+
AID="$(printf '%s' "$PAYLOAD" | sed -n 's/.*"agent_id"[[:space:]]*:[[:space:]]*"\\([^"\\\\]*\\)".*/\\1/p')"
|
|
120
|
+
# Untrusted payload values are used as path segments, so anything outside [A-Za-z0-9._-] collapses to _
|
|
121
|
+
# and a leading dot is neutralised — ../../etc can never escape the logs directory.
|
|
122
|
+
clean() { printf '%s' "$1" | tr -c 'A-Za-z0-9._-' '_' \\
|
|
123
|
+
| sed -e 's/\\.\\{2,\\}/_/g' -e 's/^\\.\\{1,\\}/_/' | cut -c1-64; }
|
|
124
|
+
wp_cd_log() { # $1 = verdict, $2 = destination (may be empty)
|
|
125
|
+
{
|
|
126
|
+
[ -n "$CLAUDE_PROJECT_DIR" ] || return 0
|
|
127
|
+
_d="$CLAUDE_PROJECT_DIR/.webpieces/logs"
|
|
128
|
+
mkdir -p "$_d" 2>/dev/null || return 0
|
|
129
|
+
# Flat name, same scheme as LogStream.fileName(): <session>-<agent|coordinator>-guarantee-root-<base>
|
|
130
|
+
# ALWAYS prefixed; a missing session_id renders as 'unknown'. No bare-name branch anywhere.
|
|
131
|
+
_p="$(clean "\${SID:-unknown}")-$(clean "\${AID:-coordinator}")-guarantee-root-"
|
|
132
|
+
_f="$_d/\${_p}cd-audit.log"
|
|
133
|
+
_sz="$(wc -c < "$_f" 2>/dev/null | tr -d ' ')"
|
|
134
|
+
case "$_sz" in ''|*[!0-9]*) _sz=0 ;; esac
|
|
135
|
+
[ "$_sz" -gt 524288 ] && mv -f "$_f" "$_d/\${_p}cd-audit.1.log" 2>/dev/null
|
|
136
|
+
printf '%s\\t%s\\tdest=%s\\tcwd=%s\\t%s\\n' \\
|
|
137
|
+
"$(date '+%Y-%m-%dT%H:%M:%S%z' 2>/dev/null)" "$1" "$2" "$CWD" "$CMD" >> "$_f"
|
|
138
|
+
} 2>/dev/null || true
|
|
139
|
+
}
|
|
140
|
+
`;
|
|
141
|
+
// The deny boundary. Extracted for the same reason CD_AUDIT_SH and HEADER_SH are — to keep the
|
|
142
|
+
// renderer inside the 70-line method budget — and spliced back verbatim. Mirrors the shim's own emit:
|
|
143
|
+
// for Bash, permissionDecisionReason is NOT user-visible, so the red systemMessage carries the text.
|
|
144
|
+
const DENY_EMIT_SH = `wp_cd_log DENY "\${ABS:-$DEST}"
|
|
145
|
+
|
|
146
|
+
BS='\\' # one literal backslash, so the \\u001b escape never sits in this source
|
|
147
|
+
ESC="\${BS}u001b" # the 6 chars: backslash u 0 0 1 b — Claude Code parses \\u001b -> ESC
|
|
148
|
+
printf '{"systemMessage":"%s🛑 %s%s","hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"%s"}}\\n' "\${ESC}[31;1m" "$REASON" "\${ESC}[0m" "$REASON"
|
|
149
|
+
exit 0 # the decision is carried by permissionDecision deny, not the exit code
|
|
150
|
+
`;
|
|
151
|
+
// The file's own banner. Extracted to a module const for the same reason renderShim() extracts
|
|
152
|
+
// VERSION_DRIFT_GUARD_SH — to keep the renderer inside the 80-line method budget — and spliced back
|
|
153
|
+
// in verbatim, byte for byte.
|
|
154
|
+
const HEADER_SH = `#!/bin/sh
|
|
155
|
+
# webpieces L-1 hook — GUARANTEE ROOT. Generated by renderGuaranteeRoot(); do not hand-edit.
|
|
156
|
+
#
|
|
157
|
+
# Registered ABSOLUTE in .claude/settings.json, matcher "Bash":
|
|
158
|
+
# sh "$CLAUDE_PROJECT_DIR/.claude/webpieces/guarantee-root.sh"
|
|
159
|
+
#
|
|
160
|
+
# It exists because the GUARD hooks beside it are registered RELATIVE, so that each git tree is
|
|
161
|
+
# governed by its own @webpieces release. A relative hook that cannot resolve does not block — the
|
|
162
|
+
# harness logs it and lets the tool call proceed UNGUARDED. This file makes that unreachable by
|
|
163
|
+
# refusing any cd that would park the shell where the relative hooks cannot launch.
|
|
164
|
+
#
|
|
165
|
+
# Three tests, no config, no binary, no network:
|
|
166
|
+
# 1. destination holds .git -> ALLOW (tree root, worktree, or foreign clone)
|
|
167
|
+
# 2. destination is outside $CLAUDE_PROJECT_DIR -> ALLOW (the harness resets the cwd next call)
|
|
168
|
+
# 3. otherwise -> DENY (sticky AND unguarded)
|
|
169
|
+
#
|
|
170
|
+
# A denied cd never runs, so the shell never leaves the root and there is nothing to recover from.
|
|
171
|
+
`;
|
|
172
|
+
/**
|
|
173
|
+
* The POSIX-sh source. Byte-identical to `templates/guarantee-root.sh`, locked by a unit test, exactly
|
|
174
|
+
* as renderShim()/templates/ai-hook.sh are — so the file a consumer commits and the file this release
|
|
175
|
+
* expects can never silently diverge.
|
|
176
|
+
*/
|
|
177
|
+
// webpieces-disable no-function-outside-class -- L-1 twin of shim.ts's renderShim(), byte-locked to templates/guarantee-root.sh; module-scope for the same dependency-free reason
|
|
178
|
+
function renderGuaranteeRoot() {
|
|
179
|
+
return `${HEADER_SH}
|
|
180
|
+
PAYLOAD="$(cat)"
|
|
181
|
+
CWD="$(printf '%s' "$PAYLOAD" | sed -n 's/.*"cwd"[[:space:]]*:[[:space:]]*"\\([^"\\\\]*\\)".*/\\1/p')"
|
|
182
|
+
TOOL="$(printf '%s' "$PAYLOAD" | sed -n 's/.*"tool_name"[[:space:]]*:[[:space:]]*"\\([^"\\\\]*\\)".*/\\1/p')"
|
|
183
|
+
|
|
184
|
+
# The command PREFIX, not the whole command — note there is no closing " in this pattern.
|
|
185
|
+
# WHY: a JSON payload escapes an embedded double quote as \\", and \`[^"\\\\]*\` stops dead at that
|
|
186
|
+
# backslash, so the usual "capture between quotes" form yields the EMPTY STRING for any command
|
|
187
|
+
# containing a quote at all (measured: \`cd /a/b && echo "hi"\` -> ''). An empty CMD here would mean
|
|
188
|
+
# "no cd found" -> ALLOW, i.e. this guard would fail OPEN for every quoted command — the exact hazard
|
|
189
|
+
# it exists to close. Capturing only up to the first quote/backslash is enough, because everything
|
|
190
|
+
# L-1 needs (is the FIRST word a cd, and what is its target) lives in the prefix; a quote can only
|
|
191
|
+
# appear later, in the part we do not need.
|
|
192
|
+
CMD="$(printf '%s' "$PAYLOAD" | sed -n 's/.*"command"[[:space:]]*:[[:space:]]*"\\([^"\\\\]*\\).*/\\1/p')"
|
|
193
|
+
|
|
194
|
+
# Only Bash can move the shell. Anything else, and any payload we cannot read, is not ours.
|
|
195
|
+
[ "$TOOL" = "Bash" ] || exit 0
|
|
196
|
+
[ -n "$CMD" ] || exit 0
|
|
197
|
+
|
|
198
|
+
${CD_AUDIT_SH}
|
|
199
|
+
|
|
200
|
+
# Does the command OPEN with cd/pushd? Only a LEADING cd counts — the same rule effective-tree.ts
|
|
201
|
+
# enforces, because a later cd cannot retroactively move a command that has already run.
|
|
202
|
+
FIRST="$(printf '%s' "$CMD" | sed -n 's/^[[:space:]]*\\([^[:space:]]\\{1,\\}\\).*/\\1/p')"
|
|
203
|
+
case "$FIRST" in
|
|
204
|
+
cd|pushd) ;;
|
|
205
|
+
*) exit 0 ;; # no leading cd: nothing to audit, nothing to judge
|
|
206
|
+
esac
|
|
207
|
+
|
|
208
|
+
# The target: a single-quoted path first (that is how a path with spaces is spelled), else a bare word.
|
|
209
|
+
DEST="$(printf '%s' "$CMD" | sed -n "s/^[[:space:]]*[a-z]\\{2,5\\}[[:space:]]\\{1,\\}'\\([^']*\\)'.*/\\1/p")"
|
|
210
|
+
[ -n "$DEST" ] || DEST="$(printf '%s' "$CMD" | sed -n 's/^[[:space:]]*[a-z]\\{2,5\\}[[:space:]]\\{1,\\}\\([^[:space:];&|]\\{1,\\}\\).*/\\1/p')"
|
|
211
|
+
|
|
212
|
+
REASON=""
|
|
213
|
+
if [ -z "$DEST" ] || [ "$DEST" = "-" ]; then
|
|
214
|
+
REASON='${DENY_NO_TARGET}'
|
|
215
|
+
else
|
|
216
|
+
# A target the guard cannot expand is a target it cannot judge. sh has no regex here, so test the
|
|
217
|
+
# four unexpandable shapes directly.
|
|
218
|
+
case "$DEST" in
|
|
219
|
+
*'$'*|*'\`'*|'~'|'~/'*) REASON='${DENY_NOT_LITERAL}' ;;
|
|
220
|
+
esac
|
|
221
|
+
fi
|
|
222
|
+
|
|
223
|
+
if [ -z "$REASON" ]; then
|
|
224
|
+
# Resolve against the shell's real cwd. A destination that does not exist needs no verdict: the cd
|
|
225
|
+
# itself will fail and the shell stays exactly where it is.
|
|
226
|
+
ABS="$(CDPATH= cd -- "\${CWD:-.}" 2>/dev/null && CDPATH= cd -- "$DEST" 2>/dev/null && pwd)"
|
|
227
|
+
if [ -z "$ABS" ]; then wp_cd_log ALLOW-NO-SUCH-DIR "$DEST"; exit 0; fi
|
|
228
|
+
|
|
229
|
+
# TEST 1 — a git tree of any kind. A worktree's .git is a FILE, a clone's is a DIR; -e covers both.
|
|
230
|
+
if [ -e "$ABS/.git" ]; then wp_cd_log ALLOW-GIT-TREE "$ABS"; exit 0; fi
|
|
231
|
+
|
|
232
|
+
# TEST 2 — outside the governed project. The harness resets the cwd before the next call, so at most
|
|
233
|
+
# one command runs there, on paths we do not govern anyway.
|
|
234
|
+
case "$ABS/" in
|
|
235
|
+
"$CLAUDE_PROJECT_DIR"/*) ;;
|
|
236
|
+
*) wp_cd_log ALLOW-OUTSIDE "$ABS"; exit 0 ;;
|
|
237
|
+
esac
|
|
238
|
+
|
|
239
|
+
# TEST 3 — inside a governed tree with no shim beside it: sticky AND unguarded.
|
|
240
|
+
REASON="$(printf '${DENY_SUBDIR}' "$ABS" "$CLAUDE_PROJECT_DIR")"
|
|
241
|
+
fi
|
|
242
|
+
|
|
243
|
+
${DENY_EMIT_SH}`;
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* True when a committed guarantee-root.sh EXISTS but no longer equals renderGuaranteeRoot(). Missing
|
|
247
|
+
* file → false: a repo that has not adopted L-1 yet is not "stale", it is simply still on the two-hook
|
|
248
|
+
* registration, and `wp-install-ai-hooks` is what moves it forward.
|
|
249
|
+
*
|
|
250
|
+
* `root` is the tree whose committed copy this BINARY governs — resolved from the running module's own
|
|
251
|
+
* location by governingShimRoot(), never from cwd and never from $CLAUDE_PROJECT_DIR, for the same
|
|
252
|
+
* reason the shim's own check is anchored that way: it makes the two-tree straddle unconstructible.
|
|
253
|
+
*/
|
|
254
|
+
// webpieces-disable no-function-outside-class -- L-1 twin of shim.ts's committedShimStale(); module-scope for the same dependency-free reason
|
|
255
|
+
function committedGuaranteeRootStale(root) {
|
|
256
|
+
if (root === null)
|
|
257
|
+
return false;
|
|
258
|
+
const file = guaranteeRootPath(root);
|
|
259
|
+
// eslint-disable-next-line @webpieces/no-unmanaged-exceptions
|
|
260
|
+
try {
|
|
261
|
+
if (!fs.existsSync(file))
|
|
262
|
+
return false;
|
|
263
|
+
return fs.readFileSync(file, 'utf8') !== renderGuaranteeRoot();
|
|
264
|
+
}
|
|
265
|
+
catch (err) {
|
|
266
|
+
const error = (0, to_error_1.toError)(err);
|
|
267
|
+
void error; // best-effort: an unreadable tree counts as "not stale" so this never wedges a call
|
|
268
|
+
return false;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
//# sourceMappingURL=guarantee-root.js.map
|