@webpieces/agent-workflow-rules 0.4.909 → 0.4.911

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 (69) hide show
  1. package/package.json +7 -7
  2. package/src/adapters/codex-subagent-guard.d.ts +2 -2
  3. package/src/adapters/codex-subagent-guard.js +2 -2
  4. package/src/adapters/codex-subagent-guard.js.map +1 -1
  5. package/src/adapters/hook-app-fixtures.d.ts +1 -1
  6. package/src/adapters/hook-app-fixtures.js +1 -1
  7. package/src/adapters/hook-app-fixtures.js.map +1 -1
  8. package/src/adapters/hook-core.js +3 -3
  9. package/src/adapters/hook-core.js.map +1 -1
  10. package/src/bin/dev-hook-install.js +1 -1
  11. package/src/bin/dev-hook-install.js.map +1 -1
  12. package/src/bin/dev-hook-uninstall.js +1 -1
  13. package/src/bin/dev-hook-uninstall.js.map +1 -1
  14. package/src/bin/l0-allowlist.js +4 -2
  15. package/src/bin/l0-allowlist.js.map +1 -1
  16. package/src/bin/setup.js +3 -3
  17. package/src/bin/setup.js.map +1 -1
  18. package/src/bin/shim-audit-log.d.ts +2 -2
  19. package/src/bin/shim-audit-log.js +3 -3
  20. package/src/bin/shim-audit-log.js.map +1 -1
  21. package/src/bin/shim.js +1 -1
  22. package/src/bin/shim.js.map +1 -1
  23. package/src/bin/upgrade-shim.js +3 -1
  24. package/src/bin/upgrade-shim.js.map +1 -1
  25. package/src/configs/main-sync-guard-configs.d.ts +1 -1
  26. package/src/configs/main-sync-guard-configs.js +1 -1
  27. package/src/configs/main-sync-guard-configs.js.map +1 -1
  28. package/src/core/decision-log.d.ts +6 -6
  29. package/src/core/decision-log.js +7 -7
  30. package/src/core/decision-log.js.map +1 -1
  31. package/src/core/excluded-path-escape.d.ts +4 -4
  32. package/src/core/excluded-path-escape.js +5 -5
  33. package/src/core/excluded-path-escape.js.map +1 -1
  34. package/src/core/l0-matrix.d.ts +1 -1
  35. package/src/core/l0-matrix.js +1 -1
  36. package/src/core/l0-matrix.js.map +1 -1
  37. package/src/core/l1-doc.js +7 -7
  38. package/src/core/l1-doc.js.map +1 -1
  39. package/src/core/l1-matrix-doc.js +1 -1
  40. package/src/core/l1-matrix-doc.js.map +1 -1
  41. package/src/core/l1-rows.js +2 -2
  42. package/src/core/l1-rows.js.map +1 -1
  43. package/src/core/l2-doc.js +2 -2
  44. package/src/core/l2-doc.js.map +1 -1
  45. package/src/core/l2-matrix-doc.js +1 -1
  46. package/src/core/l2-matrix-doc.js.map +1 -1
  47. package/src/core/l2-rows.js +1 -1
  48. package/src/core/l2-rows.js.map +1 -1
  49. package/src/core/main-sync-log.d.ts +2 -2
  50. package/src/core/main-sync-log.js +3 -3
  51. package/src/core/main-sync-log.js.map +1 -1
  52. package/src/core/main-sync-refresh.d.ts +1 -1
  53. package/src/core/main-sync-refresh.js +2 -2
  54. package/src/core/main-sync-refresh.js.map +1 -1
  55. package/src/core/main-sync-timeout.js +1 -1
  56. package/src/core/main-sync-timeout.js.map +1 -1
  57. package/src/core/rejection-log.js +2 -2
  58. package/src/core/rejection-log.js.map +1 -1
  59. package/src/core/rules/content-read-scan.js +2 -2
  60. package/src/core/rules/content-read-scan.js.map +1 -1
  61. package/src/core/rules/feature-branch-guard.d.ts +1 -1
  62. package/src/core/rules/feature-branch-guard.js +1 -1
  63. package/src/core/rules/feature-branch-guard.js.map +1 -1
  64. package/src/core/runner.js +1 -1
  65. package/src/core/runner.js.map +1 -1
  66. package/src/core/sync-main.d.ts +2 -2
  67. package/src/core/sync-main.js +2 -2
  68. package/src/core/sync-main.js.map +1 -1
  69. package/templates/ai-hook.sh +7 -7
@@ -1 +1 @@
1
- {"version":3,"file":"upgrade-shim.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/bin/upgrade-shim.ts"],"names":[],"mappings":";;;AAyEA,wCAqCC;AAqKD,oBAEC;;AApRD,+CAAyB;AACzB,mDAA6B;AAE7B,iCAA4D;AAC5D,qDAA6E;AAC7E,2DAA8H;AA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AAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;IAC1B,IAAI,EAAE,CAAC;AACX,CAAC","sourcesContent":["#!/usr/bin/env node\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nimport { renderShim, shimPath, findShimRoot } from './shim';\nimport { REVIEWER_AGENT_MARKER, writeReviewerAgent } from './reviewer-agent';\nimport { repairRegistrationAt, managedSurfaceDrift, SettingsRepair, LEGACY_GUARANTEE_ROOT_MARKER } from './hook-registration';\nimport { BASH_CWD_ENV_KEY, BASH_CWD_ENV_VALUE } from './managed-env';\nimport { toError } from '@webpieces/tooling-common/to-error';\n\n// ---------------------------------------------------------------------------\n// The `wp-upgrade-shim` entry point — the CURE for the managed-hook-surface self-guard (L0 fault S).\n//\n// WHAT IT REPAIRS, and why all of them (2026-08-07, extended). This used to write EXACTLY ONE FILE,\n// ai-hook.sh, and touch nothing else. That was correct while the installed surface WAS one file. It is\n// now five (the name `wp-upgrade-shim` is older than the job and is NOT renamed — a rename with no\n// functional change is a cost with no payer; the prose is what gets corrected):\n//\n// 1. .claude/webpieces/ai-hook.sh the ONE guard shim, shared by every harness and registered\n// ABSOLUTE, so the MAIN tree governs every tree\n// 2. the .claude/settings.json registration itself\n// 3. the .codex/hooks.json registration — the SAME two hooks under Codex's own matchers and its own\n// $PWD anchor. Repaired only where it already EXISTS: arming a harness is the installer's decision,\n// this is the cure for one that has drifted\n// 3b. the NEIGHBOUR hook commands in both of those files — the entries a CONSUMER repo registers\n// beside webpieces' own. A repo-RELATIVE entry path (`node \".claude/hooks/guard-deploy.mjs\"`)\n// resolves against the hook process's cwd, so it dies the moment that cwd is not the repo root,\n// and per the hooks reference that non-zero exit is a NON-BLOCKING error — a SILENT UNGUARDED\n// ALLOW. Measured in a consumer repo (issue #852) silently disarming three security guards while\n// printing nothing but a `node:internal/modules/cjs/loader` fragment with no rule name. They are\n// anchored to the harness's own prefix, the same reversal webpieces made for its own hook. See\n// neighbour-hooks.ts\n// 4. the .claude/settings.json `env` entry CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR=1, which pins the\n// Bash cwd to the project root — and, because settings `env` is inherited, pins it identically for\n// every subagent, so a verdict never depends on where an earlier `cd` left the shell. Claude-only:\n// Codex has no settings `env`, and its cwd is measured not to drift\n// 5. .claude/agents/webpieces-reviewer.md — the generic PR-gate reviewer agent (issue #938), a committed,\n// generated file with the same contract as the shim; see reviewer-agent.ts\n//\n// WHAT IT DELIBERATELY DOES *NOT* DO: sweep this tree's dangling `node_modules/.bin/wp-*` symlinks. That\n// is the same class of defect as the retired-file removal below — an entry pointing at a missing file is\n// worse than absence, because `ls node_modules/.bin` advertises a capability that only fails on execution\n// — and it WOULD read naturally here. It is not here because the one implementation of that sweep lives in\n// `@webpieces/rules-config` (`stale-bin-sweep.ts`), which this module may not import: the barrel pulls in\n// inversify and the config loader, and a subpath import resolves against the INSTALLED rules-config, which\n// is a release behind this source (see .claude/rules/published-vs-local-source.md) — so a spawned\n// `wp-upgrade-shim` would die on module resolution, in the one command an L0-blocked session has left. A\n// second copy of the sweep here would be a second spelling of it, which is worse again.\n//\n// It does not need to be here. The sweep rides the `wp-*` startup pass that regenerates\n// `.webpieces/instruct-ai/*`, so ANY `wp-*` command heals the tree — including the `pnpm install` +\n// `pnpm exec wp-upgrade-shim` sequence this bin's own advice ends with.\n//\n// It also DELETES the retired `.claude/webpieces/guarantee-root.sh` and any settings entry still naming\n// it. That file was the L-1 hook, which existed only to guarantee the once-RELATIVE shim path resolved;\n// an absolute path resolves from any cwd, so it has no job left. Removing the file without removing the\n// entry (or vice versa) is the worst possible half-state — a registered hook pointing at a missing file\n// exits 127, which per the hooks reference is a NON-BLOCKING error, i.e. a SILENT UNGUARDED ALLOW — so\n// both happen here, file first.\n//\n// A cure that fixes some of them is worse than no cure, because it reports success. This bin is the\n// sanctioned cure named in fault S's message and is on the L0 allowlist, so it must repair everything.\n//\n// Deliberately imports only ./shim and ./hook-registration (fs + path) + toError,\n// exactly like install-entry: the whole job is to rewrite webpieces-managed files, which never needed\n// the rule engine, and it must stay runnable on a tree too broken to load it.\n// ---------------------------------------------------------------------------\nconst RED = '[31;1m';\nconst RESET = '[0m';\n\n// Returns the process exit code (0 = ok). Kept as a function (not top-level code) so it is unit-testable\n// without spawning node.\n// webpieces-disable no-function-outside-class -- bin entry point: this module MUST load with only fs+path (see header), mirroring install-entry.ts. A DI-managed class would pull the container in and reintroduce the require-time crash this dependency-free path exists to survive.\nexport function runUpgradeShim(cwd: string): number {\n const root = findShimRoot(cwd);\n if (root === null) {\n console.error(`${RED}🛑 @webpieces: no committed .claude/webpieces/ai-hook.sh found to regenerate.${RESET}`);\n console.error(' Run this from a repo that installs @webpieces/agent-workflow-rules, or run the installer (pnpm wp-install-ai-hooks).');\n return 1;\n }\n const target = shimPath(root);\n // webpieces-disable no-unmanaged-exceptions -- bin entry chokepoint: turn an fs error into an actionable line + non-zero exit rather than a raw node trace; there is no caller above a bin to handle it.\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n fs.writeFileSync(target, renderShim(), { mode: 0o755 });\n // writeFileSync's mode only applies on create; force it on overwrite too (matches writeShim).\n fs.chmodSync(target, 0o755);\n // ORDER MATTERS, and it is registration-FIRST. The reverse leaves a window in which a settings\n // entry still names a file that is gone — exit 127, which the hooks reference defines as a\n // NON-BLOCKING error, i.e. a SILENT UNGUARDED ALLOW. This way round the transient state is an\n // ORPHANED FILE that nothing references, which is inert. (An earlier draft of this function\n // argued file-first was safer; it is not. repairRegistration() also early-returns when the file\n // registers no guard bins, and the retired H1 command contains neither bin name, so a\n // guarantee-root-ONLY settings file would have lost the file and kept the entry.)\n const repairs = repairRegistrationAt(root);\n const removedLegacy = removeRetiredGuaranteeRoot(root);\n // The generic PR-gate reviewer agent — a managed file like the shim, so the one cure rewrites it too.\n if (writeReviewerAgent(root)) {\n console.log(`✅ @webpieces: wrote the generic PR-gate reviewer agent ${REVIEWER_AGENT_MARKER} (generated — commit it, do not edit it).`);\n }\n reportRepairs(target, removedLegacy, repairs);\n // ADVISORY ONLY, and deliberately after the ✅ lines: it never touches the exit code (see\n // reportTreeDivergence).\n reportTreeDivergence(root);\n return verifyRepaired(root);\n } catch (err: unknown) {\n const error = toError(err);\n console.error(`${RED}🛑 @webpieces: could not write under ${root}: ${error.message}${RESET}`);\n return 1;\n }\n}\n\n/**\n * Say what was actually done, per managed thing. The old single line (\"regenerated the managed shim\")\n * would now be a lie by omission on the three most important repairs — and an agent reading a cure's\n * output is how it decides whether the cure worked.\n *\n * Each settings file reports the repairs IT needed, from the flags recorded before the rewrite. Printing\n * \"rewrote the hook registration\" for a file whose hooks were already current and whose `env` entry was\n * the only thing missing would be the same class of dishonesty one level down.\n */\n// webpieces-disable no-function-outside-class -- sibling of runUpgradeShim in this deliberately dependency-free bin module\n/**\n * Delete the RETIRED L-1 hook file, returning whether there was one. Removal-only, one way, no writer.\n *\n * This runs AFTER repairRegistrationAt(), which strips the stale H1 ENTRY from settings.json. Removing\n * the entry first means the file is merely orphaned in between — inert, because nothing references it.\n * File-first would instead leave a registered hook pointing at a missing file, and per the hooks\n * reference a non-2 non-zero exit is a NON-BLOCKING error: every `cd` would go unjudged.\n */\n// webpieces-disable no-function-outside-class -- module-scope like every other helper in this bin, which must load on a tree too broken to build a DI container\nfunction removeRetiredGuaranteeRoot(root: string): boolean {\n // The path comes from LEGACY_GUARANTEE_ROOT_MARKER, never re-spelled here: a second literal is a\n // second spelling, and when the expiry in hook-registration.ts fires the documented removal would\n // miss this copy and the dead name would survive in a file nobody thought to grep.\n const legacy = path.join(root, LEGACY_GUARANTEE_ROOT_MARKER);\n if (!fs.existsSync(legacy)) return false;\n fs.rmSync(legacy, { force: true });\n return true;\n}\n\n// webpieces-disable no-function-outside-class -- module-scope like every other helper in this bin, which must load on a tree too broken to build a DI container\nfunction reportRepairs(shimFile: string, removedLegacy: boolean, repairs: readonly SettingsRepair[]): void {\n console.log(`✅ @webpieces: regenerated the managed shim at ${shimFile} — tool calls are re-armed.`);\n if (removedLegacy) {\n console.log('✅ @webpieces: deleted the RETIRED L-1 hook .claude/webpieces/guarantee-root.sh.');\n console.log(' The guard hooks are ABSOLUTE now, so the launch guarantee it provided is structural.');\n }\n if (repairs.length === 0) {\n console.log(' .claude/settings.json (hook registration + managed env) already matches this release — no change.');\n }\n for (const repair of repairs) {\n if (repair.registration) {\n console.log(`✅ @webpieces: rewrote the hook registration in ${repair.settingsPath} to the two-hook form`);\n console.log(' (both guard hooks ABSOLUTE via $CLAUDE_PROJECT_DIR, so the MAIN tree governs every tree;');\n console.log(' any retired guarantee-root.sh entry was removed).');\n }\n for (const command of repair.anchoredNeighbours) {\n console.log(`✅ @webpieces: anchored a RELATIVE hook command in ${repair.settingsPath} so it resolves from any cwd`);\n console.log(` now: ${command}`);\n console.log(' (a relative entry path resolves against the hook process cwd; off the repo root it fails to load, and');\n console.log(' per the hooks reference that non-zero exit is NON-BLOCKING — the guard silently stops guarding.)');\n }\n if (repair.env) {\n console.log(`✅ @webpieces: set env.${BASH_CWD_ENV_KEY}=${BASH_CWD_ENV_VALUE} in ${repair.settingsPath}`);\n console.log(' (pins the Bash cwd to the project root, so the guard hooks resolve identically for every subagent — for');\n console.log(' this session and, because settings env is inherited, for every subagent it spawns).');\n }\n }\n console.log(' These files are generated + committed by webpieces; do not revert or hand-edit them.');\n}\n\n/**\n * WAS THE REPAIRED TREE THE TREE THE HOOKS LAUNCH FROM — the second way this cure can report success\n * while changing nothing the session is actually governed by.\n *\n * H1 is registered ABSOLUTE, `sh \"$CLAUDE_PROJECT_DIR/…\"`, and `$CLAUDE_PROJECT_DIR` never moves off the\n * PRIMARY clone (the two-tree straddle recorded in shim.ts, and the whole reason H2/H3 are relative\n * while H1 is not). So repairing a LINKED WORKTREE leaves the running session still loading the\n * PRIMARY's files, the PRIMARY's binary and the PRIMARY's pin. Four green lines, and the block does not\n * lift. Nothing printed above is false — but the question the reader has (\"will the block lift?\") went\n * unanswered, which is the same failure this file's header exists to prevent, one level out.\n *\n * THE PREDICATE IS TREE DIVERGENCE, NOT \"am I a subagent\". There is no runtime subagent marker in the\n * hook environment to read, and divergence is the more accurate question anyway: a MAIN agent in a\n * linked worktree HAS this problem (a subagent test would miss it), and a SUBAGENT in the same tree does\n * NOT (a subagent test would cry wolf). Both paths are realpath'd before comparing — a worktree path can\n * arrive symlinked, and /tmp vs /private/tmp on darwin is a live case in this repo's own specs.\n *\n * SILENT when `$CLAUDE_PROJECT_DIR` is unset: a plain CLI run outside Claude Code has no second tree to\n * talk about. And ADVISORY always — it must never turn a verified repair into a failure, so it returns\n * nothing and `verifyRepaired()`'s contract (non-zero only when a surface in THIS tree still differs) is\n * untouched.\n */\n// webpieces-disable no-function-outside-class -- sibling of runUpgradeShim in this deliberately dependency-free bin module\nfunction reportTreeDivergence(root: string): void {\n const projectDir = process.env['CLAUDE_PROJECT_DIR'];\n if (projectDir === undefined || projectDir === '') return;\n if (sameTree(root, projectDir)) return;\n console.log('');\n console.log('⚠️ @webpieces: the tree just repaired is NOT the tree the hooks launch from.');\n console.log(` repaired: ${root}`);\n console.log(` CLAUDE_PROJECT_DIR: ${projectDir}`);\n console.log(' The hooks governing this session resolve through CLAUDE_PROJECT_DIR (H1 is registered');\n console.log(' absolute), so this repair has not changed what is currently enforcing — it made THIS');\n console.log(' tree correct for when its own branch is the one being judged, which is not wasted work.');\n console.log(' To change what is enforcing NOW, run the same repair in the primary tree, and install');\n console.log(' there too — the hooks execute the INSTALLED release, not this tree\\'s source:');\n console.log(` cd ${projectDir} && pnpm install && pnpm exec wp-upgrade-shim`);\n console.log(' Repaired in BOTH trees is the aligned end state, and running it twice is safe.');\n}\n\n/**\n * Do two paths name the same tree? realpath'd (symlinked worktrees, /tmp vs /private/tmp) and stripped\n * of a trailing separator before comparing. A path that cannot be realpath'd falls back to `resolve`,\n * so an absent CLAUDE_PROJECT_DIR directory reads as \"different\" rather than throwing inside a cure.\n */\n// webpieces-disable no-function-outside-class -- sibling of runUpgradeShim in this deliberately dependency-free bin module\nfunction sameTree(a: string, b: string): boolean {\n return canonicalTree(a) === canonicalTree(b);\n}\n\n// webpieces-disable no-function-outside-class -- sibling of runUpgradeShim in this deliberately dependency-free bin module\nfunction canonicalTree(dir: string): string {\n // webpieces-disable no-unmanaged-exceptions -- realpath throws on a path that does not exist; the fallback IS the handling, and an advisory notice must never crash the cure it annotates.\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return path.resolve(fs.realpathSync(dir));\n } catch (err: unknown) {\n const error = toError(err);\n void error; // best-effort: an unresolvable path simply compares as itself\n return path.resolve(dir);\n }\n}\n\n/**\n * DID THE CURE ACTUALLY CURE IT — asked of the same predicate the guard asks, not of our own writes.\n *\n * A cure that cannot fail loudly is worse than no cure. This bin used to print three ✅ lines and\n * return 0 the moment `writeFileSync` did not throw, which asserts only \"the bytes we chose were\n * written\", never \"the surface the guard measures now agrees\". Fault S blocks EVERY tool call, so the\n * one thing a blocked agent must be able to trust is whether the block will lift — and a success line\n * that is not backed by the guard's own check is exactly the false certainty that leaves it retrying a\n * cure that cannot work. So re-run `managedSurfaceDrift()`, the very function `enforceCommittedShim()`\n * calls, and return NON-ZERO naming whatever still differs.\n *\n * Measured against `root` (the tree we just repaired), not `governingShimRoot()` (the tree the running\n * binary came from). Those differ when the cure is run across trees, and the honest claim here is about\n * the files this invocation wrote.\n */\n// webpieces-disable no-function-outside-class -- sibling of runUpgradeShim in this deliberately dependency-free bin module\nfunction verifyRepaired(root: string): number {\n const stillDrifted = managedSurfaceDrift(root);\n if (stillDrifted.length === 0) return 0;\n console.error(`${RED}🛑 @webpieces: the repair ran but ${stillDrifted.length} managed surface(s) STILL differ: ${stillDrifted.join(', ')}.${RESET}`);\n console.error(` The guard will keep blocking. This is a webpieces bug or an unwritable tree under ${root} - do not retry this command in a loop; report it with the list above.`);\n return 1;\n}\n\n/**\n * THE PROCESS ENTRY POINT — the thing whose absence made this whole bin a lie.\n *\n * Up to and including 0.4.588 this module ENDED at the closing brace above. `pnpm exec wp-upgrade-shim`\n * loaded it, defined two functions, and exited 0 having printed nothing and changed no file. Fault S\n * names this command as OPTION 1, the only option that repairs every managed surface, so the\n * guard's own \"THIS IS NOT A DEADLOCK\" promise was false: OPTION 2 repairs one of three, and OPTION 1\n * did nothing at all. Twenty-one unit tests missed it because every one of them called\n * `runUpgradeShim()` as a FUNCTION — the defect lived entirely in what the module does when SPAWNED.\n *\n * `runMain` from @webpieces/rules-config is the repo-wide wrapper and is deliberately NOT used here:\n * this bin must load with fs+path only (see the header) so it still runs on the broken tree it exists\n * to repair. `main()` is the sanctioned exit site instead, and `bin-process-entry.spec.ts` spawns\n * this file as a process so a future refactor cannot silently drop the launcher again.\n */\n// webpieces-disable no-function-outside-class -- bin entry point in this deliberately dependency-free module; see header\nexport function main(): void {\n process.exit(runUpgradeShim(process.cwd()));\n}\n\nif (require.main === module) {\n main();\n}\n"]}
1
+ {"version":3,"file":"upgrade-shim.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/bin/upgrade-shim.ts"],"names":[],"mappings":";;;AA0EA,wCAsCC;AAqKD,oBAEC;;AAtRD,mFAA+E;AAC/E,+CAAyB;AACzB,mDAA6B;AAE7B,iCAA4D;AAC5D,qDAA6E;AAC7E,2DAA8H;AAC9H,+CAAqE;AACrE,iEAA6D;AAE7D,8EAA8E;AAC9E,qGAAqG;AACrG,EAAE;AACF,oGAAoG;AACpG,uGAAuG;AACvG,mGAAmG;AACnG,gFAAgF;AAChF,EAAE;AACF,wGAAwG;AACxG,2FAA2F;AAC3F,qDAAqD;AACrD,sGAAsG;AACtG,yGAAyG;AACzG,iDAAiD;AACjD,mGAAmG;AACnG,mGAAmG;AACnG,qGAAqG;AACrG,mGAAmG;AACnG,sGAAsG;AACtG,sGAAsG;AACtG,oGAAoG;AACpG,0BAA0B;AAC1B,wGAAwG;AACxG,wGAAwG;AACxG,wGAAwG;AACxG,yEAAyE;AACzE,4GAA4G;AAC5G,gFAAgF;AAChF,EAAE;AACF,yGAAyG;AAC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CAAC;IAC9C,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,KAAK,KAAK,CAAC,CAAC,8DAA8D;QAC1E,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IAC7B,CAAC;AACL,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,2HAA2H;AAC3H,SAAS,cAAc,CAAC,IAAY;IAChC,MAAM,YAAY,GAAG,IAAA,uCAAmB,EAAC,IAAI,CAAC,CAAC;IAC/C,IAAI,YAAY,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,CAAC,CAAC;IACxC,OAAO,CAAC,KAAK,CAAC,GAAG,GAAG,qCAAqC,YAAY,CAAC,MAAM,qCAAqC,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,KAAK,EAAE,CAAC,CAAC;IACrJ,OAAO,CAAC,KAAK,CAAC,uFAAuF,IAAI,wEAAwE,CAAC,CAAC;IACnL,OAAO,CAAC,CAAC;AACb,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,yHAAyH;AACzH,SAAgB,IAAI;IAChB,OAAO,CAAC,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;AAChD,CAAC;AAED,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;IAC1B,IAAI,EAAE,CAAC;AACX,CAAC","sourcesContent":["#!/usr/bin/env node\nimport { RepositoryLayout } from '@webpieces/tooling-common/repository-layout';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nimport { renderShim, shimPath, findShimRoot } from './shim';\nimport { REVIEWER_AGENT_MARKER, writeReviewerAgent } from './reviewer-agent';\nimport { repairRegistrationAt, managedSurfaceDrift, SettingsRepair, LEGACY_GUARANTEE_ROOT_MARKER } from './hook-registration';\nimport { BASH_CWD_ENV_KEY, BASH_CWD_ENV_VALUE } from './managed-env';\nimport { toError } from '@webpieces/tooling-common/to-error';\n\n// ---------------------------------------------------------------------------\n// The `wp-upgrade-shim` entry point — the CURE for the managed-hook-surface self-guard (L0 fault S).\n//\n// WHAT IT REPAIRS, and why all of them (2026-08-07, extended). This used to write EXACTLY ONE FILE,\n// ai-hook.sh, and touch nothing else. That was correct while the installed surface WAS one file. It is\n// now five (the name `wp-upgrade-shim` is older than the job and is NOT renamed — a rename with no\n// functional change is a cost with no payer; the prose is what gets corrected):\n//\n// 1. .claude/webpieces/ai-hook.sh the ONE guard shim, shared by every harness and registered\n// ABSOLUTE, so the MAIN tree governs every tree\n// 2. the .claude/settings.json registration itself\n// 3. the .codex/hooks.json registration — the SAME two hooks under Codex's own matchers and its own\n// $PWD anchor. Repaired only where it already EXISTS: arming a harness is the installer's decision,\n// this is the cure for one that has drifted\n// 3b. the NEIGHBOUR hook commands in both of those files — the entries a CONSUMER repo registers\n// beside webpieces' own. A repo-RELATIVE entry path (`node \".claude/hooks/guard-deploy.mjs\"`)\n// resolves against the hook process's cwd, so it dies the moment that cwd is not the repo root,\n// and per the hooks reference that non-zero exit is a NON-BLOCKING error — a SILENT UNGUARDED\n// ALLOW. Measured in a consumer repo (issue #852) silently disarming three security guards while\n// printing nothing but a `node:internal/modules/cjs/loader` fragment with no rule name. They are\n// anchored to the harness's own prefix, the same reversal webpieces made for its own hook. See\n// neighbour-hooks.ts\n// 4. the .claude/settings.json `env` entry CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR=1, which pins the\n// Bash cwd to the project root — and, because settings `env` is inherited, pins it identically for\n// every subagent, so a verdict never depends on where an earlier `cd` left the shell. Claude-only:\n// Codex has no settings `env`, and its cwd is measured not to drift\n// 5. .claude/agents/webpieces-reviewer.md — the generic PR-gate reviewer agent (issue #938), a committed,\n// generated file with the same contract as the shim; see reviewer-agent.ts\n//\n// WHAT IT DELIBERATELY DOES *NOT* DO: sweep this tree's dangling `node_modules/.bin/wp-*` symlinks. That\n// is the same class of defect as the retired-file removal below — an entry pointing at a missing file is\n// worse than absence, because `ls node_modules/.bin` advertises a capability that only fails on execution\n// — and it WOULD read naturally here. It is not here because the one implementation of that sweep lives in\n// `@webpieces/rules-config` (`stale-bin-sweep.ts`), which this module may not import: the barrel pulls in\n// inversify and the config loader, and a subpath import resolves against the INSTALLED rules-config, which\n// is a release behind this source (see .claude/rules/published-vs-local-source.md) — so a spawned\n// `wp-upgrade-shim` would die on module resolution, in the one command an L0-blocked session has left. A\n// second copy of the sweep here would be a second spelling of it, which is worse again.\n//\n// It does not need to be here. The sweep rides the `wp-*` startup pass that regenerates\n// `.webpieces-logs/instruct-ai/*`, so ANY `wp-*` command heals the tree — including the `pnpm install` +\n// `pnpm exec wp-upgrade-shim` sequence this bin's own advice ends with.\n//\n// It also DELETES the retired `.claude/webpieces/guarantee-root.sh` and any settings entry still naming\n// it. That file was the L-1 hook, which existed only to guarantee the once-RELATIVE shim path resolved;\n// an absolute path resolves from any cwd, so it has no job left. Removing the file without removing the\n// entry (or vice versa) is the worst possible half-state — a registered hook pointing at a missing file\n// exits 127, which per the hooks reference is a NON-BLOCKING error, i.e. a SILENT UNGUARDED ALLOW — so\n// both happen here, file first.\n//\n// A cure that fixes some of them is worse than no cure, because it reports success. This bin is the\n// sanctioned cure named in fault S's message and is on the L0 allowlist, so it must repair everything.\n//\n// Deliberately imports only ./shim and ./hook-registration (fs + path) + toError,\n// exactly like install-entry: the whole job is to rewrite webpieces-managed files, which never needed\n// the rule engine, and it must stay runnable on a tree too broken to load it.\n// ---------------------------------------------------------------------------\nconst RED = '[31;1m';\nconst RESET = '[0m';\n\n// Returns the process exit code (0 = ok). Kept as a function (not top-level code) so it is unit-testable\n// without spawning node.\n// webpieces-disable no-function-outside-class -- bin entry point: this module MUST load with only fs+path (see header), mirroring install-entry.ts. A DI-managed class would pull the container in and reintroduce the require-time crash this dependency-free path exists to survive.\nexport function runUpgradeShim(cwd: string): number {\n const root = findShimRoot(cwd);\n if (root === null) {\n console.error(`${RED}🛑 @webpieces: no committed .claude/webpieces/ai-hook.sh found to regenerate.${RESET}`);\n console.error(' Run this from a repo that installs @webpieces/agent-workflow-rules, or run the installer (pnpm wp-install-ai-hooks).');\n return 1;\n }\n const target = shimPath(root);\n // webpieces-disable no-unmanaged-exceptions -- bin entry chokepoint: turn an fs error into an actionable line + non-zero exit rather than a raw node trace; there is no caller above a bin to handle it.\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n new RepositoryLayout().migrate(root);\n fs.writeFileSync(target, renderShim(), { mode: 0o755 });\n // writeFileSync's mode only applies on create; force it on overwrite too (matches writeShim).\n fs.chmodSync(target, 0o755);\n // ORDER MATTERS, and it is registration-FIRST. The reverse leaves a window in which a settings\n // entry still names a file that is gone — exit 127, which the hooks reference defines as a\n // NON-BLOCKING error, i.e. a SILENT UNGUARDED ALLOW. This way round the transient state is an\n // ORPHANED FILE that nothing references, which is inert. (An earlier draft of this function\n // argued file-first was safer; it is not. repairRegistration() also early-returns when the file\n // registers no guard bins, and the retired H1 command contains neither bin name, so a\n // guarantee-root-ONLY settings file would have lost the file and kept the entry.)\n const repairs = repairRegistrationAt(root);\n const removedLegacy = removeRetiredGuaranteeRoot(root);\n // The generic PR-gate reviewer agent — a managed file like the shim, so the one cure rewrites it too.\n if (writeReviewerAgent(root)) {\n console.log(`✅ @webpieces: wrote the generic PR-gate reviewer agent ${REVIEWER_AGENT_MARKER} (generated — commit it, do not edit it).`);\n }\n reportRepairs(target, removedLegacy, repairs);\n // ADVISORY ONLY, and deliberately after the ✅ lines: it never touches the exit code (see\n // reportTreeDivergence).\n reportTreeDivergence(root);\n return verifyRepaired(root);\n } catch (err: unknown) {\n const error = toError(err);\n console.error(`${RED}🛑 @webpieces: could not write under ${root}: ${error.message}${RESET}`);\n return 1;\n }\n}\n\n/**\n * Say what was actually done, per managed thing. The old single line (\"regenerated the managed shim\")\n * would now be a lie by omission on the three most important repairs — and an agent reading a cure's\n * output is how it decides whether the cure worked.\n *\n * Each settings file reports the repairs IT needed, from the flags recorded before the rewrite. Printing\n * \"rewrote the hook registration\" for a file whose hooks were already current and whose `env` entry was\n * the only thing missing would be the same class of dishonesty one level down.\n */\n// webpieces-disable no-function-outside-class -- sibling of runUpgradeShim in this deliberately dependency-free bin module\n/**\n * Delete the RETIRED L-1 hook file, returning whether there was one. Removal-only, one way, no writer.\n *\n * This runs AFTER repairRegistrationAt(), which strips the stale H1 ENTRY from settings.json. Removing\n * the entry first means the file is merely orphaned in between — inert, because nothing references it.\n * File-first would instead leave a registered hook pointing at a missing file, and per the hooks\n * reference a non-2 non-zero exit is a NON-BLOCKING error: every `cd` would go unjudged.\n */\n// webpieces-disable no-function-outside-class -- module-scope like every other helper in this bin, which must load on a tree too broken to build a DI container\nfunction removeRetiredGuaranteeRoot(root: string): boolean {\n // The path comes from LEGACY_GUARANTEE_ROOT_MARKER, never re-spelled here: a second literal is a\n // second spelling, and when the expiry in hook-registration.ts fires the documented removal would\n // miss this copy and the dead name would survive in a file nobody thought to grep.\n const legacy = path.join(root, LEGACY_GUARANTEE_ROOT_MARKER);\n if (!fs.existsSync(legacy)) return false;\n fs.rmSync(legacy, { force: true });\n return true;\n}\n\n// webpieces-disable no-function-outside-class -- module-scope like every other helper in this bin, which must load on a tree too broken to build a DI container\nfunction reportRepairs(shimFile: string, removedLegacy: boolean, repairs: readonly SettingsRepair[]): void {\n console.log(`✅ @webpieces: regenerated the managed shim at ${shimFile} — tool calls are re-armed.`);\n if (removedLegacy) {\n console.log('✅ @webpieces: deleted the RETIRED L-1 hook .claude/webpieces/guarantee-root.sh.');\n console.log(' The guard hooks are ABSOLUTE now, so the launch guarantee it provided is structural.');\n }\n if (repairs.length === 0) {\n console.log(' .claude/settings.json (hook registration + managed env) already matches this release — no change.');\n }\n for (const repair of repairs) {\n if (repair.registration) {\n console.log(`✅ @webpieces: rewrote the hook registration in ${repair.settingsPath} to the two-hook form`);\n console.log(' (both guard hooks ABSOLUTE via $CLAUDE_PROJECT_DIR, so the MAIN tree governs every tree;');\n console.log(' any retired guarantee-root.sh entry was removed).');\n }\n for (const command of repair.anchoredNeighbours) {\n console.log(`✅ @webpieces: anchored a RELATIVE hook command in ${repair.settingsPath} so it resolves from any cwd`);\n console.log(` now: ${command}`);\n console.log(' (a relative entry path resolves against the hook process cwd; off the repo root it fails to load, and');\n console.log(' per the hooks reference that non-zero exit is NON-BLOCKING — the guard silently stops guarding.)');\n }\n if (repair.env) {\n console.log(`✅ @webpieces: set env.${BASH_CWD_ENV_KEY}=${BASH_CWD_ENV_VALUE} in ${repair.settingsPath}`);\n console.log(' (pins the Bash cwd to the project root, so the guard hooks resolve identically for every subagent — for');\n console.log(' this session and, because settings env is inherited, for every subagent it spawns).');\n }\n }\n console.log(' These files are generated + committed by webpieces; do not revert or hand-edit them.');\n}\n\n/**\n * WAS THE REPAIRED TREE THE TREE THE HOOKS LAUNCH FROM — the second way this cure can report success\n * while changing nothing the session is actually governed by.\n *\n * H1 is registered ABSOLUTE, `sh \"$CLAUDE_PROJECT_DIR/…\"`, and `$CLAUDE_PROJECT_DIR` never moves off the\n * PRIMARY clone (the two-tree straddle recorded in shim.ts, and the whole reason H2/H3 are relative\n * while H1 is not). So repairing a LINKED WORKTREE leaves the running session still loading the\n * PRIMARY's files, the PRIMARY's binary and the PRIMARY's pin. Four green lines, and the block does not\n * lift. Nothing printed above is false — but the question the reader has (\"will the block lift?\") went\n * unanswered, which is the same failure this file's header exists to prevent, one level out.\n *\n * THE PREDICATE IS TREE DIVERGENCE, NOT \"am I a subagent\". There is no runtime subagent marker in the\n * hook environment to read, and divergence is the more accurate question anyway: a MAIN agent in a\n * linked worktree HAS this problem (a subagent test would miss it), and a SUBAGENT in the same tree does\n * NOT (a subagent test would cry wolf). Both paths are realpath'd before comparing — a worktree path can\n * arrive symlinked, and /tmp vs /private/tmp on darwin is a live case in this repo's own specs.\n *\n * SILENT when `$CLAUDE_PROJECT_DIR` is unset: a plain CLI run outside Claude Code has no second tree to\n * talk about. And ADVISORY always — it must never turn a verified repair into a failure, so it returns\n * nothing and `verifyRepaired()`'s contract (non-zero only when a surface in THIS tree still differs) is\n * untouched.\n */\n// webpieces-disable no-function-outside-class -- sibling of runUpgradeShim in this deliberately dependency-free bin module\nfunction reportTreeDivergence(root: string): void {\n const projectDir = process.env['CLAUDE_PROJECT_DIR'];\n if (projectDir === undefined || projectDir === '') return;\n if (sameTree(root, projectDir)) return;\n console.log('');\n console.log('⚠️ @webpieces: the tree just repaired is NOT the tree the hooks launch from.');\n console.log(` repaired: ${root}`);\n console.log(` CLAUDE_PROJECT_DIR: ${projectDir}`);\n console.log(' The hooks governing this session resolve through CLAUDE_PROJECT_DIR (H1 is registered');\n console.log(' absolute), so this repair has not changed what is currently enforcing — it made THIS');\n console.log(' tree correct for when its own branch is the one being judged, which is not wasted work.');\n console.log(' To change what is enforcing NOW, run the same repair in the primary tree, and install');\n console.log(' there too — the hooks execute the INSTALLED release, not this tree\\'s source:');\n console.log(` cd ${projectDir} && pnpm install && pnpm exec wp-upgrade-shim`);\n console.log(' Repaired in BOTH trees is the aligned end state, and running it twice is safe.');\n}\n\n/**\n * Do two paths name the same tree? realpath'd (symlinked worktrees, /tmp vs /private/tmp) and stripped\n * of a trailing separator before comparing. A path that cannot be realpath'd falls back to `resolve`,\n * so an absent CLAUDE_PROJECT_DIR directory reads as \"different\" rather than throwing inside a cure.\n */\n// webpieces-disable no-function-outside-class -- sibling of runUpgradeShim in this deliberately dependency-free bin module\nfunction sameTree(a: string, b: string): boolean {\n return canonicalTree(a) === canonicalTree(b);\n}\n\n// webpieces-disable no-function-outside-class -- sibling of runUpgradeShim in this deliberately dependency-free bin module\nfunction canonicalTree(dir: string): string {\n // webpieces-disable no-unmanaged-exceptions -- realpath throws on a path that does not exist; the fallback IS the handling, and an advisory notice must never crash the cure it annotates.\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return path.resolve(fs.realpathSync(dir));\n } catch (err: unknown) {\n const error = toError(err);\n void error; // best-effort: an unresolvable path simply compares as itself\n return path.resolve(dir);\n }\n}\n\n/**\n * DID THE CURE ACTUALLY CURE IT — asked of the same predicate the guard asks, not of our own writes.\n *\n * A cure that cannot fail loudly is worse than no cure. This bin used to print three ✅ lines and\n * return 0 the moment `writeFileSync` did not throw, which asserts only \"the bytes we chose were\n * written\", never \"the surface the guard measures now agrees\". Fault S blocks EVERY tool call, so the\n * one thing a blocked agent must be able to trust is whether the block will lift — and a success line\n * that is not backed by the guard's own check is exactly the false certainty that leaves it retrying a\n * cure that cannot work. So re-run `managedSurfaceDrift()`, the very function `enforceCommittedShim()`\n * calls, and return NON-ZERO naming whatever still differs.\n *\n * Measured against `root` (the tree we just repaired), not `governingShimRoot()` (the tree the running\n * binary came from). Those differ when the cure is run across trees, and the honest claim here is about\n * the files this invocation wrote.\n */\n// webpieces-disable no-function-outside-class -- sibling of runUpgradeShim in this deliberately dependency-free bin module\nfunction verifyRepaired(root: string): number {\n const stillDrifted = managedSurfaceDrift(root);\n if (stillDrifted.length === 0) return 0;\n console.error(`${RED}🛑 @webpieces: the repair ran but ${stillDrifted.length} managed surface(s) STILL differ: ${stillDrifted.join(', ')}.${RESET}`);\n console.error(` The guard will keep blocking. This is a webpieces bug or an unwritable tree under ${root} - do not retry this command in a loop; report it with the list above.`);\n return 1;\n}\n\n/**\n * THE PROCESS ENTRY POINT — the thing whose absence made this whole bin a lie.\n *\n * Up to and including 0.4.588 this module ENDED at the closing brace above. `pnpm exec wp-upgrade-shim`\n * loaded it, defined two functions, and exited 0 having printed nothing and changed no file. Fault S\n * names this command as OPTION 1, the only option that repairs every managed surface, so the\n * guard's own \"THIS IS NOT A DEADLOCK\" promise was false: OPTION 2 repairs one of three, and OPTION 1\n * did nothing at all. Twenty-one unit tests missed it because every one of them called\n * `runUpgradeShim()` as a FUNCTION — the defect lived entirely in what the module does when SPAWNED.\n *\n * `runMain` from @webpieces/rules-config is the repo-wide wrapper and is deliberately NOT used here:\n * this bin must load with fs+path only (see the header) so it still runs on the broken tree it exists\n * to repair. `main()` is the sanctioned exit site instead, and `bin-process-entry.spec.ts` spawns\n * this file as a process so a future refactor cannot silently drop the launcher again.\n */\n// webpieces-disable no-function-outside-class -- bin entry point in this deliberately dependency-free module; see header\nexport function main(): void {\n process.exit(runUpgradeShim(process.cwd()));\n}\n\nif (require.main === module) {\n main();\n}\n"]}
@@ -14,7 +14,7 @@ export declare const DEFAULT_MAX_COMMITS_BEHIND = 5;
14
14
  * Bash | stale-main-bash-guard | merged-branch-bash-guard
15
15
  *
16
16
  * Those four class NAMES are unchanged and still appear in every decision-log line as `rule=`, so
17
- * `grep rule=stale-main-bash-guard` over `.webpieces/logs/L2-decisions` keeps working. What merged is
17
+ * `grep rule=stale-main-bash-guard` over `.webpieces-logs/logs/L2-decisions` keeps working. What merged is
18
18
  * the SWITCH: all four read this one config entry (`AbstractRule.configKey`).
19
19
  *
20
20
  * ## Why one key and not four
@@ -17,7 +17,7 @@ exports.DEFAULT_MAX_COMMITS_BEHIND = 5;
17
17
  * Bash | stale-main-bash-guard | merged-branch-bash-guard
18
18
  *
19
19
  * Those four class NAMES are unchanged and still appear in every decision-log line as `rule=`, so
20
- * `grep rule=stale-main-bash-guard` over `.webpieces/logs/L2-decisions` keeps working. What merged is
20
+ * `grep rule=stale-main-bash-guard` over `.webpieces-logs/logs/L2-decisions` keeps working. What merged is
21
21
  * the SWITCH: all four read this one config entry (`AbstractRule.configKey`).
22
22
  *
23
23
  * ## Why one key and not four
@@ -1 +1 @@
1
- {"version":3,"file":"main-sync-guard-configs.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/configs/main-sync-guard-configs.ts"],"names":[],"mappings":";;;AAAA,oDAA+F;AAC/F,oDAA+D;AAClD,QAAA,0BAA0B,GAAG,CAAC,CAAC;AAE5C;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,MAAa,sBAAuB,SAAQ,0BAAc;IAEtD,oGAAoG;IACpG,uEAAuE;IACvE,sBAAsB,CAAU;IAChC,oGAAoG;IACpG,wEAAwE;IACxE,kBAAkB,CAAU;IAC5B,6FAA6F;IAC7F,oFAAoF;IACpF,gBAAgB,CAAU;IAE1B,MAAM,CAAU,MAAM,GAAwC;QAC1D,IAAI,EAAE,IAAI,oBAAQ,CAAC,QAAQ,EAAE,wBAAY,CAAC;QAC1C,sBAAsB,EAAE,oBAAQ,CAAC,QAAQ,CAAC,QAAQ,CAAC;QACnD,kBAAkB,EAAE,oBAAQ,CAAC,QAAQ,CAAC,QAAQ,CAAC;QAC/C,gBAAgB,EAAE,IAAI,oBAAQ,CAAC,QAAQ,CAAC;QACxC,GAAG,4BAAgB;KACtB,CAAC;;AAlBN,wDAmBC","sourcesContent":["import { FieldDef, SchemaShape, BaseRuleConfig, BASE_RULE_SCHEMA } from \"@webpieces/rules-sdk\";\nimport { OnOffMode, ON_OFF_MODES } from \"@webpieces/rules-sdk\";\nexport const DEFAULT_MAX_COMMITS_BEHIND = 5;\n\n/**\n * `branch-state-guard` — ONE key, ONE policy: *may I work here, and is what I read current?*\n *\n * Four CLASSES implement it, because the tool wiring genuinely differs (a Read names one file, a Bash\n * command is opaque, and the two Bash halves are not De Morgan duals of each other — see\n * guards/L2-branch-state.md, \"Deliberate divergence\"):\n *\n * | on stale `main` (state A) | on an already-merged branch (state B)\n * Write/Edit | feature-branch-guard | feature-branch-guard\n * Read | read-stale-guard | read-stale-guard\n * Bash | stale-main-bash-guard | merged-branch-bash-guard\n *\n * Those four class NAMES are unchanged and still appear in every decision-log line as `rule=`, so\n * `grep rule=stale-main-bash-guard` over `.webpieces/logs/L2-decisions` keeps working. What merged is\n * the SWITCH: all four read this one config entry (`AbstractRule.configKey`).\n *\n * ## Why one key and not four\n *\n * Four keys made **half a policy representable**: `read-stale-guard: OFF` beside\n * `merged-branch-bash-guard: ON` is \"read the file, yes; `cat` the same file, no\" — the same\n * information, opposite verdicts. Nobody chose that; it was reachable because the config had a knob\n * per class instead of a knob per decision. One key makes it unconstructible.\n *\n * And `hangTimeoutMinutes` was declared four times, read four times, and fed ONE shared refresher for\n * ONE shared cache — with a per-process latch (main-sync-refresh.ts) plus config-blind callers ahead of\n * the guards, so at most one of the four values could ever reach a spawn. Four knobs, one honoured; now\n * one knob, honoured everywhere (runner + hook-core route through this entry too).\n */\nexport class BranchStateGuardConfig extends BaseRuleConfig {\n declare mode?: OnOffMode;\n // Surfaced verbatim in the on-main block's message, so a project's own convention is what the agent\n // is told to follow. Consumed by FeatureBranchGuardRule.onMainMessage.\n branchNamingConvention?: string;\n // Tunes the DETACHED refresher's stale-lock reclaim window (main-sync.lock.json). One value for one\n // refresher writing one cache — which is what it always physically was.\n hangTimeoutMinutes?: number;\n // Maximum cached commit distance tolerated on local main. Required so every repo consciously\n // carries the policy; 5 means 0..5 are allowed and stale-main blocks starting at 6.\n maxCommitsBehind!: number;\n\n static readonly SCHEMA: SchemaShape<BranchStateGuardConfig> = {\n mode: new FieldDef('string', ON_OFF_MODES),\n branchNamingConvention: FieldDef.optional('string'),\n hangTimeoutMinutes: FieldDef.optional('number'),\n maxCommitsBehind: new FieldDef('number'),\n ...BASE_RULE_SCHEMA,\n };\n}\n"]}
1
+ {"version":3,"file":"main-sync-guard-configs.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/configs/main-sync-guard-configs.ts"],"names":[],"mappings":";;;AAAA,oDAA+F;AAC/F,oDAA+D;AAClD,QAAA,0BAA0B,GAAG,CAAC,CAAC;AAE5C;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,MAAa,sBAAuB,SAAQ,0BAAc;IAEtD,oGAAoG;IACpG,uEAAuE;IACvE,sBAAsB,CAAU;IAChC,oGAAoG;IACpG,wEAAwE;IACxE,kBAAkB,CAAU;IAC5B,6FAA6F;IAC7F,oFAAoF;IACpF,gBAAgB,CAAU;IAE1B,MAAM,CAAU,MAAM,GAAwC;QAC1D,IAAI,EAAE,IAAI,oBAAQ,CAAC,QAAQ,EAAE,wBAAY,CAAC;QAC1C,sBAAsB,EAAE,oBAAQ,CAAC,QAAQ,CAAC,QAAQ,CAAC;QACnD,kBAAkB,EAAE,oBAAQ,CAAC,QAAQ,CAAC,QAAQ,CAAC;QAC/C,gBAAgB,EAAE,IAAI,oBAAQ,CAAC,QAAQ,CAAC;QACxC,GAAG,4BAAgB;KACtB,CAAC;;AAlBN,wDAmBC","sourcesContent":["import { FieldDef, SchemaShape, BaseRuleConfig, BASE_RULE_SCHEMA } from \"@webpieces/rules-sdk\";\nimport { OnOffMode, ON_OFF_MODES } from \"@webpieces/rules-sdk\";\nexport const DEFAULT_MAX_COMMITS_BEHIND = 5;\n\n/**\n * `branch-state-guard` — ONE key, ONE policy: *may I work here, and is what I read current?*\n *\n * Four CLASSES implement it, because the tool wiring genuinely differs (a Read names one file, a Bash\n * command is opaque, and the two Bash halves are not De Morgan duals of each other — see\n * guards/L2-branch-state.md, \"Deliberate divergence\"):\n *\n * | on stale `main` (state A) | on an already-merged branch (state B)\n * Write/Edit | feature-branch-guard | feature-branch-guard\n * Read | read-stale-guard | read-stale-guard\n * Bash | stale-main-bash-guard | merged-branch-bash-guard\n *\n * Those four class NAMES are unchanged and still appear in every decision-log line as `rule=`, so\n * `grep rule=stale-main-bash-guard` over `.webpieces-logs/logs/L2-decisions` keeps working. What merged is\n * the SWITCH: all four read this one config entry (`AbstractRule.configKey`).\n *\n * ## Why one key and not four\n *\n * Four keys made **half a policy representable**: `read-stale-guard: OFF` beside\n * `merged-branch-bash-guard: ON` is \"read the file, yes; `cat` the same file, no\" — the same\n * information, opposite verdicts. Nobody chose that; it was reachable because the config had a knob\n * per class instead of a knob per decision. One key makes it unconstructible.\n *\n * And `hangTimeoutMinutes` was declared four times, read four times, and fed ONE shared refresher for\n * ONE shared cache — with a per-process latch (main-sync-refresh.ts) plus config-blind callers ahead of\n * the guards, so at most one of the four values could ever reach a spawn. Four knobs, one honoured; now\n * one knob, honoured everywhere (runner + hook-core route through this entry too).\n */\nexport class BranchStateGuardConfig extends BaseRuleConfig {\n declare mode?: OnOffMode;\n // Surfaced verbatim in the on-main block's message, so a project's own convention is what the agent\n // is told to follow. Consumed by FeatureBranchGuardRule.onMainMessage.\n branchNamingConvention?: string;\n // Tunes the DETACHED refresher's stale-lock reclaim window (main-sync.lock.json). One value for one\n // refresher writing one cache — which is what it always physically was.\n hangTimeoutMinutes?: number;\n // Maximum cached commit distance tolerated on local main. Required so every repo consciously\n // carries the policy; 5 means 0..5 are allowed and stale-main blocks starting at 6.\n maxCommitsBehind!: number;\n\n static readonly SCHEMA: SchemaShape<BranchStateGuardConfig> = {\n mode: new FieldDef('string', ON_OFF_MODES),\n branchNamingConvention: FieldDef.optional('string'),\n hangTimeoutMinutes: FieldDef.optional('number'),\n maxCommitsBehind: new FieldDef('number'),\n ...BASE_RULE_SCHEMA,\n };\n}\n"]}
@@ -109,18 +109,18 @@ export declare class GuardDecision {
109
109
  constructor(rule: string, tool: string, target: string, branch: string, verdict: Verdict, reason: string, cache: string | undefined, fault: string, matrix: MatrixRef);
110
110
  }
111
111
  /**
112
- * Append one tab-separated line per L2 decision to `.webpieces/logs/L2-decisions/<writer>.log`, where
112
+ * Append one tab-separated line per L2 decision to `.webpieces-logs/logs/L2-decisions/<writer>.log`, where
113
113
  * <writer> is LogStream's `<sessionId>-<agentId|coordinator>-<hook>` key (a caller that never
114
114
  * identified renders as `unknown-coordinator-hook` — there is no un-keyed name).
115
115
  * `root` is
116
- * the repo/workspace root that holds `.webpieces` (callers pass workspaceRoot, or a
116
+ * the repo/workspace root that holds `.webpieces-logs` (callers pass workspaceRoot, or a
117
117
  * RepoRootFinder-resolved root at the pre-load config-bypass site — never a raw cwd, so a bypass
118
- * logged from a subdir never scatters a stray `.webpieces`). Swallows all errors — logging must never
118
+ * logged from a subdir never scatters a stray `.webpieces-logs`). Swallows all errors — logging must never
119
119
  * block or fail a hook.
120
120
  */
121
121
  export declare function logGuardDecision(root: string, decision: GuardDecision): void;
122
122
  /**
123
- * The L1 stream — `.webpieces/logs/L1-location/<writer>.log`.
123
+ * The L1 stream — `.webpieces-logs/logs/L1-location/<writer>.log`.
124
124
  *
125
125
  * L1 had NO stream. Its three blocking paths wrote into L2's file under an implementation name
126
126
  * (`force-to-root`, `trinary-version-skew`, `cd-must-be-first`), and its NON-blocking outcomes —
@@ -149,7 +149,7 @@ export declare class GuardInvocation {
149
149
  constructor(root: string, timestamp: string, tool: string, target: string, branch: string, sync: string, projectDir: string);
150
150
  }
151
151
  /**
152
- * The per-INVOCATION stream — `.webpieces/logs/calls/<writer>.log` (see LogStream for the writer
152
+ * The per-INVOCATION stream — `.webpieces-logs/logs/calls/<writer>.log` (see LogStream for the writer
153
153
  * key), one line for EVERY guards-hook
154
154
  * call (allow or block, bash or file), unlike `L2-decisions/` which records only the calls a
155
155
  * rule actually judged. It captures the tool, the command/file, the live git branch, the async-written
@@ -171,7 +171,7 @@ export declare class InvocationLog {
171
171
  private pending;
172
172
  /**
173
173
  * Capture the context of one invocation. `cwd` is the AI's working dir; the repo root that owns
174
- * `.webpieces` is resolved from it. Writes NOTHING — {@link finish} does that.
174
+ * `.webpieces-logs` is resolved from it. Writes NOTHING — {@link finish} does that.
175
175
  */
176
176
  begin(cwd: string, tool: string, target: string): void;
177
177
  /**
@@ -24,7 +24,7 @@ const matrix_cures_1 = require("./matrix-cures");
24
24
  // the ASYNC log (the `async-refresh/` stream, written by the detached refresher in main-sync-log.ts). This
25
25
  // one records EVERY guard decision — allow, block, config-bypass, and the fail-open cases — and CITES
26
26
  // the async-written cache snapshot (`cache` field) that drove the decision, so a wrong allow/block is
27
- // traceable to a stale or missing async write. Writes to `.webpieces/logs/L2-decisions/<writer>.log` —
27
+ // traceable to a stale or missing async write. Writes to `.webpieces-logs/logs/L2-decisions/<writer>.log` —
28
28
  // the LAYER is the directory, the WRITER is the file (see log-streams.ts and LogStream).
29
29
  const MAX_LOG_BYTES = 512 * 1024; // 512 KB — rotate when exceeded (mirrors rotation in rejection-log)
30
30
  /**
@@ -136,13 +136,13 @@ class GuardDecision {
136
136
  }
137
137
  exports.GuardDecision = GuardDecision;
138
138
  /**
139
- * Append one tab-separated line per L2 decision to `.webpieces/logs/L2-decisions/<writer>.log`, where
139
+ * Append one tab-separated line per L2 decision to `.webpieces-logs/logs/L2-decisions/<writer>.log`, where
140
140
  * <writer> is LogStream's `<sessionId>-<agentId|coordinator>-<hook>` key (a caller that never
141
141
  * identified renders as `unknown-coordinator-hook` — there is no un-keyed name).
142
142
  * `root` is
143
- * the repo/workspace root that holds `.webpieces` (callers pass workspaceRoot, or a
143
+ * the repo/workspace root that holds `.webpieces-logs` (callers pass workspaceRoot, or a
144
144
  * RepoRootFinder-resolved root at the pre-load config-bypass site — never a raw cwd, so a bypass
145
- * logged from a subdir never scatters a stray `.webpieces`). Swallows all errors — logging must never
145
+ * logged from a subdir never scatters a stray `.webpieces-logs`). Swallows all errors — logging must never
146
146
  * block or fail a hook.
147
147
  */
148
148
  // webpieces-disable no-function-outside-class -- the module-scope writer this log has always been, beside branchForLog/oneLine/rotateLogFile; it must stay callable from a tree too broken to build a DI container
@@ -150,7 +150,7 @@ function logGuardDecision(root, decision) {
150
150
  appendDecision(root, log_streams_1.L2_DECISIONS_STREAM, decision);
151
151
  }
152
152
  /**
153
- * The L1 stream — `.webpieces/logs/L1-location/<writer>.log`.
153
+ * The L1 stream — `.webpieces-logs/logs/L1-location/<writer>.log`.
154
154
  *
155
155
  * L1 had NO stream. Its three blocking paths wrote into L2's file under an implementation name
156
156
  * (`force-to-root`, `trinary-version-skew`, `cd-must-be-first`), and its NON-blocking outcomes —
@@ -250,7 +250,7 @@ class GuardInvocation {
250
250
  }
251
251
  exports.GuardInvocation = GuardInvocation;
252
252
  /**
253
- * The per-INVOCATION stream — `.webpieces/logs/calls/<writer>.log` (see LogStream for the writer
253
+ * The per-INVOCATION stream — `.webpieces-logs/logs/calls/<writer>.log` (see LogStream for the writer
254
254
  * key), one line for EVERY guards-hook
255
255
  * call (allow or block, bash or file), unlike `L2-decisions/` which records only the calls a
256
256
  * rule actually judged. It captures the tool, the command/file, the live git branch, the async-written
@@ -272,7 +272,7 @@ class InvocationLog {
272
272
  pending = null;
273
273
  /**
274
274
  * Capture the context of one invocation. `cwd` is the AI's working dir; the repo root that owns
275
- * `.webpieces` is resolved from it. Writes NOTHING — {@link finish} does that.
275
+ * `.webpieces-logs` is resolved from it. Writes NOTHING — {@link finish} does that.
276
276
  */
277
277
  begin(cwd, tool, target) {
278
278
  // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
@@ -1 +1 @@
1
- {"version":3,"file":"decision-log.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/core/decision-log.ts"],"names":[],"mappings":";;;AAqGA,kCAGC;AAkED,4CAEC;AAiBD,sCAEC;AAsMD,oCAaC;;AAlZD,iDAAyC;AACzC,+CAAyB;AACzB,mDAA6B;AAE7B,8DAAyD;AACzD,sEAAmF;AACnF,0DAAoE;AACpE,+CAAsF;AAEtF,0DAA4F;AAC5F,iEAA6D;AAC7D,6CAAyC;AACzC,6CAAyC;AACzC,uDAAkD;AAClD,uCAA2C;AAC3C,iDAA+C;AAE/C,qGAAqG;AACrG,2GAA2G;AAC3G,sGAAsG;AACtG,sGAAsG;AACtG,uGAAuG;AACvG,yFAAyF;AACzF,MAAM,aAAa,GAAG,GAAG,GAAG,IAAI,CAAC,CAAC,oEAAoE;AA6BtG;;;;;;;GAOG;AACH,MAAa,SAAS;IACG;IAAwB;IAA7C,YAAqB,KAAa,EAAW,GAAW;QAAnC,UAAK,GAAL,KAAK,CAAQ;QAAW,QAAG,GAAH,GAAG,CAAQ;IAAG,CAAC;CAC/D;AAFD,8BAEC;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACU,QAAA,eAAe,GAAG,IAAI,SAAS,CAAC,IAAI,EAAE,iCAAkB,CAAC,CAAC;AAC1D,QAAA,eAAe,GAAG,IAAI,SAAS,CAAC,IAAI,EAAE,6BAAc,CAAC,CAAC;AAEnE;;;;;;;;;;;;GAYG;AACH,qIA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O,SAAS,CAAC;IACrB,CAAC;AACL,CAAC;AAED,oGAAoG;AACpG,oGAAoG;AACpG,kGAAkG;AAClG,UAAU;AACV,iHAAiH;AACjH,SAAS,OAAO,CAAC,KAAa;IAC1B,OAAO,sBAAS,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AACpC,CAAC;AAED,mKAAmK;AACnK,SAAS,aAAa,CAAC,OAAe,EAAE,QAAgB;IACpD,8DAA8D;IAC9D,IAAI,CAAC;QACD,MAAM,IAAI,GAAG,EAAE,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;QAClC,IAAI,IAAI,CAAC,IAAI,GAAG,aAAa,EAAE,CAAC;YAC5B,IAAI,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC;gBAAE,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;YACrD,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;QACrC,CAAC;IACL,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,KAAK,KAAK,CAAC;IACf,CAAC;AACL,CAAC","sourcesContent":["import { execSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nimport { dotWebpieces } from '@webpieces/tooling-common';\nimport { readMainSyncStatus, MainSyncStatus } from '@webpieces/repo-workflow-core';\nimport { RepoRootFinder, claudeEnv } from '@webpieces/rules-config';\nimport { L1_LOCATION_STREAM, L2_DECISIONS_STREAM, CALLS_STREAM } from './log-streams';\n\nimport { L0_FAULT_NONE, L0_ROW_ALLOWLISTED, L0_ROW_BLOCKED } from '@webpieces/rules-config';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { logStream } from './log-stream';\nimport { logTarget } from './log-target';\nimport { aiTypeContext } from './ai-type-context';\nimport { l2RowForReason } from './l2-rows';\nimport { cureForMatrix } from './matrix-cures';\n\n// The SYNC decision log — what the synchronous hook DID on each invocation and WHY. Its companion is\n// the ASYNC log (the `async-refresh/` stream, written by the detached refresher in main-sync-log.ts). This\n// one records EVERY guard decision — allow, block, config-bypass, and the fail-open cases — and CITES\n// the async-written cache snapshot (`cache` field) that drove the decision, so a wrong allow/block is\n// traceable to a stale or missing async write. Writes to `.webpieces/logs/L2-decisions/<writer>.log` —\n// the LAYER is the directory, the WRITER is the file (see log-streams.ts and LogStream).\nconst MAX_LOG_BYTES = 512 * 1024; // 512 KB — rotate when exceeded (mirrors rotation in rejection-log)\n\n/**\n * THE ACTION CODEBOOK, as a type. These are the five actions GUARD_MATRIX.md numbers 1-5, and they\n * are the vocabulary EVERY layer reports in — so one grep spans L-1, L0, L1 and L2.\n *\n * The three distinctions this exists to make, none of which `'ALLOW' | 'BLOCK'` could:\n *\n * ALLOW no objection — the call was HANDED DOWN to the next layer. A layer saying ALLOW\n * is NOT saying the call ran: the layer below it, or the OTHER parallel hook, may\n * still deny. This is L1's `ACT_DOWN`.\n * ALLOW_EXEMPT out of scope by construction — allowed, and evaluation STOPS here. L1's\n * `ACT_EXEMPT`.\n * ALLOW_FAIL_OPEN state could not be established, so nothing was judged. Keeping this distinct\n * from ALLOW is the entire point of the type: a fail-open allow and a real allow\n * that look identical make it impossible to tell whether the guards are protecting\n * anything or quietly abstaining. It used to be a `' (fail-open)'` SUBSTRING on the\n * reason field, which is exactly why the abstentions were never countable.\n * BLOCK_AI_CURE blocked, and the printed cure is a command the AI can run itself.\n * BLOCK_HUMAN blocked, and it needs a human decision — or a delegation (spawn a subagent) that\n * the blocked agent cannot perform for itself.\n *\n * Hard cut, per `.claude/rules/no-backwards-compat.md`: `'BLOCK'` is GONE rather than aliased, so every\n * construction site fails to\n * compile and has to say which kind of block it is. Before, that question had exactly one wrong\n * answer available — silence.\n */\nexport type Verdict = 'ALLOW' | 'ALLOW_EXEMPT' | 'ALLOW_FAIL_OPEN' | 'BLOCK_AI_CURE' | 'BLOCK_HUMAN';\n\n/**\n * WHICH ROW of WHICH layer's decision table produced this line. Data-only → a class, per CLAUDE.md.\n *\n * `row` is the row NUMBER from the layer's row array (`L1_ROWS[i].num`, `L2_ROWS[i].num`) — the\n * same number the generated doc prints, because the doc is rendered from that same array. So a log\n * line joins to its matrix row BY NUMBER, and checking observed behaviour against the documented use\n * cases becomes a lookup rather than an investigation.\n */\nexport class MatrixRef {\n constructor(readonly layer: string, readonly row: string) {}\n}\n\n/**\n * The layer tokens. EVERY layer now cites a row: L0 through its two decision-matrix rows, L1 through\n * L1_ROWS, and L2 through L2_ROWS (see `matrixL2Row`). This used to say `'-'` was for \"a layer with no\n * row array YET (L2 is the un-converted one)\" — L2 is converted, and a comment describing a state the\n * code left behind is exactly the kind of doc a reader trusts and should not.\n *\n * `'-'` survives for ONE case, and it is a real one: an L2 reason that no row claims. See matrixL2Row.\n *\n * These are REQUIRED at the constructor, not defaulted: a defaulted `MatrixRef` would make the\n * uncited case reachable by doing nothing and impossible to grep — the same defect this file's own\n * docblock argues against for `'BLOCK'`, where silence was the one wrong answer available.\n *\n * L0 NOW CITES ITS ROW TOO. It used to be `'-'` on the grounds that \"L0's faults are a table of letters\n * rather than numbered rows\" — but L0 has BOTH: the letter says WHICH fault, and the numbered decision\n * matrix (`renderGuardMatrixDoc`) says which of its three rows was taken. There is one ALLOW row and one\n * BLOCK row, so the pair `row=` + `fault=` pins the decision exactly, and the deny an agent reads now\n * carries the identical pair. That is the join: one grep spans the deny, the log line and the doc.\n * Two constants, not one `MATRIX_L0`, because the two call sites are a cure-bypass ALLOW and an L0\n * BLOCK — one token covering both is what made the row unciteable in the first place.\n */\nexport const MATRIX_L0_ALLOW = new MatrixRef('L0', L0_ROW_ALLOWLISTED);\nexport const MATRIX_L0_BLOCK = new MatrixRef('L0', L0_ROW_BLOCKED);\n\n/**\n * The L2 reference for one decision, with the row DERIVED FROM THE REASON.\n *\n * There is no `MATRIX_L2` constant any more, and its absence is the point: a single shared instance\n * meant every L2 line in the repo carried `row=-`, which reads as \"L2 has no rows\" rather than \"this\n * decision was not classified\". Deleting it makes every construction site name a reason, and the reason\n * is the only thing a call site has that identifies which row it is an instance of.\n *\n * `l2RowForReason` returns null for a reason no row claims, and that renders as `'-'` — visible in the\n * log, not silently absorbed into a default row. l2-matrix.spec.ts reads the four guard sources and\n * fails the build if any reason literal in them is unmapped, so `-` should never appear in practice;\n * when it does, it is a genuine hole in the table and the log says so.\n */\n// webpieces-disable no-function-outside-class -- a named constructor for MatrixRef beside it, in this module of module-scope writers\nexport function matrixL2Row(reason: string): MatrixRef {\n const row = l2RowForReason(reason);\n return new MatrixRef('L2', row === null ? '-' : String(row));\n}\n\n/**\n * The L2 stream, with NO row — for the two kinds of line that genuinely are not an instance of a row.\n *\n * 1. The runner's AGGREGATE bash lines (\"no bash-guard block\" / \"bash-guard block\"). They summarise\n * the whole guard set's answer for one command, not one row's verdict; the per-guard lines that\n * DO cite rows are written alongside them by the guards themselves.\n * 2. `whole-repo-build-guard`, which is not a branch-state policy at all — it is the experimental\n * home-config guard, has no webpieces.config.json entry, and shares this stream only because the\n * stream is \"bash decisions\", not \"L2 rows\".\n *\n * A NAMED constant rather than an inline `new MatrixRef('L2', '-')`, so `grep MATRIX_L2_UNROWED` lists\n * every uncited line and the list stays short and arguable. It is deliberately NOT called `MATRIX_L2`:\n * the old name was used by everything and made \"L2 has no rows\" indistinguishable from \"this line is\n * not a row\".\n */\nexport const MATRIX_L2_UNROWED = new MatrixRef('L2', '-');\n\n// Data-only record of one guard decision (per CLAUDE.md: classes for data, not object literals).\n// `cache` summarizes the async-written main-sync-status.json that drove a feature-branch-guard\n// decision (branch/merged/conflict/fork + the cache timestamp), or '-' when no cache was consulted\n// (bash guards, on-main, config-bypass).\nexport class GuardDecision {\n rule: string;\n tool: string;\n target: string; // file path (file guards) or the bash command (bash guards)\n branch: string;\n verdict: Verdict;\n reason: string;\n cache: string;\n /**\n * The L0 fault this decision IS, in the codebook's letter (core/l0-fault-codes.ts), or `-` for an\n * ordinary rule decision. The `sh` shim has always stamped `fault=` on its own stream; the three\n * JS-side faults (S/C/Y) reached this one with no label at all, so `grep fault=S` found nothing\n * even while an S storm was blocking every call.\n */\n fault: string;\n /** Which layer + row decided this. See MatrixRef — it is what joins a log line to the doc. */\n matrix: MatrixRef;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(rule: string, tool: string, target: string, branch: string, verdict: Verdict, reason: string, cache: string = '-', fault: string, matrix: MatrixRef) {\n this.rule = rule;\n this.tool = tool;\n this.target = target;\n this.branch = branch;\n this.verdict = verdict;\n this.reason = reason;\n this.cache = cache;\n this.fault = fault;\n this.matrix = matrix;\n }\n}\n\n/**\n * Append one tab-separated line per L2 decision to `.webpieces/logs/L2-decisions/<writer>.log`, where\n * <writer> is LogStream's `<sessionId>-<agentId|coordinator>-<hook>` key (a caller that never\n * identified renders as `unknown-coordinator-hook` — there is no un-keyed name).\n * `root` is\n * the repo/workspace root that holds `.webpieces` (callers pass workspaceRoot, or a\n * RepoRootFinder-resolved root at the pre-load config-bypass site — never a raw cwd, so a bypass\n * logged from a subdir never scatters a stray `.webpieces`). Swallows all errors — logging must never\n * block or fail a hook.\n */\n// webpieces-disable no-function-outside-class -- the module-scope writer this log has always been, beside branchForLog/oneLine/rotateLogFile; it must stay callable from a tree too broken to build a DI container\nexport function logGuardDecision(root: string, decision: GuardDecision): void {\n appendDecision(root, L2_DECISIONS_STREAM, decision);\n}\n\n/**\n * The L1 stream — `.webpieces/logs/L1-location/<writer>.log`.\n *\n * L1 had NO stream. Its three blocking paths wrote into L2's file under an implementation name\n * (`force-to-root`, `trinary-version-skew`, `cd-must-be-first`), and its NON-blocking outcomes —\n * the exempt row and the three hand-down rows — wrote nothing at all. So \"L1 had no objection\" was\n * unobservable, and \"show me every L1 decision\" had no answer: L1 existed in the trail only as the\n * `root=` / `projectDir=` / `tree=` columns stapled onto somebody else's line.\n *\n * A SIBLING rather than a `base` parameter on logGuardDecision, deliberately: that signature is what\n * the process-wide `logStream` singleton exists to keep unchanged (see LogStream's docblock), and\n * `INVOCATION_LOG_FILE` already establishes the pattern of a second stream owning its own name in\n * this same module.\n */\n// webpieces-disable no-function-outside-class -- sibling of logGuardDecision, same module-scope writer shape and same reason\nexport function logL1Decision(root: string, decision: GuardDecision): void {\n appendDecision(root, L1_LOCATION_STREAM, decision);\n}\n\n// The one appender both streams share. `streamDir` is the LAYER; the writer key inside it is\n// logStream's session/agent/hook, which is what keeps one writer per file.\n// webpieces-disable no-function-outside-class -- the shared body of the two module-scope writers above\nfunction appendDecision(root: string, streamDir: string, decision: GuardDecision): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const timestamp = new Date().toISOString();\n // LOCAL scope: a guard decision belongs to the tree it judged. WHO made the call is answered\n // by the filename, which logStream names with session/agent/hook.\n const logsDir = dotWebpieces.logsFile(root, streamDir);\n fs.mkdirSync(logsDir, { recursive: true });\n\n const logPath = path.join(logsDir, logStream.writerFile('.log'));\n rotateLogFile(logPath, path.join(logsDir, logStream.writerFile('.1.log')));\n\n const line = [\n `[${timestamp}]`,\n decision.verdict,\n decision.tool,\n oneLine(decision.target),\n decision.branch,\n decision.rule,\n oneLine(decision.reason),\n oneLine(decision.cache),\n // WHICH ROW of WHICH table decided this. The directory already carries the layer, but a\n // line quoted out of its file must still say what judged it — and `row=` is the join key\n // to the generated doc, which is the point of the whole exercise.\n `layer=${decision.matrix.layer}`,\n `row=${decision.matrix.row}`,\n // The tree this decision was actually made against, and what Claude Code told the hook the\n // project was. Appended (never reordered) for the same reason as on the invocation line —\n // see ClaudeEnv: when these two disagree, that disagreement is the bug.\n `root=${root}`,\n `projectDir=${claudeEnv.projectDirForLog()}`,\n // git's name for that tree — `primary`, else the worktree name. Same literal and same\n // derivation as the L0 shim log's `tree=` (shim-audit-log.ts), so one grep spans both\n // streams: L0 carries tree without projectDir, L1 now carries both.\n `tree=${dotWebpieces.worktreeName(root) || 'primary'}`,\n // APPEND-ONLY, same spelling as the invocation line and the L0 shim log: which L0 fault\n // this was, or `-`.\n `fault=${decision.fault}`,\n // WHAT THE AGENT WAS TOLD TO DO — looked up from the row above, never passed in, so it is\n // by construction the same literal the generated matrix prints for that row (see\n // matrix-cures.ts). `row=` says which row judged the call; this says what that row\n // prescribed, which is what makes the trail auditable against the doc without opening it.\n // APPEND-ONLY, like every field before it.\n `cure=${oneLine(cureForMatrix(decision.matrix.layer, decision.matrix.row))}`,\n // WHICH HARNESS made the call, spelled exactly as the L0 sh shim spells it on its own\n // stream — so ONE grep (`ai=codex`) spans all five streams and \"is Codex actually being\n // guarded?\" is a question the trail can answer. APPEND-ONLY, like every field before it; a\n // row from a release that predates this carries no `ai=` and reads as `unknown`.\n `ai=${aiTypeContext.forLog()}`,\n ].join('\\t') + '\\n';\n fs.appendFileSync(logPath, line);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n}\n\n/**\n * What the guard SAW on one invocation, captured up front and held until the outcome is known.\n * Data-only (per CLAUDE.md: classes for data, explicit construction).\n */\nexport class GuardInvocation {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n public readonly root: string,\n public readonly timestamp: string,\n public readonly tool: string,\n public readonly target: string,\n public readonly branch: string,\n public readonly sync: string,\n public readonly projectDir: string,\n ) {}\n}\n\n/**\n * The per-INVOCATION stream — `.webpieces/logs/calls/<writer>.log` (see LogStream for the writer\n * key), one line for EVERY guards-hook\n * call (allow or block, bash or file), unlike `L2-decisions/` which records only the calls a\n * rule actually judged. It captures the tool, the command/file, the live git branch, the async-written\n * main-sync-status.json snapshot (branch / merged / fork-point / conflict), and — since this class\n * replaced a bare log-and-forget function — HOW THE CALL ENDED.\n *\n * WHY IT IS TWO CALLS. The line used to be written the moment the hook started, so it could not carry\n * a verdict: the decision had not been made yet. Answering \"what happened to this call?\" therefore\n * meant joining this file against the L2 decision stream BY TIMESTAMP, which is exactly the kind of\n * reconstruction a log exists to make unnecessary. So {@link begin} now only CAPTURES (including the\n * git/cache reads, which must still happen while the hook is running), and {@link finish} — called\n * from the hook's single terminal boundary, emitAllow/emitDeny — writes the whole line once the\n * outcome is known. The two streams stay distinct in purpose: this one is \"every call and how it\n * ended\", the decision log remains \"every judgement and why\".\n *\n * Every error is swallowed: logging must never block or fail a hook.\n */\nexport class InvocationLog {\n private pending: GuardInvocation | null = null;\n\n /**\n * Capture the context of one invocation. `cwd` is the AI's working dir; the repo root that owns\n * `.webpieces` is resolved from it. Writes NOTHING — {@link finish} does that.\n */\n begin(cwd: string, tool: string, target: string): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const root = new RepoRootFinder().resolveRepoRoot(cwd);\n const branch = branchForLog(root);\n // The cache is branch-keyed, so the entry to log is the one for the branch we are standing\n // on. 'unknown' (branchForLog's failure value) simply misses and logs 'sync=none'.\n const sync = summarizeSyncStatus(readMainSyncStatus(root, branch));\n this.pending = new GuardInvocation(root, new Date().toISOString(), tool, oneLine(target), branch, sync, claudeEnv.projectDirForLog());\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n }\n\n /**\n * Write the captured line, now stamped with the outcome. A no-op when nothing was captured (the\n * 'rules' hook, or a terminal boundary reached before begin()), and it clears the pending entry so\n * a second emit cannot double-log.\n *\n * `rule` is the rule that blocked, or '-' when there is none; `fault` is the L0 fault code when this\n * call ended on one (S/C/Y — the JS-side faults), else '-'. FIELD ORDER IS APPEND-ONLY: the five\n * original fields keep their positions (cleanup automation mines this file), and `guards=` /\n * `rule=` / … / `fault=` are added at the end.\n */\n finish(verdict: Verdict, rule: string, fault: string = L0_FAULT_NONE): void {\n const invocation = this.pending;\n this.pending = null;\n if (invocation === null) return;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const logsDir = dotWebpieces.logsFile(invocation.root, CALLS_STREAM);\n fs.mkdirSync(logsDir, { recursive: true });\n const logPath = path.join(logsDir, logStream.writerFile('.log'));\n rotateLogFile(logPath, path.join(logsDir, logStream.writerFile('.1.log')));\n\n const line = [\n `[${invocation.timestamp}]`,\n invocation.tool,\n invocation.target,\n `branch=${invocation.branch}`,\n invocation.sync,\n // `guards=`, NOT `verdict=`. This hook can only report on ITSELF. Claude Code runs all\n // its PreToolUse hooks IN PARALLEL, so another hook process may deny a call this one\n // had no objection to, and neither can see the other's answer. Measured under the\n // RETIRED three-hook form: `cd <repo>/packages && ls` was DENIED by L-1 and recorded\n // here three times as `verdict=ALLOW`. The old field name promised an outcome it\n // structurally cannot know, so the name stayed even though L-1 is gone: the two\n // surviving hooks still run in parallel and still cannot see each other.\n `guards=${verdict}`,\n `rule=${oneLine(rule) || '-'}`,\n // The tree the guard ACTED in, next to what Claude Code said the project was. Both, on\n // every line, because the diagnostic value is entirely in comparing them — see\n // ClaudeEnv for the open question this field exists to settle empirically.\n `root=${invocation.root}`,\n `projectDir=${invocation.projectDir}`,\n // See logGuardDecision: the short tree label, so `tree=primary` with a matching\n // projectDir reads as healthy at a glance and `tree=<worktree>` beside a projectDir\n // pointing at the primary is the straddle, without diffing two absolute paths.\n `tree=${dotWebpieces.worktreeName(invocation.root) || 'primary'}`,\n // WHICH L0 fault ended this call, in the same letters and the same field name the L0 sh\n // shim uses (the `L0-shim/` stream) — so ONE grep spans the whole trail.\n `fault=${fault}`,\n // WHICH HARNESS made the call — same field name and same vocabulary as the L0 sh shim's\n // `ai=` and the decision stream's, so one grep spans the whole trail. APPEND-ONLY.\n `ai=${aiTypeContext.forLog()}`,\n ].join('\\t') + '\\n';\n fs.appendFileSync(logPath, line);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n }\n}\n\n// Process-wide instance: one hook process handles exactly one tool call, so a single pending entry is\n// the whole state there is. Module-scope (rather than DI) because the terminal boundary that flushes\n// it — emitAllow/emitDeny — is itself module-scope protocol code with no container in reach.\nexport const invocationLog = new InvocationLog();\n\n// One-field summary of main-sync-status.json for the invocation log: the branch the cache is FOR,\n// whether it is already merged (and its PR), fork-point presence, and conflict state — the signals a\n// cleanup step keys off. 'sync=none' when the cache has not been written yet (first call of a session).\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nfunction summarizeSyncStatus(status: MainSyncStatus | null): string {\n if (status === null) return 'sync=none';\n const merged = status.branchAlreadyMerged ? `PR#${status.mergedPr !== '' ? status.mergedPr : '?'}` : 'no';\n return `sync=${status.branch} merged=${merged} fork=${String(status.hasForkPoint)} conflict=${String(status.conflict)} ts=${status.timestamp}`;\n}\n\n// Best-effort current branch for the log line. Returns 'unknown' on any failure (e.g. not a git\n// repo) — this is for display only, never for a control decision.\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nexport function branchForLog(root: string): string {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return execSync('git rev-parse --abbrev-ref HEAD', {\n cwd: root,\n encoding: 'utf8',\n stdio: ['pipe', 'pipe', 'pipe'],\n }).trim() || 'unknown';\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return 'unknown';\n }\n}\n\n// Collapse newlines/tabs and cap length so one decision is always one log line. The collapse itself\n// lives in LogTarget, because SessionCallHistory READS this format back and the two must agree byte\n// for byte — a second private copy of the cap is a silent way for a long command to stop matching\n// itself.\n// webpieces-disable no-function-outside-class -- the module's own leaf helper, beside branchForLog/rotateLogFile\nfunction oneLine(value: string): string {\n return logTarget.oneLine(value);\n}\n\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nfunction 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 error;\n }\n}\n"]}
1
+ {"version":3,"file":"decision-log.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/core/decision-log.ts"],"names":[],"mappings":";;;AAqGA,kCAGC;AAkED,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C,UAAU,CAAC,QAAQ,CAAC;gBAAE,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;YACrD,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;QACrC,CAAC;IACL,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,KAAK,KAAK,CAAC;IACf,CAAC;AACL,CAAC","sourcesContent":["import { execSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nimport { dotWebpieces } from '@webpieces/tooling-common';\nimport { readMainSyncStatus, MainSyncStatus } from '@webpieces/repo-workflow-core';\nimport { RepoRootFinder, claudeEnv } from '@webpieces/rules-config';\nimport { L1_LOCATION_STREAM, L2_DECISIONS_STREAM, CALLS_STREAM } from './log-streams';\n\nimport { L0_FAULT_NONE, L0_ROW_ALLOWLISTED, L0_ROW_BLOCKED } from '@webpieces/rules-config';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { logStream } from './log-stream';\nimport { logTarget } from './log-target';\nimport { aiTypeContext } from './ai-type-context';\nimport { l2RowForReason } from './l2-rows';\nimport { cureForMatrix } from './matrix-cures';\n\n// The SYNC decision log — what the synchronous hook DID on each invocation and WHY. Its companion is\n// the ASYNC log (the `async-refresh/` stream, written by the detached refresher in main-sync-log.ts). This\n// one records EVERY guard decision — allow, block, config-bypass, and the fail-open cases — and CITES\n// the async-written cache snapshot (`cache` field) that drove the decision, so a wrong allow/block is\n// traceable to a stale or missing async write. Writes to `.webpieces-logs/logs/L2-decisions/<writer>.log` —\n// the LAYER is the directory, the WRITER is the file (see log-streams.ts and LogStream).\nconst MAX_LOG_BYTES = 512 * 1024; // 512 KB — rotate when exceeded (mirrors rotation in rejection-log)\n\n/**\n * THE ACTION CODEBOOK, as a type. These are the five actions GUARD_MATRIX.md numbers 1-5, and they\n * are the vocabulary EVERY layer reports in — so one grep spans L-1, L0, L1 and L2.\n *\n * The three distinctions this exists to make, none of which `'ALLOW' | 'BLOCK'` could:\n *\n * ALLOW no objection — the call was HANDED DOWN to the next layer. A layer saying ALLOW\n * is NOT saying the call ran: the layer below it, or the OTHER parallel hook, may\n * still deny. This is L1's `ACT_DOWN`.\n * ALLOW_EXEMPT out of scope by construction — allowed, and evaluation STOPS here. L1's\n * `ACT_EXEMPT`.\n * ALLOW_FAIL_OPEN state could not be established, so nothing was judged. Keeping this distinct\n * from ALLOW is the entire point of the type: a fail-open allow and a real allow\n * that look identical make it impossible to tell whether the guards are protecting\n * anything or quietly abstaining. It used to be a `' (fail-open)'` SUBSTRING on the\n * reason field, which is exactly why the abstentions were never countable.\n * BLOCK_AI_CURE blocked, and the printed cure is a command the AI can run itself.\n * BLOCK_HUMAN blocked, and it needs a human decision — or a delegation (spawn a subagent) that\n * the blocked agent cannot perform for itself.\n *\n * Hard cut, per `.claude/rules/no-backwards-compat.md`: `'BLOCK'` is GONE rather than aliased, so every\n * construction site fails to\n * compile and has to say which kind of block it is. Before, that question had exactly one wrong\n * answer available — silence.\n */\nexport type Verdict = 'ALLOW' | 'ALLOW_EXEMPT' | 'ALLOW_FAIL_OPEN' | 'BLOCK_AI_CURE' | 'BLOCK_HUMAN';\n\n/**\n * WHICH ROW of WHICH layer's decision table produced this line. Data-only → a class, per CLAUDE.md.\n *\n * `row` is the row NUMBER from the layer's row array (`L1_ROWS[i].num`, `L2_ROWS[i].num`) — the\n * same number the generated doc prints, because the doc is rendered from that same array. So a log\n * line joins to its matrix row BY NUMBER, and checking observed behaviour against the documented use\n * cases becomes a lookup rather than an investigation.\n */\nexport class MatrixRef {\n constructor(readonly layer: string, readonly row: string) {}\n}\n\n/**\n * The layer tokens. EVERY layer now cites a row: L0 through its two decision-matrix rows, L1 through\n * L1_ROWS, and L2 through L2_ROWS (see `matrixL2Row`). This used to say `'-'` was for \"a layer with no\n * row array YET (L2 is the un-converted one)\" — L2 is converted, and a comment describing a state the\n * code left behind is exactly the kind of doc a reader trusts and should not.\n *\n * `'-'` survives for ONE case, and it is a real one: an L2 reason that no row claims. See matrixL2Row.\n *\n * These are REQUIRED at the constructor, not defaulted: a defaulted `MatrixRef` would make the\n * uncited case reachable by doing nothing and impossible to grep — the same defect this file's own\n * docblock argues against for `'BLOCK'`, where silence was the one wrong answer available.\n *\n * L0 NOW CITES ITS ROW TOO. It used to be `'-'` on the grounds that \"L0's faults are a table of letters\n * rather than numbered rows\" — but L0 has BOTH: the letter says WHICH fault, and the numbered decision\n * matrix (`renderGuardMatrixDoc`) says which of its three rows was taken. There is one ALLOW row and one\n * BLOCK row, so the pair `row=` + `fault=` pins the decision exactly, and the deny an agent reads now\n * carries the identical pair. That is the join: one grep spans the deny, the log line and the doc.\n * Two constants, not one `MATRIX_L0`, because the two call sites are a cure-bypass ALLOW and an L0\n * BLOCK — one token covering both is what made the row unciteable in the first place.\n */\nexport const MATRIX_L0_ALLOW = new MatrixRef('L0', L0_ROW_ALLOWLISTED);\nexport const MATRIX_L0_BLOCK = new MatrixRef('L0', L0_ROW_BLOCKED);\n\n/**\n * The L2 reference for one decision, with the row DERIVED FROM THE REASON.\n *\n * There is no `MATRIX_L2` constant any more, and its absence is the point: a single shared instance\n * meant every L2 line in the repo carried `row=-`, which reads as \"L2 has no rows\" rather than \"this\n * decision was not classified\". Deleting it makes every construction site name a reason, and the reason\n * is the only thing a call site has that identifies which row it is an instance of.\n *\n * `l2RowForReason` returns null for a reason no row claims, and that renders as `'-'` — visible in the\n * log, not silently absorbed into a default row. l2-matrix.spec.ts reads the four guard sources and\n * fails the build if any reason literal in them is unmapped, so `-` should never appear in practice;\n * when it does, it is a genuine hole in the table and the log says so.\n */\n// webpieces-disable no-function-outside-class -- a named constructor for MatrixRef beside it, in this module of module-scope writers\nexport function matrixL2Row(reason: string): MatrixRef {\n const row = l2RowForReason(reason);\n return new MatrixRef('L2', row === null ? '-' : String(row));\n}\n\n/**\n * The L2 stream, with NO row — for the two kinds of line that genuinely are not an instance of a row.\n *\n * 1. The runner's AGGREGATE bash lines (\"no bash-guard block\" / \"bash-guard block\"). They summarise\n * the whole guard set's answer for one command, not one row's verdict; the per-guard lines that\n * DO cite rows are written alongside them by the guards themselves.\n * 2. `whole-repo-build-guard`, which is not a branch-state policy at all — it is the experimental\n * home-config guard, has no webpieces.config.json entry, and shares this stream only because the\n * stream is \"bash decisions\", not \"L2 rows\".\n *\n * A NAMED constant rather than an inline `new MatrixRef('L2', '-')`, so `grep MATRIX_L2_UNROWED` lists\n * every uncited line and the list stays short and arguable. It is deliberately NOT called `MATRIX_L2`:\n * the old name was used by everything and made \"L2 has no rows\" indistinguishable from \"this line is\n * not a row\".\n */\nexport const MATRIX_L2_UNROWED = new MatrixRef('L2', '-');\n\n// Data-only record of one guard decision (per CLAUDE.md: classes for data, not object literals).\n// `cache` summarizes the async-written main-sync-status.json that drove a feature-branch-guard\n// decision (branch/merged/conflict/fork + the cache timestamp), or '-' when no cache was consulted\n// (bash guards, on-main, config-bypass).\nexport class GuardDecision {\n rule: string;\n tool: string;\n target: string; // file path (file guards) or the bash command (bash guards)\n branch: string;\n verdict: Verdict;\n reason: string;\n cache: string;\n /**\n * The L0 fault this decision IS, in the codebook's letter (core/l0-fault-codes.ts), or `-` for an\n * ordinary rule decision. The `sh` shim has always stamped `fault=` on its own stream; the three\n * JS-side faults (S/C/Y) reached this one with no label at all, so `grep fault=S` found nothing\n * even while an S storm was blocking every call.\n */\n fault: string;\n /** Which layer + row decided this. See MatrixRef — it is what joins a log line to the doc. */\n matrix: MatrixRef;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(rule: string, tool: string, target: string, branch: string, verdict: Verdict, reason: string, cache: string = '-', fault: string, matrix: MatrixRef) {\n this.rule = rule;\n this.tool = tool;\n this.target = target;\n this.branch = branch;\n this.verdict = verdict;\n this.reason = reason;\n this.cache = cache;\n this.fault = fault;\n this.matrix = matrix;\n }\n}\n\n/**\n * Append one tab-separated line per L2 decision to `.webpieces-logs/logs/L2-decisions/<writer>.log`, where\n * <writer> is LogStream's `<sessionId>-<agentId|coordinator>-<hook>` key (a caller that never\n * identified renders as `unknown-coordinator-hook` — there is no un-keyed name).\n * `root` is\n * the repo/workspace root that holds `.webpieces-logs` (callers pass workspaceRoot, or a\n * RepoRootFinder-resolved root at the pre-load config-bypass site — never a raw cwd, so a bypass\n * logged from a subdir never scatters a stray `.webpieces-logs`). Swallows all errors — logging must never\n * block or fail a hook.\n */\n// webpieces-disable no-function-outside-class -- the module-scope writer this log has always been, beside branchForLog/oneLine/rotateLogFile; it must stay callable from a tree too broken to build a DI container\nexport function logGuardDecision(root: string, decision: GuardDecision): void {\n appendDecision(root, L2_DECISIONS_STREAM, decision);\n}\n\n/**\n * The L1 stream — `.webpieces-logs/logs/L1-location/<writer>.log`.\n *\n * L1 had NO stream. Its three blocking paths wrote into L2's file under an implementation name\n * (`force-to-root`, `trinary-version-skew`, `cd-must-be-first`), and its NON-blocking outcomes —\n * the exempt row and the three hand-down rows — wrote nothing at all. So \"L1 had no objection\" was\n * unobservable, and \"show me every L1 decision\" had no answer: L1 existed in the trail only as the\n * `root=` / `projectDir=` / `tree=` columns stapled onto somebody else's line.\n *\n * A SIBLING rather than a `base` parameter on logGuardDecision, deliberately: that signature is what\n * the process-wide `logStream` singleton exists to keep unchanged (see LogStream's docblock), and\n * `INVOCATION_LOG_FILE` already establishes the pattern of a second stream owning its own name in\n * this same module.\n */\n// webpieces-disable no-function-outside-class -- sibling of logGuardDecision, same module-scope writer shape and same reason\nexport function logL1Decision(root: string, decision: GuardDecision): void {\n appendDecision(root, L1_LOCATION_STREAM, decision);\n}\n\n// The one appender both streams share. `streamDir` is the LAYER; the writer key inside it is\n// logStream's session/agent/hook, which is what keeps one writer per file.\n// webpieces-disable no-function-outside-class -- the shared body of the two module-scope writers above\nfunction appendDecision(root: string, streamDir: string, decision: GuardDecision): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const timestamp = new Date().toISOString();\n // LOCAL scope: a guard decision belongs to the tree it judged. WHO made the call is answered\n // by the filename, which logStream names with session/agent/hook.\n const logsDir = dotWebpieces.logsFile(root, streamDir);\n fs.mkdirSync(logsDir, { recursive: true });\n\n const logPath = path.join(logsDir, logStream.writerFile('.log'));\n rotateLogFile(logPath, path.join(logsDir, logStream.writerFile('.1.log')));\n\n const line = [\n `[${timestamp}]`,\n decision.verdict,\n decision.tool,\n oneLine(decision.target),\n decision.branch,\n decision.rule,\n oneLine(decision.reason),\n oneLine(decision.cache),\n // WHICH ROW of WHICH table decided this. The directory already carries the layer, but a\n // line quoted out of its file must still say what judged it — and `row=` is the join key\n // to the generated doc, which is the point of the whole exercise.\n `layer=${decision.matrix.layer}`,\n `row=${decision.matrix.row}`,\n // The tree this decision was actually made against, and what Claude Code told the hook the\n // project was. Appended (never reordered) for the same reason as on the invocation line —\n // see ClaudeEnv: when these two disagree, that disagreement is the bug.\n `root=${root}`,\n `projectDir=${claudeEnv.projectDirForLog()}`,\n // git's name for that tree — `primary`, else the worktree name. Same literal and same\n // derivation as the L0 shim log's `tree=` (shim-audit-log.ts), so one grep spans both\n // streams: L0 carries tree without projectDir, L1 now carries both.\n `tree=${dotWebpieces.worktreeName(root) || 'primary'}`,\n // APPEND-ONLY, same spelling as the invocation line and the L0 shim log: which L0 fault\n // this was, or `-`.\n `fault=${decision.fault}`,\n // WHAT THE AGENT WAS TOLD TO DO — looked up from the row above, never passed in, so it is\n // by construction the same literal the generated matrix prints for that row (see\n // matrix-cures.ts). `row=` says which row judged the call; this says what that row\n // prescribed, which is what makes the trail auditable against the doc without opening it.\n // APPEND-ONLY, like every field before it.\n `cure=${oneLine(cureForMatrix(decision.matrix.layer, decision.matrix.row))}`,\n // WHICH HARNESS made the call, spelled exactly as the L0 sh shim spells it on its own\n // stream — so ONE grep (`ai=codex`) spans all five streams and \"is Codex actually being\n // guarded?\" is a question the trail can answer. APPEND-ONLY, like every field before it; a\n // row from a release that predates this carries no `ai=` and reads as `unknown`.\n `ai=${aiTypeContext.forLog()}`,\n ].join('\\t') + '\\n';\n fs.appendFileSync(logPath, line);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n}\n\n/**\n * What the guard SAW on one invocation, captured up front and held until the outcome is known.\n * Data-only (per CLAUDE.md: classes for data, explicit construction).\n */\nexport class GuardInvocation {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n public readonly root: string,\n public readonly timestamp: string,\n public readonly tool: string,\n public readonly target: string,\n public readonly branch: string,\n public readonly sync: string,\n public readonly projectDir: string,\n ) {}\n}\n\n/**\n * The per-INVOCATION stream — `.webpieces-logs/logs/calls/<writer>.log` (see LogStream for the writer\n * key), one line for EVERY guards-hook\n * call (allow or block, bash or file), unlike `L2-decisions/` which records only the calls a\n * rule actually judged. It captures the tool, the command/file, the live git branch, the async-written\n * main-sync-status.json snapshot (branch / merged / fork-point / conflict), and — since this class\n * replaced a bare log-and-forget function — HOW THE CALL ENDED.\n *\n * WHY IT IS TWO CALLS. The line used to be written the moment the hook started, so it could not carry\n * a verdict: the decision had not been made yet. Answering \"what happened to this call?\" therefore\n * meant joining this file against the L2 decision stream BY TIMESTAMP, which is exactly the kind of\n * reconstruction a log exists to make unnecessary. So {@link begin} now only CAPTURES (including the\n * git/cache reads, which must still happen while the hook is running), and {@link finish} — called\n * from the hook's single terminal boundary, emitAllow/emitDeny — writes the whole line once the\n * outcome is known. The two streams stay distinct in purpose: this one is \"every call and how it\n * ended\", the decision log remains \"every judgement and why\".\n *\n * Every error is swallowed: logging must never block or fail a hook.\n */\nexport class InvocationLog {\n private pending: GuardInvocation | null = null;\n\n /**\n * Capture the context of one invocation. `cwd` is the AI's working dir; the repo root that owns\n * `.webpieces-logs` is resolved from it. Writes NOTHING — {@link finish} does that.\n */\n begin(cwd: string, tool: string, target: string): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const root = new RepoRootFinder().resolveRepoRoot(cwd);\n const branch = branchForLog(root);\n // The cache is branch-keyed, so the entry to log is the one for the branch we are standing\n // on. 'unknown' (branchForLog's failure value) simply misses and logs 'sync=none'.\n const sync = summarizeSyncStatus(readMainSyncStatus(root, branch));\n this.pending = new GuardInvocation(root, new Date().toISOString(), tool, oneLine(target), branch, sync, claudeEnv.projectDirForLog());\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n }\n\n /**\n * Write the captured line, now stamped with the outcome. A no-op when nothing was captured (the\n * 'rules' hook, or a terminal boundary reached before begin()), and it clears the pending entry so\n * a second emit cannot double-log.\n *\n * `rule` is the rule that blocked, or '-' when there is none; `fault` is the L0 fault code when this\n * call ended on one (S/C/Y — the JS-side faults), else '-'. FIELD ORDER IS APPEND-ONLY: the five\n * original fields keep their positions (cleanup automation mines this file), and `guards=` /\n * `rule=` / … / `fault=` are added at the end.\n */\n finish(verdict: Verdict, rule: string, fault: string = L0_FAULT_NONE): void {\n const invocation = this.pending;\n this.pending = null;\n if (invocation === null) return;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const logsDir = dotWebpieces.logsFile(invocation.root, CALLS_STREAM);\n fs.mkdirSync(logsDir, { recursive: true });\n const logPath = path.join(logsDir, logStream.writerFile('.log'));\n rotateLogFile(logPath, path.join(logsDir, logStream.writerFile('.1.log')));\n\n const line = [\n `[${invocation.timestamp}]`,\n invocation.tool,\n invocation.target,\n `branch=${invocation.branch}`,\n invocation.sync,\n // `guards=`, NOT `verdict=`. This hook can only report on ITSELF. Claude Code runs all\n // its PreToolUse hooks IN PARALLEL, so another hook process may deny a call this one\n // had no objection to, and neither can see the other's answer. Measured under the\n // RETIRED three-hook form: `cd <repo>/packages && ls` was DENIED by L-1 and recorded\n // here three times as `verdict=ALLOW`. The old field name promised an outcome it\n // structurally cannot know, so the name stayed even though L-1 is gone: the two\n // surviving hooks still run in parallel and still cannot see each other.\n `guards=${verdict}`,\n `rule=${oneLine(rule) || '-'}`,\n // The tree the guard ACTED in, next to what Claude Code said the project was. Both, on\n // every line, because the diagnostic value is entirely in comparing them — see\n // ClaudeEnv for the open question this field exists to settle empirically.\n `root=${invocation.root}`,\n `projectDir=${invocation.projectDir}`,\n // See logGuardDecision: the short tree label, so `tree=primary` with a matching\n // projectDir reads as healthy at a glance and `tree=<worktree>` beside a projectDir\n // pointing at the primary is the straddle, without diffing two absolute paths.\n `tree=${dotWebpieces.worktreeName(invocation.root) || 'primary'}`,\n // WHICH L0 fault ended this call, in the same letters and the same field name the L0 sh\n // shim uses (the `L0-shim/` stream) — so ONE grep spans the whole trail.\n `fault=${fault}`,\n // WHICH HARNESS made the call — same field name and same vocabulary as the L0 sh shim's\n // `ai=` and the decision stream's, so one grep spans the whole trail. APPEND-ONLY.\n `ai=${aiTypeContext.forLog()}`,\n ].join('\\t') + '\\n';\n fs.appendFileSync(logPath, line);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n }\n}\n\n// Process-wide instance: one hook process handles exactly one tool call, so a single pending entry is\n// the whole state there is. Module-scope (rather than DI) because the terminal boundary that flushes\n// it — emitAllow/emitDeny — is itself module-scope protocol code with no container in reach.\nexport const invocationLog = new InvocationLog();\n\n// One-field summary of main-sync-status.json for the invocation log: the branch the cache is FOR,\n// whether it is already merged (and its PR), fork-point presence, and conflict state — the signals a\n// cleanup step keys off. 'sync=none' when the cache has not been written yet (first call of a session).\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nfunction summarizeSyncStatus(status: MainSyncStatus | null): string {\n if (status === null) return 'sync=none';\n const merged = status.branchAlreadyMerged ? `PR#${status.mergedPr !== '' ? status.mergedPr : '?'}` : 'no';\n return `sync=${status.branch} merged=${merged} fork=${String(status.hasForkPoint)} conflict=${String(status.conflict)} ts=${status.timestamp}`;\n}\n\n// Best-effort current branch for the log line. Returns 'unknown' on any failure (e.g. not a git\n// repo) — this is for display only, never for a control decision.\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nexport function branchForLog(root: string): string {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return execSync('git rev-parse --abbrev-ref HEAD', {\n cwd: root,\n encoding: 'utf8',\n stdio: ['pipe', 'pipe', 'pipe'],\n }).trim() || 'unknown';\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return 'unknown';\n }\n}\n\n// Collapse newlines/tabs and cap length so one decision is always one log line. The collapse itself\n// lives in LogTarget, because SessionCallHistory READS this format back and the two must agree byte\n// for byte — a second private copy of the cap is a silent way for a long command to stop matching\n// itself.\n// webpieces-disable no-function-outside-class -- the module's own leaf helper, beside branchForLog/rotateLogFile\nfunction oneLine(value: string): string {\n return logTarget.oneLine(value);\n}\n\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nfunction 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 error;\n }\n}\n"]}
@@ -25,7 +25,7 @@ export declare class ExcludedPathReference {
25
25
  * Finds the paths a BASH command names that the top-level `excludePaths` already exempts.
26
26
  *
27
27
  * WHY this exists: the bash guards judge the shell's effective CWD, not the paths in the command, so
28
- * `cat .webpieces/tasks.md` at the repo root is DENIED even though that exact file is exempt from
28
+ * `cat .webpieces-logs/tasks.md` at the repo root is DENIED even though that exact file is exempt from
29
29
  * every guard and was reachable, that instant, through Read/Write. Every remedy the deny body printed
30
30
  * was a git state change — strictly more destructive than the one it omitted. This class supplies the
31
31
  * missing sentence; it changes no verdict.
@@ -42,7 +42,7 @@ export declare class ExcludedPathEscapeScan {
42
42
  * `effectiveCwd` is the directory the command really runs in, after its own leading `cd` — the
43
43
  * same base ContentReadScan resolves relative operands against. RELATIVE tokens are resolved
44
44
  * there and ABSOLUTE ones normalised straight to workspace-relative, which is how
45
- * `cat /abs/path/to/repo/.webpieces/tasks.md` reaches the same verdict as `cat .webpieces/tasks.md`.
45
+ * `cat /abs/path/to/repo/.webpieces-logs/tasks.md` reaches the same verdict as `cat .webpieces-logs/tasks.md`.
46
46
  */
47
47
  constructor(scanner: CommandScanner, workspaceRoot: string, effectiveCwd: string);
48
48
  /**
@@ -58,8 +58,8 @@ export declare class ExcludedPathEscapeScan {
58
58
  * A directory the agent may `cd` into and have the guards actually stand down, or null.
59
59
  *
60
60
  * THE TRAP: the bash path matches the relative cwd with `globMatches`, which compiles
61
- * `.webpieces/**` to the anchored `/^\.webpieces\/.*$/` — the `/` is a LITERAL, so the bare
62
- * directory `.webpieces` does NOT match its own glob. `cd .webpieces && cat tasks.md` is still
61
+ * `.webpieces-logs/**` to the anchored `/^\.webpieces-logs\/.*$/` — the `/` is a LITERAL, so the bare
62
+ * directory `.webpieces-logs` does NOT match its own glob. `cd .webpieces-logs && cat tasks.md` is still
63
63
  * denied. Emitting that would be worse than emitting nothing: it looks authoritative and costs a
64
64
  * turn to disprove. So the directory is only offered when it passes the very same matcher the
65
65
  * runner will use, and the renderer says so plainly when nothing does.
@@ -36,7 +36,7 @@ exports.ExcludedPathReference = ExcludedPathReference;
36
36
  * Finds the paths a BASH command names that the top-level `excludePaths` already exempts.
37
37
  *
38
38
  * WHY this exists: the bash guards judge the shell's effective CWD, not the paths in the command, so
39
- * `cat .webpieces/tasks.md` at the repo root is DENIED even though that exact file is exempt from
39
+ * `cat .webpieces-logs/tasks.md` at the repo root is DENIED even though that exact file is exempt from
40
40
  * every guard and was reachable, that instant, through Read/Write. Every remedy the deny body printed
41
41
  * was a git state change — strictly more destructive than the one it omitted. This class supplies the
42
42
  * missing sentence; it changes no verdict.
@@ -53,7 +53,7 @@ class ExcludedPathEscapeScan {
53
53
  * `effectiveCwd` is the directory the command really runs in, after its own leading `cd` — the
54
54
  * same base ContentReadScan resolves relative operands against. RELATIVE tokens are resolved
55
55
  * there and ABSOLUTE ones normalised straight to workspace-relative, which is how
56
- * `cat /abs/path/to/repo/.webpieces/tasks.md` reaches the same verdict as `cat .webpieces/tasks.md`.
56
+ * `cat /abs/path/to/repo/.webpieces-logs/tasks.md` reaches the same verdict as `cat .webpieces-logs/tasks.md`.
57
57
  */
58
58
  constructor(scanner, workspaceRoot, effectiveCwd) {
59
59
  this.scanner = scanner;
@@ -93,8 +93,8 @@ class ExcludedPathEscapeScan {
93
93
  * A directory the agent may `cd` into and have the guards actually stand down, or null.
94
94
  *
95
95
  * THE TRAP: the bash path matches the relative cwd with `globMatches`, which compiles
96
- * `.webpieces/**` to the anchored `/^\.webpieces\/.*$/` — the `/` is a LITERAL, so the bare
97
- * directory `.webpieces` does NOT match its own glob. `cd .webpieces && cat tasks.md` is still
96
+ * `.webpieces-logs/**` to the anchored `/^\.webpieces-logs\/.*$/` — the `/` is a LITERAL, so the bare
97
+ * directory `.webpieces-logs` does NOT match its own glob. `cd .webpieces-logs && cat tasks.md` is still
98
98
  * denied. Emitting that would be worse than emitting nothing: it looks authoritative and costs a
99
99
  * turn to disprove. So the directory is only offered when it passes the very same matcher the
100
100
  * runner will use, and the renderer says so plainly when nothing does.
@@ -180,7 +180,7 @@ class ExcludedPathEscapeHint {
180
180
  lines.push(` ${glob}`);
181
181
  lines.push(` Your command referenced: ${references.map((r) => r.referencedPath).join(', ')}`);
182
182
  // Scoped to the FILE, deliberately. The stanza fires on any rule block whose command names an
183
- // exempt path, and `git push … && cat .webpieces/tasks.md` is blocked for the push — for which
183
+ // exempt path, and `git push … && cat .webpieces-logs/tasks.md` is blocked for the push — for which
184
184
  // Read/Write substitutes for nothing. Claiming the remedies below were optional would be false.
185
185
  lines.push(' Read/Write/Edit reaches that file RIGHT NOW, with no git operation at all.');
186
186
  lines.push(' Anything ELSE this command does — a git/gh operation, a build — still needs the');
@@ -1 +1 @@
1
- {"version":3,"file":"excluded-path-escape.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/core/excluded-path-escape.ts"],"names":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,MAAM,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,cAAc,CAAC,CAAC;QAC/C,OAAO;YACH,wDAAwD;YACxD,QAAQ,GAAG,6DAA6D,KAAK,CAAC,WAAW,gBAAgB;YACzG,2FAA2F;YAC3F,gGAAgG;YAChG,wFAAwF;YACxF,oEAAoE,GAAG,OAAO,KAAK,CAAC,WAAW,IAAI;SACtG,CAAC;IACN,CAAC;CACJ;AAxED,wDAwEC","sourcesContent":["import * as path from 'path';\n\nimport { ExcludePaths } from '@webpieces/rules-config';\n\nimport { CommandScanner } from '@webpieces/hook-runtime';\nimport { globMatches } from '@webpieces/hook-runtime';\n\n/**\n * One path the denied command NAMED that `excludePaths` already exempts, plus how to reach it.\n *\n * Data-only, so a class (per CLAUDE.md).\n *\n * `cdDirectory` is the whole point of the class rather than a bare string: it is a directory that\n * ITSELF satisfies `globMatches` against one of the configured globs, or null when no such directory\n * exists for this reference. Callers must never invent one — see ExcludedPathEscapeScan for why a\n * naive `dirname` is wrong exactly when it looks most obviously right.\n */\nexport class ExcludedPathReference {\n /** The referenced path, workspace-relative, as it was matched. */\n readonly referencedPath: string;\n /** The `excludePaths` glob that matched it — quoted back so the agent need not re-derive it. */\n readonly matchedGlob: string;\n /** A directory a `cd` may legally land in (matches a glob on its own), or null when none does. */\n readonly cdDirectory: string | null;\n /** `referencedPath` re-expressed relative to `cdDirectory`; '' when there is no `cdDirectory`. */\n readonly pathFromCdDirectory: string;\n\n constructor(\n referencedPath: string,\n matchedGlob: string,\n cdDirectory: string | null,\n pathFromCdDirectory: string,\n ) {\n this.referencedPath = referencedPath;\n this.matchedGlob = matchedGlob;\n this.cdDirectory = cdDirectory;\n this.pathFromCdDirectory = pathFromCdDirectory;\n }\n}\n\n/**\n * Finds the paths a BASH command names that the top-level `excludePaths` already exempts.\n *\n * WHY this exists: the bash guards judge the shell's effective CWD, not the paths in the command, so\n * `cat .webpieces/tasks.md` at the repo root is DENIED even though that exact file is exempt from\n * every guard and was reachable, that instant, through Read/Write. Every remedy the deny body printed\n * was a git state change — strictly more destructive than the one it omitted. This class supplies the\n * missing sentence; it changes no verdict.\n *\n * A token is treated as a candidate path with no filesystem check: whether it exists says nothing\n * about whether it is exempt, and a stat per token on the blocking hook path is exactly the cost these\n * guards avoid. Non-path tokens (a `grep` pattern, a `sed` script) simply match no glob.\n */\nexport class ExcludedPathEscapeScan {\n private readonly scanner: CommandScanner;\n private readonly workspaceRoot: string;\n private readonly effectiveCwd: string;\n\n /**\n * `effectiveCwd` is the directory the command really runs in, after its own leading `cd` — the\n * same base ContentReadScan resolves relative operands against. RELATIVE tokens are resolved\n * there and ABSOLUTE ones normalised straight to workspace-relative, which is how\n * `cat /abs/path/to/repo/.webpieces/tasks.md` reaches the same verdict as `cat .webpieces/tasks.md`.\n */\n constructor(scanner: CommandScanner, workspaceRoot: string, effectiveCwd: string) {\n this.scanner = scanner;\n this.workspaceRoot = workspaceRoot;\n this.effectiveCwd = effectiveCwd;\n }\n\n /**\n * Every excluded path this command references, in command order, de-duplicated.\n *\n * Scans EVERY segment, not just a leading `cd`: `cat x`, `grep -n foo x`, `sed -n '1,5p' x` and a\n * path inside an `&&` compound all count, because the agent's next move depends on the file it\n * wanted, wherever in the line it named it.\n */\n references(command: string, ex: ExcludePaths): readonly ExcludedPathReference[] {\n if (ex.paths.length === 0) return [];\n\n const found: ExcludedPathReference[] = [];\n const seen = new Set<string>();\n for (const token of this.candidateTokens(command)) {\n const relative = this.workspaceRelative(token);\n if (relative === null || seen.has(relative)) continue;\n seen.add(relative);\n const glob = this.matchingGlob(relative, ex);\n if (glob === null) continue;\n found.push(this.reference(relative, glob, ex));\n }\n return found;\n }\n\n // Build the reference, including the `cd` target — the ONE subtle part, see cdDirectory below.\n private reference(relative: string, glob: string, ex: ExcludePaths): ExcludedPathReference {\n const dir = this.cdDirectory(relative, ex);\n return new ExcludedPathReference(\n relative, glob, dir, dir === null ? '' : path.relative(dir, relative),\n );\n }\n\n /**\n * A directory the agent may `cd` into and have the guards actually stand down, or null.\n *\n * THE TRAP: the bash path matches the relative cwd with `globMatches`, which compiles\n * `.webpieces/**` to the anchored `/^\\.webpieces\\/.*$/` — the `/` is a LITERAL, so the bare\n * directory `.webpieces` does NOT match its own glob. `cd .webpieces && cat tasks.md` is still\n * denied. Emitting that would be worse than emitting nothing: it looks authoritative and costs a\n * turn to disprove. So the directory is only offered when it passes the very same matcher the\n * runner will use, and the renderer says so plainly when nothing does.\n */\n private cdDirectory(relative: string, ex: ExcludePaths): string | null {\n const dir = path.dirname(relative);\n if (dir === '.' || dir === '' || dir === relative) return null;\n return this.matchingGlob(dir, ex) === null ? null : dir;\n }\n\n // The first configured glob this workspace-relative path satisfies, under the runner's OWN matcher\n // (globMatches, load-rules.ts) — never a looser one, or the stanza would promise an exemption the\n // guards do not grant.\n private matchingGlob(relative: string, ex: ExcludePaths): string | null {\n for (const pattern of ex.paths) {\n if (globMatches(pattern, relative)) return pattern;\n }\n return null;\n }\n\n /**\n * Workspace-relative form of a token, or null when it is not a path inside this workspace.\n *\n * `~`-rooted and out-of-tree paths are nothing to do with this repo's exclusions, and the\n * workspace root itself ('') matches no glob by construction.\n */\n private workspaceRelative(token: string): string | null {\n const cleaned = token.replace(REDIRECT_PREFIX, '');\n if (cleaned === '' || cleaned.startsWith('~')) return null;\n const absolute = path.isAbsolute(cleaned) ? cleaned : path.resolve(this.effectiveCwd, cleaned);\n const relative = path.relative(this.workspaceRoot, absolute);\n if (relative === '' || relative.startsWith('..')) return null;\n return relative;\n }\n\n /**\n * Every token that could name a file: each segment's words minus the command word itself and\n * minus flags. Deliberately generous — a token that is not a path matches no glob, while a token\n * dropped by a cleverer filter is a file the agent is never told it can read.\n */\n private candidateTokens(command: string): readonly string[] {\n const tokens: string[] = [];\n for (const segment of this.scanner.commandSegments(command)) {\n const words = this.scanner.words(segment);\n for (let i = 1; i < words.length; i++) {\n if (words[i].startsWith('-')) continue;\n tokens.push(words[i]);\n }\n }\n return tokens;\n }\n}\n\n// A redirection glued to its target (`>out.log`, `2>>err.log`, `<in.txt`) — strip the operator so the\n// target is scanned as the path it is.\nconst REDIRECT_PREFIX = /^\\d*(?:>>?|<)/;\n\n/**\n * Renders the leading stanza of a bash deny body: the Read/Write escape the agent already has, and —\n * when one genuinely exists — the `cd` that makes bash itself work.\n *\n * It goes at the TOP of the report, above the git remedies, because the agent acts on the first\n * actionable thing it reads. The live incident this fixes had the agent create a branch in a human's\n * working tree to record a row in a gitignored scratch file; the cheap, side-effect-free path was one\n * sentence away and never printed. Returns '' when the command names no excluded path, so a repo\n * without exemptions — and every command that names nothing exempt — sees no extra noise.\n */\nexport class ExcludedPathEscapeHint {\n private readonly scan: ExcludedPathEscapeScan;\n\n /** `effectiveCwd` is the directory the command really runs in — see ExcludedPathEscapeScan. */\n constructor(workspaceRoot: string, effectiveCwd: string) {\n this.scan = new ExcludedPathEscapeScan(new CommandScanner(), workspaceRoot, effectiveCwd);\n }\n\n render(command: string, ex: ExcludePaths): string {\n const references = this.scan.references(command, ex);\n if (references.length === 0) return '';\n\n const lines: string[] = [];\n lines.push('✅ YOU CAN USE THE READ/WRITE TOOLS RIGHT NOW — no git operation needed.');\n lines.push(' These paths are in excludePaths and are exempt from every guard:');\n for (const glob of ex.paths) lines.push(` ${glob}`);\n lines.push(` Your command referenced: ${references.map((r: ExcludedPathReference): string => r.referencedPath).join(', ')}`);\n // Scoped to the FILE, deliberately. The stanza fires on any rule block whose command names an\n // exempt path, and `git push … && cat .webpieces/tasks.md` is blocked for the push — for which\n // Read/Write substitutes for nothing. Claiming the remedies below were optional would be false.\n lines.push(' Read/Write/Edit reaches that file RIGHT NOW, with no git operation at all.');\n lines.push(' Anything ELSE this command does — a git/gh operation, a build — still needs the');\n lines.push(' remedies below.');\n const bash = this.bashLines(references);\n if (bash.length > 0) {\n lines.push('');\n for (const line of bash) lines.push(line);\n }\n lines.push('');\n return lines.join('\\n');\n }\n\n // The bash half: the `cd` when one matches, the honest refusal to invent one when none does, and\n // silence when there is not even a directory worth naming.\n private bashLines(references: readonly ExcludedPathReference[]): readonly string[] {\n const withCd = references.find((r: ExcludedPathReference): boolean => r.cdDirectory !== null);\n if (withCd !== undefined) return this.cdLines(withCd);\n // A workspace-ROOT-level file — matched by a file-shaped glob like `*.md` — has no directory to\n // name: `dirname` is `.`, which no excludePaths glob can usefully exempt (the relative cwd at\n // the root is '', so `.` would never match) and which reads as \"exempt the whole repo\". Say\n // nothing about bash rather than something false.\n const nested = references.find(\n (r: ExcludedPathReference): boolean => path.dirname(r.referencedPath) !== '.',\n );\n return nested === undefined ? [] : this.noCdLines(nested);\n }\n\n // A `cd` the guards will actually honour: its directory passed globMatches in the scan.\n private cdLines(withCd: ExcludedPathReference): readonly string[] {\n return [\n '✅ OR KEEP USING BASH — put a `cd` into the excluded tree FIRST:',\n ` cd ${String(withCd.cdDirectory)} && <your command, writing \\`${withCd.referencedPath}\\` as \\`${withCd.pathFromCdDirectory}\\`>`,\n ' The guard resolves a LEADING `cd` and judges that directory, so this runs.',\n ' It must be the first thing in the command: no leading VAR= assignment,',\n ' no subshell wrapper — those defeat the resolution.',\n ];\n }\n\n // No directory on the way to the file matches a glob on its own, so there is no `cd` to offer.\n // Say WHY and give the one-line config edit that would create one, rather than printing a `cd`\n // that would be denied.\n private noCdLines(first: ExcludedPathReference): readonly string[] {\n const dir = path.dirname(first.referencedPath);\n return [\n '⚠️ A `cd` CANNOT rescue bash here, so do not try one.',\n ` \\`${dir}\\` (the directory itself) matches no excludePaths glob: \\`${first.matchedGlob}\\` compiles to`,\n ' an anchored regex whose `/` is literal, so the bare directory fails it and a `cd` into',\n ' it is STILL denied. That form is deliberately not printed here — it looks right and is not.',\n ' Use Read/Write/Edit above — or, to make bash work here too, list the bare directory',\n ` alongside the glob in webpieces.config.json → excludePaths: [\"${dir}\", \"${first.matchedGlob}\"]`,\n ];\n }\n}\n"]}
1
+ {"version":3,"file":"excluded-path-escape.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-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,SAAS,CAAC,KAA4B;QAC1C,MAAM,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,cAAc,CAAC,CAAC;QAC/C,OAAO;YACH,wDAAwD;YACxD,QAAQ,GAAG,6DAA6D,KAAK,CAAC,WAAW,gBAAgB;YACzG,2FAA2F;YAC3F,gGAAgG;YAChG,wFAAwF;YACxF,oEAAoE,GAAG,OAAO,KAAK,CAAC,WAAW,IAAI;SACtG,CAAC;IACN,CAAC;CACJ;AAxED,wDAwEC","sourcesContent":["import * as path from 'path';\n\nimport { ExcludePaths } from '@webpieces/rules-config';\n\nimport { CommandScanner } from '@webpieces/hook-runtime';\nimport { globMatches } from '@webpieces/hook-runtime';\n\n/**\n * One path the denied command NAMED that `excludePaths` already exempts, plus how to reach it.\n *\n * Data-only, so a class (per CLAUDE.md).\n *\n * `cdDirectory` is the whole point of the class rather than a bare string: it is a directory that\n * ITSELF satisfies `globMatches` against one of the configured globs, or null when no such directory\n * exists for this reference. Callers must never invent one — see ExcludedPathEscapeScan for why a\n * naive `dirname` is wrong exactly when it looks most obviously right.\n */\nexport class ExcludedPathReference {\n /** The referenced path, workspace-relative, as it was matched. */\n readonly referencedPath: string;\n /** The `excludePaths` glob that matched it — quoted back so the agent need not re-derive it. */\n readonly matchedGlob: string;\n /** A directory a `cd` may legally land in (matches a glob on its own), or null when none does. */\n readonly cdDirectory: string | null;\n /** `referencedPath` re-expressed relative to `cdDirectory`; '' when there is no `cdDirectory`. */\n readonly pathFromCdDirectory: string;\n\n constructor(\n referencedPath: string,\n matchedGlob: string,\n cdDirectory: string | null,\n pathFromCdDirectory: string,\n ) {\n this.referencedPath = referencedPath;\n this.matchedGlob = matchedGlob;\n this.cdDirectory = cdDirectory;\n this.pathFromCdDirectory = pathFromCdDirectory;\n }\n}\n\n/**\n * Finds the paths a BASH command names that the top-level `excludePaths` already exempts.\n *\n * WHY this exists: the bash guards judge the shell's effective CWD, not the paths in the command, so\n * `cat .webpieces-logs/tasks.md` at the repo root is DENIED even though that exact file is exempt from\n * every guard and was reachable, that instant, through Read/Write. Every remedy the deny body printed\n * was a git state change — strictly more destructive than the one it omitted. This class supplies the\n * missing sentence; it changes no verdict.\n *\n * A token is treated as a candidate path with no filesystem check: whether it exists says nothing\n * about whether it is exempt, and a stat per token on the blocking hook path is exactly the cost these\n * guards avoid. Non-path tokens (a `grep` pattern, a `sed` script) simply match no glob.\n */\nexport class ExcludedPathEscapeScan {\n private readonly scanner: CommandScanner;\n private readonly workspaceRoot: string;\n private readonly effectiveCwd: string;\n\n /**\n * `effectiveCwd` is the directory the command really runs in, after its own leading `cd` — the\n * same base ContentReadScan resolves relative operands against. RELATIVE tokens are resolved\n * there and ABSOLUTE ones normalised straight to workspace-relative, which is how\n * `cat /abs/path/to/repo/.webpieces-logs/tasks.md` reaches the same verdict as `cat .webpieces-logs/tasks.md`.\n */\n constructor(scanner: CommandScanner, workspaceRoot: string, effectiveCwd: string) {\n this.scanner = scanner;\n this.workspaceRoot = workspaceRoot;\n this.effectiveCwd = effectiveCwd;\n }\n\n /**\n * Every excluded path this command references, in command order, de-duplicated.\n *\n * Scans EVERY segment, not just a leading `cd`: `cat x`, `grep -n foo x`, `sed -n '1,5p' x` and a\n * path inside an `&&` compound all count, because the agent's next move depends on the file it\n * wanted, wherever in the line it named it.\n */\n references(command: string, ex: ExcludePaths): readonly ExcludedPathReference[] {\n if (ex.paths.length === 0) return [];\n\n const found: ExcludedPathReference[] = [];\n const seen = new Set<string>();\n for (const token of this.candidateTokens(command)) {\n const relative = this.workspaceRelative(token);\n if (relative === null || seen.has(relative)) continue;\n seen.add(relative);\n const glob = this.matchingGlob(relative, ex);\n if (glob === null) continue;\n found.push(this.reference(relative, glob, ex));\n }\n return found;\n }\n\n // Build the reference, including the `cd` target — the ONE subtle part, see cdDirectory below.\n private reference(relative: string, glob: string, ex: ExcludePaths): ExcludedPathReference {\n const dir = this.cdDirectory(relative, ex);\n return new ExcludedPathReference(\n relative, glob, dir, dir === null ? '' : path.relative(dir, relative),\n );\n }\n\n /**\n * A directory the agent may `cd` into and have the guards actually stand down, or null.\n *\n * THE TRAP: the bash path matches the relative cwd with `globMatches`, which compiles\n * `.webpieces-logs/**` to the anchored `/^\\.webpieces-logs\\/.*$/` — the `/` is a LITERAL, so the bare\n * directory `.webpieces-logs` does NOT match its own glob. `cd .webpieces-logs && cat tasks.md` is still\n * denied. Emitting that would be worse than emitting nothing: it looks authoritative and costs a\n * turn to disprove. So the directory is only offered when it passes the very same matcher the\n * runner will use, and the renderer says so plainly when nothing does.\n */\n private cdDirectory(relative: string, ex: ExcludePaths): string | null {\n const dir = path.dirname(relative);\n if (dir === '.' || dir === '' || dir === relative) return null;\n return this.matchingGlob(dir, ex) === null ? null : dir;\n }\n\n // The first configured glob this workspace-relative path satisfies, under the runner's OWN matcher\n // (globMatches, load-rules.ts) — never a looser one, or the stanza would promise an exemption the\n // guards do not grant.\n private matchingGlob(relative: string, ex: ExcludePaths): string | null {\n for (const pattern of ex.paths) {\n if (globMatches(pattern, relative)) return pattern;\n }\n return null;\n }\n\n /**\n * Workspace-relative form of a token, or null when it is not a path inside this workspace.\n *\n * `~`-rooted and out-of-tree paths are nothing to do with this repo's exclusions, and the\n * workspace root itself ('') matches no glob by construction.\n */\n private workspaceRelative(token: string): string | null {\n const cleaned = token.replace(REDIRECT_PREFIX, '');\n if (cleaned === '' || cleaned.startsWith('~')) return null;\n const absolute = path.isAbsolute(cleaned) ? cleaned : path.resolve(this.effectiveCwd, cleaned);\n const relative = path.relative(this.workspaceRoot, absolute);\n if (relative === '' || relative.startsWith('..')) return null;\n return relative;\n }\n\n /**\n * Every token that could name a file: each segment's words minus the command word itself and\n * minus flags. Deliberately generous — a token that is not a path matches no glob, while a token\n * dropped by a cleverer filter is a file the agent is never told it can read.\n */\n private candidateTokens(command: string): readonly string[] {\n const tokens: string[] = [];\n for (const segment of this.scanner.commandSegments(command)) {\n const words = this.scanner.words(segment);\n for (let i = 1; i < words.length; i++) {\n if (words[i].startsWith('-')) continue;\n tokens.push(words[i]);\n }\n }\n return tokens;\n }\n}\n\n// A redirection glued to its target (`>out.log`, `2>>err.log`, `<in.txt`) — strip the operator so the\n// target is scanned as the path it is.\nconst REDIRECT_PREFIX = /^\\d*(?:>>?|<)/;\n\n/**\n * Renders the leading stanza of a bash deny body: the Read/Write escape the agent already has, and —\n * when one genuinely exists — the `cd` that makes bash itself work.\n *\n * It goes at the TOP of the report, above the git remedies, because the agent acts on the first\n * actionable thing it reads. The live incident this fixes had the agent create a branch in a human's\n * working tree to record a row in a gitignored scratch file; the cheap, side-effect-free path was one\n * sentence away and never printed. Returns '' when the command names no excluded path, so a repo\n * without exemptions — and every command that names nothing exempt — sees no extra noise.\n */\nexport class ExcludedPathEscapeHint {\n private readonly scan: ExcludedPathEscapeScan;\n\n /** `effectiveCwd` is the directory the command really runs in — see ExcludedPathEscapeScan. */\n constructor(workspaceRoot: string, effectiveCwd: string) {\n this.scan = new ExcludedPathEscapeScan(new CommandScanner(), workspaceRoot, effectiveCwd);\n }\n\n render(command: string, ex: ExcludePaths): string {\n const references = this.scan.references(command, ex);\n if (references.length === 0) return '';\n\n const lines: string[] = [];\n lines.push('✅ YOU CAN USE THE READ/WRITE TOOLS RIGHT NOW — no git operation needed.');\n lines.push(' These paths are in excludePaths and are exempt from every guard:');\n for (const glob of ex.paths) lines.push(` ${glob}`);\n lines.push(` Your command referenced: ${references.map((r: ExcludedPathReference): string => r.referencedPath).join(', ')}`);\n // Scoped to the FILE, deliberately. The stanza fires on any rule block whose command names an\n // exempt path, and `git push … && cat .webpieces-logs/tasks.md` is blocked for the push — for which\n // Read/Write substitutes for nothing. Claiming the remedies below were optional would be false.\n lines.push(' Read/Write/Edit reaches that file RIGHT NOW, with no git operation at all.');\n lines.push(' Anything ELSE this command does — a git/gh operation, a build — still needs the');\n lines.push(' remedies below.');\n const bash = this.bashLines(references);\n if (bash.length > 0) {\n lines.push('');\n for (const line of bash) lines.push(line);\n }\n lines.push('');\n return lines.join('\\n');\n }\n\n // The bash half: the `cd` when one matches, the honest refusal to invent one when none does, and\n // silence when there is not even a directory worth naming.\n private bashLines(references: readonly ExcludedPathReference[]): readonly string[] {\n const withCd = references.find((r: ExcludedPathReference): boolean => r.cdDirectory !== null);\n if (withCd !== undefined) return this.cdLines(withCd);\n // A workspace-ROOT-level file — matched by a file-shaped glob like `*.md` — has no directory to\n // name: `dirname` is `.`, which no excludePaths glob can usefully exempt (the relative cwd at\n // the root is '', so `.` would never match) and which reads as \"exempt the whole repo\". Say\n // nothing about bash rather than something false.\n const nested = references.find(\n (r: ExcludedPathReference): boolean => path.dirname(r.referencedPath) !== '.',\n );\n return nested === undefined ? [] : this.noCdLines(nested);\n }\n\n // A `cd` the guards will actually honour: its directory passed globMatches in the scan.\n private cdLines(withCd: ExcludedPathReference): readonly string[] {\n return [\n '✅ OR KEEP USING BASH — put a `cd` into the excluded tree FIRST:',\n ` cd ${String(withCd.cdDirectory)} && <your command, writing \\`${withCd.referencedPath}\\` as \\`${withCd.pathFromCdDirectory}\\`>`,\n ' The guard resolves a LEADING `cd` and judges that directory, so this runs.',\n ' It must be the first thing in the command: no leading VAR= assignment,',\n ' no subshell wrapper — those defeat the resolution.',\n ];\n }\n\n // No directory on the way to the file matches a glob on its own, so there is no `cd` to offer.\n // Say WHY and give the one-line config edit that would create one, rather than printing a `cd`\n // that would be denied.\n private noCdLines(first: ExcludedPathReference): readonly string[] {\n const dir = path.dirname(first.referencedPath);\n return [\n '⚠️ A `cd` CANNOT rescue bash here, so do not try one.',\n ` \\`${dir}\\` (the directory itself) matches no excludePaths glob: \\`${first.matchedGlob}\\` compiles to`,\n ' an anchored regex whose `/` is literal, so the bare directory fails it and a `cd` into',\n ' it is STILL denied. That form is deliberately not printed here — it looks right and is not.',\n ' Use Read/Write/Edit above — or, to make bash work here too, list the bare directory',\n ` alongside the glob in webpieces.config.json → excludePaths: [\"${dir}\", \"${first.matchedGlob}\"]`,\n ];\n }\n}\n"]}