@webpieces/ai-hook-rules 0.4.584 → 0.4.588

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 (40) hide show
  1. package/README.md +27 -8
  2. package/package.json +2 -2
  3. package/src/adapters/hook-core.js +33 -15
  4. package/src/adapters/hook-core.js.map +1 -1
  5. package/src/bin/guarantee-root.d.ts +95 -0
  6. package/src/bin/guarantee-root.js +284 -0
  7. package/src/bin/guarantee-root.js.map +1 -0
  8. package/src/bin/hook-registration.d.ts +134 -0
  9. package/src/bin/hook-registration.js +320 -0
  10. package/src/bin/hook-registration.js.map +1 -0
  11. package/src/bin/l0-allowlist.js +1 -1
  12. package/src/bin/l0-allowlist.js.map +1 -1
  13. package/src/bin/setup.d.ts +1 -15
  14. package/src/bin/setup.js +84 -77
  15. package/src/bin/setup.js.map +1 -1
  16. package/src/bin/shim-audit-log.js +21 -4
  17. package/src/bin/shim-audit-log.js.map +1 -1
  18. package/src/bin/shim.d.ts +1 -1
  19. package/src/bin/shim.js +85 -13
  20. package/src/bin/shim.js.map +1 -1
  21. package/src/bin/upgrade-shim.js +48 -14
  22. package/src/bin/upgrade-shim.js.map +1 -1
  23. package/src/core/decision-log.d.ts +6 -2
  24. package/src/core/decision-log.js +12 -7
  25. package/src/core/decision-log.js.map +1 -1
  26. package/src/core/l0-matrix.js +18 -11
  27. package/src/core/l0-matrix.js.map +1 -1
  28. package/src/core/log-stream.d.ts +72 -0
  29. package/src/core/log-stream.js +104 -0
  30. package/src/core/log-stream.js.map +1 -0
  31. package/src/core/main-sync-log.d.ts +2 -1
  32. package/src/core/main-sync-log.js +9 -5
  33. package/src/core/main-sync-log.js.map +1 -1
  34. package/src/core/main-sync-refresh.d.ts +2 -1
  35. package/src/core/main-sync-refresh.js +2 -1
  36. package/src/core/main-sync-refresh.js.map +1 -1
  37. package/src/core/rejection-log.js +3 -2
  38. package/src/core/rejection-log.js.map +1 -1
  39. package/templates/ai-hook.sh +51 -10
  40. package/templates/guarantee-root.sh +110 -0
@@ -1 +1 @@
1
- {"version":3,"file":"main-sync-refresh.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/core/main-sync-refresh.ts"],"names":[],"mappings":";;AAcA,4EAEC;AAaD,wDAmCC;;AAhED,iDAAsC;AACtC,+CAAyB;AACzB,mDAA6B;AAE7B,0DAAuE;AAEvE,yCAAqC;AACrC,mDAAgF;AAEhF,qGAAqG;AACrG,yEAAyE;AACzE,IAAI,gBAAgB,GAAG,KAAK,CAAC;AAE7B,8GAA8G;AAC9G,SAAgB,gCAAgC;IAC5C,gBAAgB,GAAG,KAAK,CAAC;AAC7B,CAAC;AAED;;;;;;;;;;GAUG;AACH,SAAgB,sBAAsB,CAAC,aAAqB,EAAE,qBAA6B,2CAA4B;IACnH,gGAAgG;IAChG,mGAAmG;IACnG,mGAAmG;IACnG,2FAA2F;IAC3F,wFAAwF;IACxF,IAAI,gBAAgB;QAAE,OAAO;IAC7B,gBAAgB,GAAG,IAAI,CAAC;IAExB,8DAA8D;IAC9D,IAAI,CAAC;QACD,MAAM,SAAS,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,cAAc,CAAC,CAAC;QACvD,2FAA2F;QAC3F,IAAA,4BAAY,EAAC,aAAa,EAAE,IAAI,4BAAY,CAAC,eAAe,EAAE,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,aAAa,SAAS,EAAE,CAAC,CAAC,CAAC;QAE3G,6FAA6F;QAC7F,mFAAmF;QACnF,MAAM,KAAK,GAAG,EAAE,CAAC,QAAQ,CAAC,IAAA,iCAAiB,EAAC,aAAa,CAAC,EAAE,GAAG,CAAC,CAAC;QACjE,MAAM,KAAK,GAAG,IAAA,qBAAK,EAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,SAAS,EAAE,aAAa,EAAE,MAAM,CAAC,kBAAkB,CAAC,CAAC,EAAE;YAC1F,QAAQ,EAAE,IAAI;YACd,KAAK,EAAE,CAAC,QAAQ,EAAE,KAAK,EAAE,KAAK,CAAC;SAClC,CAAC,CAAC;QACH,8FAA8F;QAC9F,wFAAwF;QACxF,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,GAAU,EAAQ,EAAE;YACrC,IAAA,4BAAY,EAAC,aAAa,EAAE,IAAI,4BAAY,CAAC,OAAO,EAAE,KAAK,CAAC,GAAG,IAAI,CAAC,CAAC,EAAE,GAAG,EAAE,iBAAiB,GAAG,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;QACjH,CAAC,CAAC,CAAC;QACH,KAAK,CAAC,KAAK,EAAE,CAAC;QACd,mFAAmF;QACnF,EAAE,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;IACxB,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,KAAK,KAAK,CAAC;QACX,0EAA0E;IAC9E,CAAC;AACL,CAAC","sourcesContent":["import { spawn } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nimport { DEFAULT_HANG_TIMEOUT_MINUTES } from '@webpieces/rules-config';\n\nimport { toError } from './to-error';\nimport { logSyncEvent, SyncLogEvent, syncStderrLogPath } from './main-sync-log';\n\n// Per-process latch for the spawn below. A hook process handles exactly one tool call, so this makes\n// the refresher at-most-once per tool call. Exported reset is test-only.\nlet alreadyTriggered = false;\n\n// webpieces-disable no-function-outside-class -- test-only latch reset, matching this module's function shape\nexport function resetMainSyncRefreshLatchForTest(): void {\n alreadyTriggered = false;\n}\n\n/**\n * Fire-and-forget spawn of the detached refresher (sync-main.js in this same dir — spawned by path,\n * not a bin). The child outlives this hook process (`detached` + `unref`), does the slow\n * merged-PR/fetch/merge-base/overlap work, and writes the cache the feature-branch-guard reads on\n * the NEXT call. This is the first detached spawn in the codebase — every existing hook is synchronous.\n *\n * Observability: we log SPAWN_ATTEMPT here and the child logs START/FINISH/ERROR, all to\n * `.webpieces/logs/guard-async-work.log`. The child's stdout/stderr are redirected to a sibling file (not\n * /dev/null) so a crash before the child's own logging is still captured. If guard-async-work.log shows\n * SPAWN_ATTEMPT but never START, the detached child was killed before it ran.\n */\nexport function triggerMainSyncRefresh(workspaceRoot: string, hangTimeoutMinutes: number = DEFAULT_HANG_TIMEOUT_MINUTES): void {\n // ONE refresher per hook process. Several call sites fire this on a single tool call — the Read\n // fast path in hook-core AND read-stale-guard's own check(), for one — which is why the log showed\n // two SPAWN_ATTEMPTs ~20ms apart from the same pid on every cycle. The loser only ever reached the\n // lock and exited, so the second child was pure waste (and one more `git fetch` racing the\n // agent's). The child's lock still guards against refreshers from OTHER hook processes.\n if (alreadyTriggered) return;\n alreadyTriggered = true;\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const refresher = path.join(__dirname, 'sync-main.js');\n // SPAWN_ATTEMPT first — this also creates .webpieces/logs so the stderr fd below can open.\n logSyncEvent(workspaceRoot, new SyncLogEvent('SPAWN_ATTEMPT', process.pid, '-', `refresher=${refresher}`));\n\n // Redirect the detached child's stdout+stderr to a file (not /dev/null) so an uncaught crash\n // before the child's own logging — e.g. a module-load failure — is still captured.\n const errFd = fs.openSync(syncStderrLogPath(workspaceRoot), 'a');\n const child = spawn(process.execPath, [refresher, workspaceRoot, String(hangTimeoutMinutes)], {\n detached: true,\n stdio: ['ignore', errFd, errFd],\n });\n // spawn errors (e.g. ENOENT) arrive asynchronously; record one if it fires. The hook may exit\n // before this handler runs, but on POSIX a successful exec has already happened by now.\n child.once('error', (err: Error): void => {\n logSyncEvent(workspaceRoot, new SyncLogEvent('ERROR', child.pid ?? -1, '-', `spawn failed: ${err.message}`));\n });\n child.unref();\n // The child has its own dup'd copy of the fd after spawn; close the parent's copy.\n fs.closeSync(errFd);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n // Spawning the background refresh must never block or fail the tool call.\n }\n}\n"]}
1
+ {"version":3,"file":"main-sync-refresh.js","sourceRoot":"","sources":["../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KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,GAAU,EAAQ,EAAE;YACrC,IAAA,4BAAY,EAAC,aAAa,EAAE,IAAI,4BAAY,CAAC,OAAO,EAAE,KAAK,CAAC,GAAG,IAAI,CAAC,CAAC,EAAE,GAAG,EAAE,iBAAiB,GAAG,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;QACjH,CAAC,CAAC,CAAC;QACH,KAAK,CAAC,KAAK,EAAE,CAAC;QACd,mFAAmF;QACnF,EAAE,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;IACxB,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,KAAK,KAAK,CAAC;QACX,0EAA0E;IAC9E,CAAC;AACL,CAAC","sourcesContent":["import { spawn } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nimport { DEFAULT_HANG_TIMEOUT_MINUTES } from '@webpieces/rules-config';\n\nimport { toError } from './to-error';\nimport { logSyncEvent, SyncLogEvent, syncStderrLogPath } from './main-sync-log';\n\n// Per-process latch for the spawn below. A hook process handles exactly one tool call, so this makes\n// the refresher at-most-once per tool call. Exported reset is test-only.\nlet alreadyTriggered = false;\n\n// webpieces-disable no-function-outside-class -- test-only latch reset, matching this module's function shape\nexport function resetMainSyncRefreshLatchForTest(): void {\n alreadyTriggered = false;\n}\n\n/**\n * Fire-and-forget spawn of the detached refresher (sync-main.js in this same dir — spawned by path,\n * not a bin). The child outlives this hook process (`detached` + `unref`), does the slow\n * merged-PR/fetch/merge-base/overlap work, and writes the cache the feature-branch-guard reads on\n * the NEXT call. This is the first detached spawn in the codebase — every existing hook is synchronous.\n *\n * Observability: we log SPAWN_ATTEMPT here and the child logs START/FINISH/ERROR, all to\n * `.webpieces/logs/<stream>guard-async-work.log` (LogStream prefixes every name). The child's\n * stdout/stderr are redirected to a sibling file (not\n * /dev/null) so a crash before the child's own logging is still captured. If guard-async-work.log shows\n * SPAWN_ATTEMPT but never START, the detached child was killed before it ran.\n */\nexport function triggerMainSyncRefresh(workspaceRoot: string, hangTimeoutMinutes: number = DEFAULT_HANG_TIMEOUT_MINUTES): void {\n // ONE refresher per hook process. Several call sites fire this on a single tool call — the Read\n // fast path in hook-core AND read-stale-guard's own check(), for one — which is why the log showed\n // two SPAWN_ATTEMPTs ~20ms apart from the same pid on every cycle. The loser only ever reached the\n // lock and exited, so the second child was pure waste (and one more `git fetch` racing the\n // agent's). The child's lock still guards against refreshers from OTHER hook processes.\n if (alreadyTriggered) return;\n alreadyTriggered = true;\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const refresher = path.join(__dirname, 'sync-main.js');\n // SPAWN_ATTEMPT first — this also creates .webpieces/logs so the stderr fd below can open.\n logSyncEvent(workspaceRoot, new SyncLogEvent('SPAWN_ATTEMPT', process.pid, '-', `refresher=${refresher}`));\n\n // Redirect the detached child's stdout+stderr to a file (not /dev/null) so an uncaught crash\n // before the child's own logging — e.g. a module-load failure — is still captured.\n const errFd = fs.openSync(syncStderrLogPath(workspaceRoot), 'a');\n const child = spawn(process.execPath, [refresher, workspaceRoot, String(hangTimeoutMinutes)], {\n detached: true,\n stdio: ['ignore', errFd, errFd],\n });\n // spawn errors (e.g. ENOENT) arrive asynchronously; record one if it fires. The hook may exit\n // before this handler runs, but on POSIX a successful exec has already happened by now.\n child.once('error', (err: Error): void => {\n logSyncEvent(workspaceRoot, new SyncLogEvent('ERROR', child.pid ?? -1, '-', `spawn failed: ${err.message}`));\n });\n child.unref();\n // The child has its own dup'd copy of the fd after spawn; close the parent's copy.\n fs.closeSync(errFd);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n // Spawning the background refresh must never block or fail the tool call.\n }\n}\n"]}
@@ -6,6 +6,7 @@ const tslib_1 = require("tslib");
6
6
  const fs = tslib_1.__importStar(require("fs"));
7
7
  const path = tslib_1.__importStar(require("path"));
8
8
  const rules_config_1 = require("@webpieces/rules-config");
9
+ const log_stream_1 = require("./log-stream");
9
10
  // The rejection log SPLITS across the two state dirs on purpose: the `.log` index goes to `logs/`
10
11
  // with every other webpieces log, while the dated `hooks/<YYYY-MM-DD>/writeInfo-*.md` DETAIL files
11
12
  // are not logs and stay in `hooks/` (see LOGS_STATE_DIR).
@@ -40,8 +41,8 @@ function logRejection(toolKind, input, result, cwd) {
40
41
  const detailRelPath = `${rules_config_1.HOOKS_STATE_DIR}/${dateStr}/${detailFileName}`;
41
42
  const detail = buildDetailContent(timestamp, toolKind, relativePath, ruleNames, result.report, input);
42
43
  fs.writeFileSync(path.join(dayDir, detailFileName), detail);
43
- const logPath = path.join(logsDir, LOG_FILE);
44
- rotateLogFile(logPath, path.join(logsDir, LOG_FILE_PREV));
44
+ const logPath = path.join(logsDir, log_stream_1.logStream.fileName(LOG_FILE));
45
+ rotateLogFile(logPath, path.join(logsDir, log_stream_1.logStream.fileName(LOG_FILE_PREV)));
45
46
  const logLine = `[${timestamp}]\t${toolKind}\t${relativePath}\t[${ruleNames.join(',')}]\t${detailRelPath}\n`;
46
47
  fs.appendFileSync(logPath, logLine);
47
48
  rotateOldDays(hooksDir, MAX_AGE_DAYS);
@@ -1 +1 @@
1
- {"version":3,"file":"rejection-log.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/core/rejection-log.ts"],"names":[],"mappings":";;AAiBA,oCA8CC;AAkBD,4CASC;;AA1FD,+CAAyB;AACzB,mDAA6B;AAE7B,0DAAwF;AAIxF,kGAAkG;AAClG,mGAAmG;AACnG,0DAA0D;AAC1D,MAAM,QAAQ,GAAG,oBAAoB,CAAC;AACtC,MAAM,aAAa,GAAG,sBAAsB,CAAC;AAC7C,MAAM,aAAa,GAAG,GAAG,GAAG,IAAI,CAAC,CAAC,gCAAgC;AAClE,MAAM,YAAY,GAAG,CAAC,CAAC;AAEvB,MAAM,YAAY,GAAG,oBAAoB,CAAC;AAE1C,SAAgB,YAAY,CACxB,QAAkB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IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;YAAE,SAAS;QACvC,IAAI,OAAO,CAAC,OAAO,EAAE,GAAG,MAAM,EAAE,CAAC;YAC7B,8DAA8D;YAC9D,IAAI,CAAC;gBACD,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,KAAK,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;YAC5E,CAAC;YAAC,OAAO,GAAY,EAAE,CAAC;gBACpB,6BAA6B;gBAC7B,KAAK,GAAG,CAAC;YACb,CAAC;QACL,CAAC;IACL,CAAC;AACL,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\n\nimport { dotWebpieces, RepoRootFinder, HOOKS_STATE_DIR } from '@webpieces/rules-config';\n\nimport type { ToolKind, NormalizedToolInput, BlockedResult } from './types';\n\n// The rejection log SPLITS across the two state dirs on purpose: the `.log` index goes to `logs/`\n// with every other webpieces log, while the dated `hooks/<YYYY-MM-DD>/writeInfo-*.md` DETAIL files\n// are not logs and stay in `hooks/` (see LOGS_STATE_DIR).\nconst LOG_FILE = 'hook-rejection.log';\nconst LOG_FILE_PREV = 'hook-rejection.1.log';\nconst MAX_LOG_BYTES = 512 * 1024; // 512 KB — rotate when exceeded\nconst MAX_AGE_DAYS = 7;\n\nconst RULE_NAME_RE = /^\\[([^\\]]+)\\] \\(/gm;\n\nexport function logRejection(\n toolKind: ToolKind,\n input: NormalizedToolInput,\n result: BlockedResult,\n cwd: string,\n): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // `.webpieces/` lives at the repo root, NOT the AI's cwd — resolve it so a hook fired while\n // the AI is in a subdirectory never scatters a stray `<subdir>/.webpieces` tree.\n const root = new RepoRootFinder().resolveRepoRoot(cwd);\n const now = new Date();\n const timestamp = now.toISOString();\n const epochMs = String(now.getTime());\n const dateStr = timestamp.slice(0, 10);\n\n // LOCAL scope — a rejection is this worktree's event, and a per-worktree log has exactly one\n // writer, so its appends and its daily detail files cannot collide with another agent's.\n const hooksDir = dotWebpieces.localFile(root, HOOKS_STATE_DIR);\n const logsDir = dotWebpieces.logs(root);\n const dayDir = path.join(hooksDir, dateStr);\n fs.mkdirSync(dayDir, { recursive: true });\n fs.mkdirSync(logsDir, { recursive: true });\n\n const relativePath = computeRelativePath(input.filePath, root);\n const ruleNames = extractRuleNames(result.report);\n const detailFileName = `writeInfo-${epochMs}.md`;\n // Relative to the STATE DIR, not to the log file's own directory: the index now lives in\n // `logs/` while the detail lives in `hooks/<date>/`, so a bare `<date>/<file>` would no\n // longer resolve from where the reader found the line.\n const detailRelPath = `${HOOKS_STATE_DIR}/${dateStr}/${detailFileName}`;\n\n const detail = buildDetailContent(timestamp, toolKind, relativePath, ruleNames, result.report, input);\n fs.writeFileSync(path.join(dayDir, detailFileName), detail);\n\n const logPath = path.join(logsDir, LOG_FILE);\n rotateLogFile(logPath, path.join(logsDir, LOG_FILE_PREV));\n\n const logLine = `[${timestamp}]\\t${toolKind}\\t${relativePath}\\t[${ruleNames.join(',')}]\\t${detailRelPath}\\n`;\n fs.appendFileSync(logPath, logLine);\n\n rotateOldDays(hooksDir, MAX_AGE_DAYS);\n } catch (err: unknown) {\n //const error = toError(err);\n void err;\n }\n}\n\nfunction computeRelativePath(filePath: string, cwd: string): string {\n if (filePath.startsWith(cwd)) {\n const rel = filePath.slice(cwd.length);\n if (rel.startsWith('/')) return rel.slice(1);\n return rel;\n }\n return filePath;\n}\n\n/**\n * The rule names a block report cites — every `[<rule-name>] (` header it opens with. Exported because\n * two audit streams need the same answer from the same regex: this file's rejection index, and the\n * `rule=` field guard-invocations.log now carries (see InvocationLog.finish). Two scrapers would be\n * two answers to one question.\n */\n// webpieces-disable no-function-outside-class -- pure regex scraper beside this module's other module-scope helpers; exported so the invocation log and the rejection index scrape rule names with the SAME code.\nexport function extractRuleNames(report: string): string[] {\n const names: string[] = [];\n let match = RULE_NAME_RE.exec(report);\n while (match !== null) {\n names.push(match[1]);\n match = RULE_NAME_RE.exec(report);\n }\n RULE_NAME_RE.lastIndex = 0;\n return names;\n}\n\nfunction buildDetailContent(\n timestamp: string,\n toolKind: ToolKind,\n relativePath: string,\n ruleNames: string[],\n report: string,\n input: NormalizedToolInput,\n): string {\n const lines: string[] = [];\n lines.push('# Hook Rejection Detail');\n lines.push('');\n lines.push(`- **Timestamp:** ${timestamp}`);\n lines.push(`- **Tool:** ${toolKind}`);\n lines.push(`- **File:** ${relativePath}`);\n lines.push(`- **Rules violated:** ${ruleNames.join(', ')}`);\n lines.push('');\n lines.push('## Report');\n lines.push('');\n lines.push('```');\n lines.push(report.trimEnd());\n lines.push('```');\n lines.push('');\n lines.push('## Content Being Written');\n lines.push('');\n\n if (toolKind === 'Write') {\n const content = input.edits.length > 0 ? input.edits[0].newString : '';\n lines.push('```typescript');\n lines.push(content.trimEnd());\n lines.push('```');\n } else {\n for (let i = 0; i < input.edits.length; i += 1) {\n const edit = input.edits[i];\n lines.push(`### Edit ${String(i + 1)} of ${String(input.edits.length)}`);\n lines.push('');\n lines.push('**old_string:**');\n lines.push('```typescript');\n lines.push(edit.oldString.trimEnd());\n lines.push('```');\n lines.push('');\n lines.push('**new_string:**');\n lines.push('```typescript');\n lines.push(edit.newString.trimEnd());\n lines.push('```');\n lines.push('');\n }\n }\n\n return lines.join('\\n') + '\\n';\n}\n\nfunction rotateLogFile(logPath: string, prevPath: string): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const stat = fs.statSync(logPath);\n if (stat.size > MAX_LOG_BYTES) {\n if (fs.existsSync(prevPath)) fs.unlinkSync(prevPath);\n fs.renameSync(logPath, prevPath);\n }\n } catch (err: unknown) {\n //const error = toError(err);\n void err;\n }\n}\n\nfunction rotateOldDays(hooksDir: string, maxAgeDays: number): void {\n const cutoff = Date.now() - maxAgeDays * 24 * 60 * 60 * 1000;\n let entries: string[];\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n entries = fs.readdirSync(hooksDir);\n } catch (err: unknown) {\n //const error = toError(err);\n void err;\n return;\n }\n\n for (const entry of entries) {\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(entry)) continue;\n const dirDate = new Date(entry + 'T00:00:00Z');\n if (isNaN(dirDate.getTime())) continue;\n if (dirDate.getTime() < cutoff) {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.rmSync(path.join(hooksDir, entry), { recursive: true, force: true });\n } catch (err: unknown) {\n //const error = toError(err);\n void err;\n }\n }\n }\n}\n"]}
1
+ {"version":3,"file":"rejection-log.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/core/rejection-log.ts"],"names":[],"mappings":";;AAkBA,oCA8CC;AAkBD,4CASC;;AA3FD,+CAAyB;AACzB,mDAA6B;AAE7B,0DAAwF;AAGxF,6CAAyC;AAEzC,kGAAkG;AAClG,mGAAmG;AACnG,0DAA0D;AAC1D,MAAM,QAAQ,GAAG,oBAAoB,CAAC;AACtC,MAAM,aAAa,GAAG,sBAAsB,CAAC;AAC7C,MAAM,aAAa,GAAG,GAAG,GAAG,IAAI,CAAC,CAAC,gCAAgC;AAClE,MAAM,YAAY,GAAG,CAAC,CAAC;AAEvB,MAAM,YAAY,GAAG,oBAAoB,CAAC;AAE1C,SAAgB,YAAY,CACxB,QAAkB,EAClB,KAA0B,EAC1B,MAAqB,EACrB,GAAW;IAEX,8DAA8D;IAC9D,IAAI,CAAC;QACD,4FAA4F;QAC5F,iFAAiF;QACjF,MAAM,IAAI,GAAG,IAAI,6BAAc,EAAE,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC;QACvD,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC;QACvB,MAAM,SAAS,GAAG,GAAG,CAAC,WAAW,EAAE,CAAC;QACpC,MAAM,OAAO,GAAG,MAAM,CAAC,GAAG,CAAC,OAAO,EAAE,CAAC,CAAC;QACtC,MAAM,O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YAC5E,CAAC;YAAC,OAAO,GAAY,EAAE,CAAC;gBACpB,6BAA6B;gBAC7B,KAAK,GAAG,CAAC;YACb,CAAC;QACL,CAAC;IACL,CAAC;AACL,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\n\nimport { dotWebpieces, RepoRootFinder, HOOKS_STATE_DIR } from '@webpieces/rules-config';\n\nimport type { ToolKind, NormalizedToolInput, BlockedResult } from './types';\nimport { logStream } from './log-stream';\n\n// The rejection log SPLITS across the two state dirs on purpose: the `.log` index goes to `logs/`\n// with every other webpieces log, while the dated `hooks/<YYYY-MM-DD>/writeInfo-*.md` DETAIL files\n// are not logs and stay in `hooks/` (see LOGS_STATE_DIR).\nconst LOG_FILE = 'hook-rejection.log';\nconst LOG_FILE_PREV = 'hook-rejection.1.log';\nconst MAX_LOG_BYTES = 512 * 1024; // 512 KB — rotate when exceeded\nconst MAX_AGE_DAYS = 7;\n\nconst RULE_NAME_RE = /^\\[([^\\]]+)\\] \\(/gm;\n\nexport function logRejection(\n toolKind: ToolKind,\n input: NormalizedToolInput,\n result: BlockedResult,\n cwd: string,\n): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // `.webpieces/` lives at the repo root, NOT the AI's cwd — resolve it so a hook fired while\n // the AI is in a subdirectory never scatters a stray `<subdir>/.webpieces` tree.\n const root = new RepoRootFinder().resolveRepoRoot(cwd);\n const now = new Date();\n const timestamp = now.toISOString();\n const epochMs = String(now.getTime());\n const dateStr = timestamp.slice(0, 10);\n\n // LOCAL scope — a rejection is this worktree's event, and a per-worktree log has exactly one\n // writer, so its appends and its daily detail files cannot collide with another agent's.\n const hooksDir = dotWebpieces.localFile(root, HOOKS_STATE_DIR);\n const logsDir = dotWebpieces.logs(root);\n const dayDir = path.join(hooksDir, dateStr);\n fs.mkdirSync(dayDir, { recursive: true });\n fs.mkdirSync(logsDir, { recursive: true });\n\n const relativePath = computeRelativePath(input.filePath, root);\n const ruleNames = extractRuleNames(result.report);\n const detailFileName = `writeInfo-${epochMs}.md`;\n // Relative to the STATE DIR, not to the log file's own directory: the index now lives in\n // `logs/` while the detail lives in `hooks/<date>/`, so a bare `<date>/<file>` would no\n // longer resolve from where the reader found the line.\n const detailRelPath = `${HOOKS_STATE_DIR}/${dateStr}/${detailFileName}`;\n\n const detail = buildDetailContent(timestamp, toolKind, relativePath, ruleNames, result.report, input);\n fs.writeFileSync(path.join(dayDir, detailFileName), detail);\n\n const logPath = path.join(logsDir, logStream.fileName(LOG_FILE));\n rotateLogFile(logPath, path.join(logsDir, logStream.fileName(LOG_FILE_PREV)));\n\n const logLine = `[${timestamp}]\\t${toolKind}\\t${relativePath}\\t[${ruleNames.join(',')}]\\t${detailRelPath}\\n`;\n fs.appendFileSync(logPath, logLine);\n\n rotateOldDays(hooksDir, MAX_AGE_DAYS);\n } catch (err: unknown) {\n //const error = toError(err);\n void err;\n }\n}\n\nfunction computeRelativePath(filePath: string, cwd: string): string {\n if (filePath.startsWith(cwd)) {\n const rel = filePath.slice(cwd.length);\n if (rel.startsWith('/')) return rel.slice(1);\n return rel;\n }\n return filePath;\n}\n\n/**\n * The rule names a block report cites — every `[<rule-name>] (` header it opens with. Exported because\n * two audit streams need the same answer from the same regex: this file's rejection index, and the\n * `rule=` field guard-invocations.log now carries (see InvocationLog.finish). Two scrapers would be\n * two answers to one question.\n */\n// webpieces-disable no-function-outside-class -- pure regex scraper beside this module's other module-scope helpers; exported so the invocation log and the rejection index scrape rule names with the SAME code.\nexport function extractRuleNames(report: string): string[] {\n const names: string[] = [];\n let match = RULE_NAME_RE.exec(report);\n while (match !== null) {\n names.push(match[1]);\n match = RULE_NAME_RE.exec(report);\n }\n RULE_NAME_RE.lastIndex = 0;\n return names;\n}\n\nfunction buildDetailContent(\n timestamp: string,\n toolKind: ToolKind,\n relativePath: string,\n ruleNames: string[],\n report: string,\n input: NormalizedToolInput,\n): string {\n const lines: string[] = [];\n lines.push('# Hook Rejection Detail');\n lines.push('');\n lines.push(`- **Timestamp:** ${timestamp}`);\n lines.push(`- **Tool:** ${toolKind}`);\n lines.push(`- **File:** ${relativePath}`);\n lines.push(`- **Rules violated:** ${ruleNames.join(', ')}`);\n lines.push('');\n lines.push('## Report');\n lines.push('');\n lines.push('```');\n lines.push(report.trimEnd());\n lines.push('```');\n lines.push('');\n lines.push('## Content Being Written');\n lines.push('');\n\n if (toolKind === 'Write') {\n const content = input.edits.length > 0 ? input.edits[0].newString : '';\n lines.push('```typescript');\n lines.push(content.trimEnd());\n lines.push('```');\n } else {\n for (let i = 0; i < input.edits.length; i += 1) {\n const edit = input.edits[i];\n lines.push(`### Edit ${String(i + 1)} of ${String(input.edits.length)}`);\n lines.push('');\n lines.push('**old_string:**');\n lines.push('```typescript');\n lines.push(edit.oldString.trimEnd());\n lines.push('```');\n lines.push('');\n lines.push('**new_string:**');\n lines.push('```typescript');\n lines.push(edit.newString.trimEnd());\n lines.push('```');\n lines.push('');\n }\n }\n\n return lines.join('\\n') + '\\n';\n}\n\nfunction rotateLogFile(logPath: string, prevPath: string): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const stat = fs.statSync(logPath);\n if (stat.size > MAX_LOG_BYTES) {\n if (fs.existsSync(prevPath)) fs.unlinkSync(prevPath);\n fs.renameSync(logPath, prevPath);\n }\n } catch (err: unknown) {\n //const error = toError(err);\n void err;\n }\n}\n\nfunction rotateOldDays(hooksDir: string, maxAgeDays: number): void {\n const cutoff = Date.now() - maxAgeDays * 24 * 60 * 60 * 1000;\n let entries: string[];\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n entries = fs.readdirSync(hooksDir);\n } catch (err: unknown) {\n //const error = toError(err);\n void err;\n return;\n }\n\n for (const entry of entries) {\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(entry)) continue;\n const dirDate = new Date(entry + 'T00:00:00Z');\n if (isNaN(dirDate.getTime())) continue;\n if (dirDate.getTime() < cutoff) {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.rmSync(path.join(hooksDir, entry), { recursive: true, force: true });\n } catch (err: unknown) {\n //const error = toError(err);\n void err;\n }\n }\n }\n}\n"]}
@@ -7,13 +7,27 @@
7
7
  # the hook has a stable entry point even when node_modules is absent. Safe to delete along with the
8
8
  # matching .claude/settings.json entries if you remove @webpieces/ai-hook-rules.
9
9
  #
10
- # Usage (wired into .claude/settings.json): sh "$CLAUDE_PROJECT_DIR/.claude/webpieces/ai-hook.sh" <bin-name>
10
+ # Usage (wired into .claude/settings.json, RELATIVE so each git tree runs its own copy):
11
+ # sh ".claude/webpieces/ai-hook.sh" <bin-name>
11
12
  BIN_NAME="$1"
12
13
  shift
13
- # Resolve the bin relative to THIS script (…/<root>/.claude/webpieces/ai-hook.sh → <root>), not the
14
+ # Resolve the tree relative to THIS script (…/<root>/.claude/webpieces/ai-hook.sh → <root>), not the
14
15
  # caller's cwd — the hook can be invoked from any directory (a subdir, or a nested clone).
15
16
  ROOT="$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd)"
17
+ # The BIN is resolved by walking UP from ROOT (as Node does), and BIN_ROOT records which tree supplied
18
+ # it — the version-drift guard below compares THIS tree's pin against THAT tree's installed version.
19
+ BIN_ROOT="$ROOT"
16
20
  BIN="$ROOT/node_modules/.bin/$BIN_NAME"
21
+ WP_WALK="$ROOT"
22
+ while [ ! -x "$WP_WALK/node_modules/.bin/$BIN_NAME" ]; do
23
+ WP_UP="$(dirname -- "$WP_WALK")"
24
+ [ "$WP_UP" != "$WP_WALK" ] || break
25
+ WP_WALK="$WP_UP"
26
+ done
27
+ if [ -x "$WP_WALK/node_modules/.bin/$BIN_NAME" ]; then
28
+ BIN_ROOT="$WP_WALK"
29
+ BIN="$WP_WALK/node_modules/.bin/$BIN_NAME"
30
+ fi
17
31
  # --- webpieces version-drift guard (pure sh — runs even when the installed guard bin is stale) -----
18
32
  # The committed shim is version-agnostic, so it keeps working right after a git pull, BEFORE the
19
33
  # matching pnpm install. That is exactly when node_modules can be STALE: an OLDER @webpieces than
@@ -77,7 +91,7 @@ if [ -f "$ROOT/package.json" ]; then
77
91
  esac
78
92
  # The release the rest of this repo is on — what fault U's cure should pin to.
79
93
  [ -n "$WP_PIN" ] || WP_PIN="$WP_DECL"
80
- WP_MANIFEST="$ROOT/node_modules/@webpieces/$WP_NAME/package.json"
94
+ WP_MANIFEST="$BIN_ROOT/node_modules/@webpieces/$WP_NAME/package.json"
81
95
  [ -f "$WP_MANIFEST" ] || continue
82
96
  WP_INST="$(sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$WP_MANIFEST" | head -n1)"
83
97
  [ -n "$WP_INST" ] || continue
@@ -91,16 +105,31 @@ if [ -f "$ROOT/package.json" ]; then
91
105
  $(sed -n 's/.*"@webpieces\/\([A-Za-z0-9._-]*\)"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1 \2/p' "$ROOT/package.json")
92
106
  WPEOF
93
107
  fi
108
+ # THE CURE FOR A BORROWED node_modules RUNS IN THIS TREE, NOT WHEREVER THE BIN CAME FROM. A bare
109
+ # 'pnpm install' typed while the shell sits in the primary clone installs into the primary, changes
110
+ # nothing in the worktree being judged, and re-fires the identical fault — the four-cure straddle
111
+ # recorded above committedShimStale(). When the bin was inherited, prescribe the cd and say why.
112
+ WP_INSTALL_CMD="pnpm install"
113
+ WP_BORROW_NOTE=""
114
+ if [ "$BIN_ROOT" != "$ROOT" ]; then
115
+ WP_INSTALL_CMD="cd $ROOT && pnpm install"
116
+ WP_BORROW_NOTE=" NOTE: this tree ($ROOT) has NO node_modules of its own, so the guard binary was inherited from $BIN_ROOT by walking up - which is only correct while the two agree on the version. Run the install HERE, in this tree, so it gets its own node_modules at its own pin."
117
+ fi
94
118
  # Read the tool payload ONCE, up front. The shim no longer exec's the bin (see RUN_BIN_SH), so it must
95
119
  # forward stdin to the bin itself — and it needs the payload again on the fail-closed path below.
96
120
  PAYLOAD="$(cat)"
97
121
  CMD="$(printf '%s' "$PAYLOAD" | sed -n 's/.*"command"[[:space:]]*:[[:space:]]*"\([^"\\]*\)".*/\1/p')"
122
+ CMD_LOG="$(printf '%s' "$PAYLOAD" | sed -n 's/.*"command"[[:space:]]*:[[:space:]]*"\([^"\\]*\).*/\1/p')"
123
+ [ -n "$CMD_LOG" ] || CMD_LOG="$CMD"
98
124
  TOOL="$(printf '%s' "$PAYLOAD" | sed -n 's/.*"tool_name"[[:space:]]*:[[:space:]]*"\([^"\\]*\)".*/\1/p')"
125
+ WP_SID="$(printf '%s' "$PAYLOAD" | sed -n 's/.*"session_id"[[:space:]]*:[[:space:]]*"\([^"\\]*\)".*/\1/p')"
126
+ WP_AID="$(printf '%s' "$PAYLOAD" | sed -n 's/.*"agent_id"[[:space:]]*:[[:space:]]*"\([^"\\]*\)".*/\1/p')"
99
127
  FILE="$(printf '%s' "$PAYLOAD" | sed -n 's/.*"file_path"[[:space:]]*:[[:space:]]*"\([^"\\]*\)".*/\1/p')"
100
128
  WP_CWD="$(printf '%s' "$PAYLOAD" | sed -n 's/.*"cwd"[[:space:]]*:[[:space:]]*"\([^"\\]*\)".*/\1/p')"
101
129
  [ -n "$WP_CWD" ] || WP_CWD="$ROOT" # no cwd in the payload (older client, or a hand-run) → the shim's own tree
102
130
  # Best-effort AUDIT TRAIL of what L0 did with this call — every call, not just the broken ones. One
103
- # tab-separated line per invocation into this TREE's own logs/ai-hook-shim.log (gitignored), so the
131
+ # tab-separated line per invocation into this TREE's own
132
+ # logs/<session>-<agent|coordinator>-<binName>-ai-hook-shim.log (gitignored), so the
104
133
  # observed behaviour can be diffed against the matrix in guards/L0-tooling.md. NEVER breaks or blocks the
105
134
  # hook: every write is swallowed, and nothing ever goes to stdout (stdout is the PreToolUse decision
106
135
  # channel — a stray byte there would corrupt allow/deny).
@@ -133,17 +162,29 @@ wp_resolve_log_dir() {
133
162
  WP_LOG_DIR="$_wp_primary/.webpieces/worktrees/$WP_TREE/logs"
134
163
  fi
135
164
  }
165
+ wp_clean() { # one path segment from an UNTRUSTED payload id — twin of LogStream's segment()
166
+ printf '%s' "$1" | tr -c 'A-Za-z0-9._-' '_' | sed -e 's/\.\{2,\}/_/g' -e 's/^\.\{1,\}/_/' | cut -c1-64
167
+ }
136
168
  wp_log() { # $1 = L0 fault code (D|X|K|-), $2 = verdict label
137
169
  {
138
170
  [ -n "$WP_LOG_DIR" ] || wp_resolve_log_dir
139
171
  mkdir -p "$WP_LOG_DIR" 2>/dev/null || return 0
140
- _wp_f="$WP_LOG_DIR/ai-hook-shim.log"
172
+ # Same flat scheme as LogStream.fileName(): <session>-<agent|coordinator>-<hook>-<base>. $BIN_NAME
173
+ # IS the hook discriminator here (wp-ai-guards-hook vs wp-ai-rules-hook), and Claude Code runs those
174
+ # two IN PARALLEL on every file edit — without this prefix they append to ONE file and tear above
175
+ # PIPE_BUF. An empty session id renders 'unknown' — this has no bare-name branch, matching
176
+ # LogStream.fileName(), which has none either.
177
+ # ALWAYS prefixed - a missing session_id renders as 'unknown', never as the shared bare name.
178
+ # Gating this on a non-empty id would drop both parallel hooks back onto one file, which is the
179
+ # torn-append case this exists to remove. Twin of LogStream.fileName(), which has no bare branch.
180
+ _wp_pfx="$(wp_clean "${WP_SID:-unknown}")-$(wp_clean "${WP_AID:-coordinator}")-$BIN_NAME-"
181
+ _wp_f="$WP_LOG_DIR/${_wp_pfx}ai-hook-shim.log"
141
182
  # Rotate at the SAME 512 KB into the SAME .1.log sibling as every JS-side webpieces log. This runs
142
183
  # on every tool call, so it is one wc and no more; a size we cannot read counts as 0 (no rotation).
143
184
  _wp_sz="$(wc -c < "$_wp_f" 2>/dev/null | tr -d ' ')"
144
185
  case "$_wp_sz" in ''|*[!0-9]*) _wp_sz=0 ;; esac
145
- [ "$_wp_sz" -gt 524288 ] && mv -f "$_wp_f" "$WP_LOG_DIR/ai-hook-shim.1.log" 2>/dev/null
146
- printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$(date '+%Y-%m-%dT%H:%M:%S%z' 2>/dev/null)" "$BIN_NAME" "$TOOL" "tree=$WP_TREE" "fault=$1" "$2" "$CMD" >> "$_wp_f"
186
+ [ "$_wp_sz" -gt 524288 ] && mv -f "$_wp_f" "$WP_LOG_DIR/${_wp_pfx}ai-hook-shim.1.log" 2>/dev/null
187
+ printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$(date '+%Y-%m-%dT%H:%M:%S%z' 2>/dev/null)" "$BIN_NAME" "$TOOL" "tree=$WP_TREE" "fault=$1" "$2" "$CMD_LOG" >> "$_wp_f"
147
188
  } 2>/dev/null || true
148
189
  }
149
190
  BROKEN_BIN=""
@@ -212,7 +253,7 @@ if [ -n "$BROKEN_BIN" ]; then
212
253
  # Report (do NOT auto-clean) the orphaned pnpm staging dirs — a package pnpm was mid-way through
213
254
  # writing is left behind as <name>_<pid>_<hash>. Their presence is the fingerprint of an install that
214
255
  # was killed, which is what corrupts node_modules in the first place. Best-effort; never fatal.
215
- STAGING_N="$(ls "$ROOT/node_modules" 2>/dev/null | grep -Ec '_[0-9a-f]+_[0-9a-f]+$' || true)"
256
+ STAGING_N="$(ls "$BIN_ROOT/node_modules" 2>/dev/null | grep -Ec '_[0-9a-f]+_[0-9a-f]+$' || true)"
216
257
  STAGING_NOTE=""
217
258
  if [ "${STAGING_N:-0}" -gt 0 ] 2>/dev/null; then
218
259
  STAGING_NOTE=" Also found $STAGING_N orphaned pnpm staging dirs (name_pid_hash) under node_modules - the fingerprint of an install that was killed mid-write." # only when N > 0
@@ -252,13 +293,13 @@ elif [ -n "$DRIFT_PKG" ]; then
252
293
  if (ip == "" && dp != "") print "newer"
253
294
  }' 2>/dev/null)"
254
295
  if [ "$DRIFT_DIR" = older ]; then
255
- REASON="❌ webpieces version drift: package.json pins $DRIFT_PKG@$DRIFT_DECLARED but node_modules has $DRIFT_INSTALLED - node_modules is OLDER, so the pin is what you want. Every other call is blocked until they agree. Run EXACTLY: 'pnpm install'. Run it EXACTLY as written - the allowlist matches the whole command, so appending anything (even && git status) makes it a different command and it is rejected; that is not the guard blocking its own cure. Only these may be added: a leading cd <dir> && (single-quote a path containing spaces), a trailing 2>&1, and | tail -N."
296
+ REASON="❌ webpieces version drift: package.json pins $DRIFT_PKG@$DRIFT_DECLARED but node_modules has $DRIFT_INSTALLED - node_modules is OLDER, so the pin is what you want. Every other call is blocked until they agree. Run EXACTLY: '$WP_INSTALL_CMD'.${WP_BORROW_NOTE} Run it EXACTLY as written - the allowlist matches the whole command, so appending anything (even && git status) makes it a different command and it is rejected; that is not the guard blocking its own cure. Only these may be added: a leading cd <dir> && (single-quote a path containing spaces), a trailing 2>&1, and | tail -N."
256
297
  else
257
298
  # NEWER, or undecidable — the same three choices apply either way, so the only thing the ambiguous
258
299
  # case changes is the claim about which side is stale.
259
300
  DRIFT_NOTE="node_modules is NEWER, so the PIN is the stale side and a bare 'pnpm install' DOWNGRADES you to $DRIFT_DECLARED"
260
301
  [ "$DRIFT_DIR" = newer ] || DRIFT_NOTE="these two versions could not be ordered automatically - compare them yourself: if node_modules is the NEWER side then the PIN is the stale side and a bare 'pnpm install' DOWNGRADES you to $DRIFT_DECLARED"
261
- REASON="❌ webpieces version drift: package.json pins $DRIFT_PKG@$DRIFT_DECLARED but node_modules has $DRIFT_INSTALLED - $DRIFT_NOTE. That may be exactly what you want. Every other call is blocked until they agree. Pick one: - move forward to what origin pins: run 'git pull origin main', then 'pnpm install'. - stay on this code deliberately: run 'pnpm install' (the downgrade is the point). - on a feature branch: run 'pnpm install' (aligns to YOUR branch pin - usually right). Run it EXACTLY as written - the allowlist matches the whole command, so appending anything (even && git status) makes it a different command and it is rejected; that is not the guard blocking its own cure. Only these may be added: a leading cd <dir> && (single-quote a path containing spaces), a trailing 2>&1, and | tail -N."
302
+ REASON="❌ webpieces version drift: package.json pins $DRIFT_PKG@$DRIFT_DECLARED but node_modules has $DRIFT_INSTALLED - $DRIFT_NOTE. That may be exactly what you want. Every other call is blocked until they agree. Pick one: - move forward to what origin pins: run 'git pull origin main', then 'pnpm install'. - stay on this code deliberately: run 'pnpm install' (the downgrade is the point). - on a feature branch: run 'pnpm install' (aligns to YOUR branch pin - usually right).${WP_BORROW_NOTE} Run it EXACTLY as written - the allowlist matches the whole command, so appending anything (even && git status) makes it a different command and it is rejected; that is not the guard blocking its own cure. Only these may be added: a leading cd <dir> && (single-quote a path containing spaces), a trailing 2>&1, and | tail -N."
262
303
  fi
263
304
  else
264
305
  # A LINKED WORKTREE is the overwhelmingly common way to land here with a perfectly healthy repo:
@@ -0,0 +1,110 @@
1
+ #!/bin/sh
2
+ # webpieces L-1 hook — GUARANTEE ROOT. Generated by renderGuaranteeRoot(); do not hand-edit.
3
+ #
4
+ # Registered ABSOLUTE in .claude/settings.json, matcher "Bash":
5
+ # sh "$CLAUDE_PROJECT_DIR/.claude/webpieces/guarantee-root.sh"
6
+ #
7
+ # It exists because the GUARD hooks beside it are registered RELATIVE, so that each git tree is
8
+ # governed by its own @webpieces release. A relative hook that cannot resolve does not block — the
9
+ # harness logs it and lets the tool call proceed UNGUARDED. This file makes that unreachable by
10
+ # refusing any cd that would park the shell where the relative hooks cannot launch.
11
+ #
12
+ # Three tests, no config, no binary, no network:
13
+ # 1. destination holds .git -> ALLOW (tree root, worktree, or foreign clone)
14
+ # 2. destination is outside $CLAUDE_PROJECT_DIR -> ALLOW (the harness resets the cwd next call)
15
+ # 3. otherwise -> DENY (sticky AND unguarded)
16
+ #
17
+ # A denied cd never runs, so the shell never leaves the root and there is nothing to recover from.
18
+
19
+ PAYLOAD="$(cat)"
20
+ CWD="$(printf '%s' "$PAYLOAD" | sed -n 's/.*"cwd"[[:space:]]*:[[:space:]]*"\([^"\\]*\)".*/\1/p')"
21
+ TOOL="$(printf '%s' "$PAYLOAD" | sed -n 's/.*"tool_name"[[:space:]]*:[[:space:]]*"\([^"\\]*\)".*/\1/p')"
22
+
23
+ # The command PREFIX, not the whole command — note there is no closing " in this pattern.
24
+ # WHY: a JSON payload escapes an embedded double quote as \", and `[^"\\]*` stops dead at that
25
+ # backslash, so the usual "capture between quotes" form yields the EMPTY STRING for any command
26
+ # containing a quote at all (measured: `cd /a/b && echo "hi"` -> ''). An empty CMD here would mean
27
+ # "no cd found" -> ALLOW, i.e. this guard would fail OPEN for every quoted command — the exact hazard
28
+ # it exists to close. Capturing only up to the first quote/backslash is enough, because everything
29
+ # L-1 needs (is the FIRST word a cd, and what is its target) lives in the prefix; a quote can only
30
+ # appear later, in the part we do not need.
31
+ CMD="$(printf '%s' "$PAYLOAD" | sed -n 's/.*"command"[[:space:]]*:[[:space:]]*"\([^"\\]*\).*/\1/p')"
32
+
33
+ # Only Bash can move the shell. Anything else, and any payload we cannot read, is not ours.
34
+ [ "$TOOL" = "Bash" ] || exit 0
35
+ [ -n "$CMD" ] || exit 0
36
+
37
+ # --- cd audit (best-effort; never blocks, never touches stdout) --------------------------------
38
+ SID="$(printf '%s' "$PAYLOAD" | sed -n 's/.*"session_id"[[:space:]]*:[[:space:]]*"\([^"\\]*\)".*/\1/p')"
39
+ AID="$(printf '%s' "$PAYLOAD" | sed -n 's/.*"agent_id"[[:space:]]*:[[:space:]]*"\([^"\\]*\)".*/\1/p')"
40
+ # Untrusted payload values are used as path segments, so anything outside [A-Za-z0-9._-] collapses to _
41
+ # and a leading dot is neutralised — ../../etc can never escape the logs directory.
42
+ clean() { printf '%s' "$1" | tr -c 'A-Za-z0-9._-' '_' \
43
+ | sed -e 's/\.\{2,\}/_/g' -e 's/^\.\{1,\}/_/' | cut -c1-64; }
44
+ wp_cd_log() { # $1 = verdict, $2 = destination (may be empty)
45
+ {
46
+ [ -n "$CLAUDE_PROJECT_DIR" ] || return 0
47
+ _d="$CLAUDE_PROJECT_DIR/.webpieces/logs"
48
+ mkdir -p "$_d" 2>/dev/null || return 0
49
+ # Flat name, same scheme as LogStream.fileName(): <session>-<agent|coordinator>-guarantee-root-<base>
50
+ # ALWAYS prefixed; a missing session_id renders as 'unknown'. No bare-name branch anywhere.
51
+ _p="$(clean "${SID:-unknown}")-$(clean "${AID:-coordinator}")-guarantee-root-"
52
+ _f="$_d/${_p}cd-audit.log"
53
+ _sz="$(wc -c < "$_f" 2>/dev/null | tr -d ' ')"
54
+ case "$_sz" in ''|*[!0-9]*) _sz=0 ;; esac
55
+ [ "$_sz" -gt 524288 ] && mv -f "$_f" "$_d/${_p}cd-audit.1.log" 2>/dev/null
56
+ printf '%s\t%s\tdest=%s\tcwd=%s\t%s\n' \
57
+ "$(date '+%Y-%m-%dT%H:%M:%S%z' 2>/dev/null)" "$1" "$2" "$CWD" "$CMD" >> "$_f"
58
+ } 2>/dev/null || true
59
+ }
60
+
61
+
62
+ # Does the command OPEN with cd/pushd? Only a LEADING cd counts — the same rule effective-tree.ts
63
+ # enforces, because a later cd cannot retroactively move a command that has already run.
64
+ FIRST="$(printf '%s' "$CMD" | sed -n 's/^[[:space:]]*\([^[:space:]]\{1,\}\).*/\1/p')"
65
+ case "$FIRST" in
66
+ cd|pushd) ;;
67
+ *) exit 0 ;; # no leading cd: nothing to audit, nothing to judge
68
+ esac
69
+
70
+ # The target: a single-quoted path first (that is how a path with spaces is spelled), else a bare word.
71
+ DEST="$(printf '%s' "$CMD" | sed -n "s/^[[:space:]]*[a-z]\{2,5\}[[:space:]]\{1,\}'\([^']*\)'.*/\1/p")"
72
+ [ -n "$DEST" ] || DEST="$(printf '%s' "$CMD" | sed -n 's/^[[:space:]]*[a-z]\{2,5\}[[:space:]]\{1,\}\([^[:space:];&|]\{1,\}\).*/\1/p')"
73
+
74
+ REASON=""
75
+ if [ -z "$DEST" ] || [ "$DEST" = "-" ]; then
76
+ REASON='A bare cd (or cd -) moves the shell somewhere the guards cannot predict - a bare cd goes to your home directory, where the webpieces hooks do not exist and every later tool call would run UNGUARDED. Name the directory: cd /abs/path && <your command>.'
77
+ else
78
+ # A target the guard cannot expand is a target it cannot judge. sh has no regex here, so test the
79
+ # four unexpandable shapes directly.
80
+ case "$DEST" in
81
+ *'$'*|*'`'*|'~'|'~/'*) REASON='This cd target is not a literal path, so the guards cannot tell where the shell will end up. Use a literal absolute path: cd /abs/path && <your command>. A $VAR, ~, $(...) or backtick is never expanded by the guard.' ;;
82
+ esac
83
+ fi
84
+
85
+ if [ -z "$REASON" ]; then
86
+ # Resolve against the shell's real cwd. A destination that does not exist needs no verdict: the cd
87
+ # itself will fail and the shell stays exactly where it is.
88
+ ABS="$(CDPATH= cd -- "${CWD:-.}" 2>/dev/null && CDPATH= cd -- "$DEST" 2>/dev/null && pwd)"
89
+ if [ -z "$ABS" ]; then wp_cd_log ALLOW-NO-SUCH-DIR "$DEST"; exit 0; fi
90
+
91
+ # TEST 1 — a git tree of any kind. A worktree's .git is a FILE, a clone's is a DIR; -e covers both.
92
+ if [ -e "$ABS/.git" ]; then wp_cd_log ALLOW-GIT-TREE "$ABS"; exit 0; fi
93
+
94
+ # TEST 2 — outside the governed project. The harness resets the cwd before the next call, so at most
95
+ # one command runs there, on paths we do not govern anyway.
96
+ case "$ABS/" in
97
+ "$CLAUDE_PROJECT_DIR"/*) ;;
98
+ *) wp_cd_log ALLOW-OUTSIDE "$ABS"; exit 0 ;;
99
+ esac
100
+
101
+ # TEST 3 — inside a governed tree with no shim beside it: sticky AND unguarded.
102
+ REASON="$(printf 'The webpieces guard hooks are registered RELATIVE (.claude/webpieces/ai-hook.sh) so that each git tree is governed by its own release. %s has no .claude/webpieces/ai-hook.sh, so a shell parked there launches NO hooks at all and every later tool call runs UNGUARDED - and a cd that stays inside the project PERSISTS to your next call. Run it from the tree root instead: cd %s && <your command>. Tools that take their own directory (git -C, pnpm -C, pnpm --filter, nx) need no cd at all.' "$ABS" "$CLAUDE_PROJECT_DIR")"
103
+ fi
104
+
105
+ wp_cd_log DENY "${ABS:-$DEST}"
106
+
107
+ BS='\' # one literal backslash, so the \u001b escape never sits in this source
108
+ ESC="${BS}u001b" # the 6 chars: backslash u 0 0 1 b — Claude Code parses \u001b -> ESC
109
+ printf '{"systemMessage":"%s🛑 %s%s","hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"%s"}}\n' "${ESC}[31;1m" "$REASON" "${ESC}[0m" "$REASON"
110
+ exit 0 # the decision is carried by permissionDecision deny, not the exit code