@webpieces/ai-hook-rules 0.4.835 → 0.4.837

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/package.json +3 -2
  2. package/src/adapters/agent-adapters.d.ts +1 -1
  3. package/src/adapters/agent-adapters.js.map +1 -1
  4. package/src/adapters/agent-response.d.ts +2 -3
  5. package/src/adapters/agent-response.js +8 -54
  6. package/src/adapters/agent-response.js.map +1 -1
  7. package/src/adapters/claude-code-adapter.d.ts +1 -1
  8. package/src/adapters/claude-code-adapter.js +6 -6
  9. package/src/adapters/claude-code-adapter.js.map +1 -1
  10. package/src/adapters/codex-adapter.d.ts +1 -1
  11. package/src/adapters/codex-adapter.js +3 -3
  12. package/src/adapters/codex-adapter.js.map +1 -1
  13. package/src/adapters/codex-subagent-guard.d.ts +1 -1
  14. package/src/adapters/codex-subagent-guard.js.map +1 -1
  15. package/src/adapters/detect-ai.d.ts +1 -1
  16. package/src/adapters/detect-ai.js.map +1 -1
  17. package/src/adapters/guards-hook.js +6 -5
  18. package/src/adapters/guards-hook.js.map +1 -1
  19. package/src/adapters/hook-core.d.ts +2 -2
  20. package/src/adapters/hook-core.js +2 -2
  21. package/src/adapters/hook-core.js.map +1 -1
  22. package/src/adapters/hook-pipeline-evaluator.d.ts +5 -0
  23. package/src/adapters/hook-pipeline-evaluator.js +18 -0
  24. package/src/adapters/hook-pipeline-evaluator.js.map +1 -0
  25. package/src/adapters/review-identity-stamper.d.ts +1 -1
  26. package/src/adapters/review-identity-stamper.js.map +1 -1
  27. package/src/adapters/rules-hook.js +6 -5
  28. package/src/adapters/rules-hook.js.map +1 -1
  29. package/src/bin/hook-registration.d.ts +1 -1
  30. package/src/bin/hook-registration.js.map +1 -1
  31. package/src/bin/l0-decide.d.ts +1 -1
  32. package/src/bin/l0-decide.js.map +1 -1
  33. package/src/bin/l0-entry.d.ts +1 -1
  34. package/src/bin/l0-entry.js.map +1 -1
  35. package/src/bin/shim-audit-log.js +2 -2
  36. package/src/bin/shim-audit-log.js.map +1 -1
  37. package/src/core/ai-type-context.d.ts +1 -1
  38. package/src/core/ai-type-context.js +2 -2
  39. package/src/core/ai-type-context.js.map +1 -1
  40. package/src/core/apply-patch-parse.d.ts +1 -1
  41. package/src/core/apply-patch-parse.js +4 -4
  42. package/src/core/apply-patch-parse.js.map +1 -1
  43. package/src/core/runner.d.ts +1 -1
  44. package/src/core/runner.js.map +1 -1
  45. package/src/core/types.d.ts +2 -16
  46. package/src/core/types.js +5 -26
  47. package/src/core/types.js.map +1 -1
  48. package/src/core/version-sync.d.ts +1 -1
  49. package/src/core/version-sync.js.map +1 -1
  50. package/src/index.d.ts +1 -2
  51. package/src/index.js +1 -12
  52. package/src/index.js.map +1 -1
  53. package/src/adapters/hook-app.d.ts +0 -61
  54. package/src/adapters/hook-app.js +0 -110
  55. package/src/adapters/hook-app.js.map +0 -1
  56. package/src/adapters/hook-outcome.d.ts +0 -46
  57. package/src/adapters/hook-outcome.js +0 -60
  58. package/src/adapters/hook-outcome.js.map +0 -1
  59. package/src/adapters/hook-ports.d.ts +0 -57
  60. package/src/adapters/hook-ports.js +0 -90
  61. package/src/adapters/hook-ports.js.map +0 -1
  62. package/src/core/agent-event.d.ts +0 -81
  63. package/src/core/agent-event.js +0 -75
  64. package/src/core/agent-event.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"l0-entry.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/bin/l0-entry.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;GAUG;;;AAIH;;;;;;;;;GASG;AACU,QAAA,aAAa,GAAG,eAAe,CAAC;AAY7C,uGAAuG;AACvG,MAAa,MAAM;IAEF;IACA;IACA;IAHb,YACa,QAAgB,EAChB,OAAe,EACf,QAAgB;QAFhB,aAAQ,GAAR,QAAQ,CAAQ;QAChB,YAAO,GAAP,OAAO,CAAQ;QACf,aAAQ,GAAR,QAAQ,CAAQ;IAC1B,CAAC;CACP;AAND,wBAMC;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAa,YAAY;IAGR;IACA;IAOA;IACA;IACA;IAYA;IACA;IACA;IA1Bb,yDAAyD;IACzD,YACa,KAAa,EACb,IAAsB;IAC/B;;;;;OAKG;IACM,IAAa,EACb,GAAkB,EAClB,EAAiB;IAC1B;;;;;;;;;;OAUG;IACM,OAAkB,EAClB,MAAc,EACd,eAAkC,EAAE;QAxBpC,UAAK,GAAL,KAAK,CAAQ;QACb,SAAI,GAAJ,IAAI,CAAkB;QAOtB,SAAI,GAAJ,IAAI,CAAS;QACb,QAAG,GAAH,GAAG,CAAe;QAClB,OAAE,GAAF,EAAE,CAAe;QAYjB,YAAO,GAAP,OAAO,CAAW;QAClB,WAAM,GAAN,MAAM,CAAQ;QACd,iBAAY,GAAZ,YAAY,CAAwB;IAC9C,CAAC;IAEJ,kFAAkF;IAClF,UAAU;QACN,OAAO,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAC,YAAY,CAAC,CAAC;IAC/C,CAAC;CACJ;AAlCD,oCAkCC","sourcesContent":["/**\n * THE L0 ENTRY TYPES — the shape of one allowlist entry, split out of ./l0-allowlist.\n *\n * Same reason `./l0-codex-read` and `./l0-ignored-tools` are their own modules: the LIST is long and\n * every entry carries a paragraph of reasoning, so the types that describe an entry get crowded out\n * by the entries themselves. Nothing here knows what is on the list; `./l0-allowlist` owns that and\n * imports these, so the dependency runs one way and there is no cycle.\n *\n * NOT re-exported from here onward — `./shim` is the ONE name that gathers L0, and it stars this\n * module alongside the others.\n */\n\nimport { AiType } from '../core/agent-event';\n\n/**\n * The token an L0 entry uses to say it serves EVERY harness — SAID OUT LOUD.\n *\n * This used to be `null`, and `null` is shim shape #5 from `.claude/rules/no-backwards-compat.md`: a widening expressed as an\n * ABSENCE. It made the widest setting the shortest thing to type and, worse, impossible to grep —\n * there is no search that lists \"the entries every harness gets\", because they were identified by\n * a field that was not there. `grep -n EVERY_HARNESS` now lists every one of them.\n *\n * It is a REAL VALUE in exactly the sense `AI_TYPE_UNKNOWN` is: countable, greppable, and typed.\n */\nexport const EVERY_HARNESS = 'every-harness';\n\n/**\n * Who one L0 entry is FOR: exactly one harness, or — named, never implied — all of them.\n *\n * Deliberately NOT `readonly AiType[]`. A list re-opens the hole this closed from the other side:\n * `[]` would be a second way to write \"nobody\", and `['claude-code', 'codex']` a second way to write\n * EVERY_HARNESS — two spellings of one decision, which is shim shape #1. Dean's rule is the whole\n * type: we only support codex or claudecode or FAIL.\n */\nexport type L0Harness = AiType | typeof EVERY_HARNESS;\n\n/** One tool call as L0 judges it: the tool name, the Bash command (or ''), the file target (or ''). */\nexport class L0Call {\n constructor(\n readonly toolName: string,\n readonly command: string,\n readonly filePath: string,\n ) {}\n}\n\n/**\n * One entry of THE L0 allowlist. Data-only → a class, per CLAUDE.md.\n *\n * `ere`/`js` are the twin regex BODIES for a Bash entry, or null for a tool-shaped entry (Read, the\n * webpieces.config.json target) that no regex can express. `sample` is a call this entry must accept —\n * it is what the matrix-coverage and cure-reachability tests drive isAllowed() with.\n *\n * `extraSamples` pins ADDITIONAL spellings the same entry must accept. A spelling that some deny\n * message prescribes belongs here, or nothing stops a later tightening of the pattern from making that\n * message's cure untypable again — which is the deadlock shape this whole module exists to prevent.\n *\n * `cure` is the ONE thing that is not uniform across the list, and it is not about L0 at all — see\n * L0_CURE_ALLOW_JS below. Every entry is judged identically while an L0 fault is up; `cure` decides\n * only whether the entry ALSO bypasses the downstream (L1) guards on a HEALTHY tree.\n */\nexport class L0AllowEntry {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n readonly label: string,\n readonly kind: 'pass' | 'allow',\n /**\n * True when this entry REPAIRS the tooling (install, sync, shim restore). A cure has to run\n * before webpieces.config.json can even be loaded, so it bypasses everything, always. A\n * non-cure (read-only orientation) is allowed while a fault is up and is otherwise an ordinary\n * command the downstream guards still judge.\n */\n readonly cure: boolean,\n readonly ere: string | null,\n readonly js: string | null,\n /**\n * The ONE harness this entry exists for, or `EVERY_HARNESS` for the entries every harness gets.\n * There is no default and no absence: an entry must say which it is, or it does not compile.\n *\n * A gated entry is unreachable from any other harness — it is spliced into its own union, which\n * both halves of L0 consult only after answering \"which harness sent this call?\". It exists\n * because the two harnesses do not have the same TOOLS: `Read` is entry 1 for Claude Code and\n * Codex has no such tool, so read parity at L0 can only be expressed per harness. Anything added\n * here later must satisfy the property stated on AI_TYPE_SH: the sh half's answer is an\n * approximation, so a gated entry may never grant more than the OTHER harness already has.\n */\n readonly harness: L0Harness,\n readonly sample: L0Call,\n readonly extraSamples: readonly L0Call[] = [],\n ) {}\n\n /** Every call this entry pins: the canonical sample plus every extra spelling. */\n allSamples(): readonly L0Call[] {\n return [this.sample, ...this.extraSamples];\n }\n}\n\n\n"]}
1
+ {"version":3,"file":"l0-entry.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/bin/l0-entry.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;GAUG;;;AAIH;;;;;;;;;GASG;AACU,QAAA,aAAa,GAAG,eAAe,CAAC;AAY7C,uGAAuG;AACvG,MAAa,MAAM;IAEF;IACA;IACA;IAHb,YACa,QAAgB,EAChB,OAAe,EACf,QAAgB;QAFhB,aAAQ,GAAR,QAAQ,CAAQ;QAChB,YAAO,GAAP,OAAO,CAAQ;QACf,aAAQ,GAAR,QAAQ,CAAQ;IAC1B,CAAC;CACP;AAND,wBAMC;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAa,YAAY;IAGR;IACA;IAOA;IACA;IACA;IAYA;IACA;IACA;IA1Bb,yDAAyD;IACzD,YACa,KAAa,EACb,IAAsB;IAC/B;;;;;OAKG;IACM,IAAa,EACb,GAAkB,EAClB,EAAiB;IAC1B;;;;;;;;;;OAUG;IACM,OAAkB,EAClB,MAAc,EACd,eAAkC,EAAE;QAxBpC,UAAK,GAAL,KAAK,CAAQ;QACb,SAAI,GAAJ,IAAI,CAAkB;QAOtB,SAAI,GAAJ,IAAI,CAAS;QACb,QAAG,GAAH,GAAG,CAAe;QAClB,OAAE,GAAF,EAAE,CAAe;QAYjB,YAAO,GAAP,OAAO,CAAW;QAClB,WAAM,GAAN,MAAM,CAAQ;QACd,iBAAY,GAAZ,YAAY,CAAwB;IAC9C,CAAC;IAEJ,kFAAkF;IAClF,UAAU;QACN,OAAO,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAC,YAAY,CAAC,CAAC;IAC/C,CAAC;CACJ;AAlCD,oCAkCC","sourcesContent":["/**\n * THE L0 ENTRY TYPES — the shape of one allowlist entry, split out of ./l0-allowlist.\n *\n * Same reason `./l0-codex-read` and `./l0-ignored-tools` are their own modules: the LIST is long and\n * every entry carries a paragraph of reasoning, so the types that describe an entry get crowded out\n * by the entries themselves. Nothing here knows what is on the list; `./l0-allowlist` owns that and\n * imports these, so the dependency runs one way and there is no cycle.\n *\n * NOT re-exported from here onward — `./shim` is the ONE name that gathers L0, and it stars this\n * module alongside the others.\n */\n\nimport { AiType } from '@webpieces/hook-runtime';\n\n/**\n * The token an L0 entry uses to say it serves EVERY harness — SAID OUT LOUD.\n *\n * This used to be `null`, and `null` is shim shape #5 from `.claude/rules/no-backwards-compat.md`: a widening expressed as an\n * ABSENCE. It made the widest setting the shortest thing to type and, worse, impossible to grep —\n * there is no search that lists \"the entries every harness gets\", because they were identified by\n * a field that was not there. `grep -n EVERY_HARNESS` now lists every one of them.\n *\n * It is a REAL VALUE in exactly the sense `AI_TYPE_UNKNOWN` is: countable, greppable, and typed.\n */\nexport const EVERY_HARNESS = 'every-harness';\n\n/**\n * Who one L0 entry is FOR: exactly one harness, or — named, never implied — all of them.\n *\n * Deliberately NOT `readonly AiType[]`. A list re-opens the hole this closed from the other side:\n * `[]` would be a second way to write \"nobody\", and `['claude-code', 'codex']` a second way to write\n * EVERY_HARNESS — two spellings of one decision, which is shim shape #1. Dean's rule is the whole\n * type: we only support codex or claudecode or FAIL.\n */\nexport type L0Harness = AiType | typeof EVERY_HARNESS;\n\n/** One tool call as L0 judges it: the tool name, the Bash command (or ''), the file target (or ''). */\nexport class L0Call {\n constructor(\n readonly toolName: string,\n readonly command: string,\n readonly filePath: string,\n ) {}\n}\n\n/**\n * One entry of THE L0 allowlist. Data-only → a class, per CLAUDE.md.\n *\n * `ere`/`js` are the twin regex BODIES for a Bash entry, or null for a tool-shaped entry (Read, the\n * webpieces.config.json target) that no regex can express. `sample` is a call this entry must accept —\n * it is what the matrix-coverage and cure-reachability tests drive isAllowed() with.\n *\n * `extraSamples` pins ADDITIONAL spellings the same entry must accept. A spelling that some deny\n * message prescribes belongs here, or nothing stops a later tightening of the pattern from making that\n * message's cure untypable again — which is the deadlock shape this whole module exists to prevent.\n *\n * `cure` is the ONE thing that is not uniform across the list, and it is not about L0 at all — see\n * L0_CURE_ALLOW_JS below. Every entry is judged identically while an L0 fault is up; `cure` decides\n * only whether the entry ALSO bypasses the downstream (L1) guards on a HEALTHY tree.\n */\nexport class L0AllowEntry {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n readonly label: string,\n readonly kind: 'pass' | 'allow',\n /**\n * True when this entry REPAIRS the tooling (install, sync, shim restore). A cure has to run\n * before webpieces.config.json can even be loaded, so it bypasses everything, always. A\n * non-cure (read-only orientation) is allowed while a fault is up and is otherwise an ordinary\n * command the downstream guards still judge.\n */\n readonly cure: boolean,\n readonly ere: string | null,\n readonly js: string | null,\n /**\n * The ONE harness this entry exists for, or `EVERY_HARNESS` for the entries every harness gets.\n * There is no default and no absence: an entry must say which it is, or it does not compile.\n *\n * A gated entry is unreachable from any other harness — it is spliced into its own union, which\n * both halves of L0 consult only after answering \"which harness sent this call?\". It exists\n * because the two harnesses do not have the same TOOLS: `Read` is entry 1 for Claude Code and\n * Codex has no such tool, so read parity at L0 can only be expressed per harness. Anything added\n * here later must satisfy the property stated on AI_TYPE_SH: the sh half's answer is an\n * approximation, so a gated entry may never grant more than the OTHER harness already has.\n */\n readonly harness: L0Harness,\n readonly sample: L0Call,\n readonly extraSamples: readonly L0Call[] = [],\n ) {}\n\n /** Every call this entry pins: the canonical sample plus every extra spelling. */\n allSamples(): readonly L0Call[] {\n return [this.sample, ...this.extraSamples];\n }\n}\n\n"]}
@@ -3,7 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.WP_LOG_SH = exports.RESOLVE_LOG_DIR_SH = exports.SHIM_LOG_PRINTF = exports.SHIM_LOG_FIELDS = exports.ShimLogField = exports.SHIM_LOG_FAULTS = exports.SHIM_LOG_VERDICTS = exports.ShimLogVerdict = exports.SHIM_LOG_MAX_BYTES = void 0;
4
4
  const rules_config_1 = require("@webpieces/rules-config");
5
5
  const log_streams_1 = require("../core/log-streams");
6
- const agent_event_1 = require("../core/agent-event");
6
+ const hook_runtime_1 = require("@webpieces/hook-runtime");
7
7
  const l0_fault_codes_1 = require("../core/l0-fault-codes");
8
8
  // ---------------------------------------------------------------------------
9
9
  // THE L0 AUDIT LOG, in POSIX sh — the shim half of
@@ -131,7 +131,7 @@ exports.SHIM_LOG_FIELDS = [
131
131
  // union's, produced by AI_TYPE_SH — one vocabulary across all five streams. A row written before
132
132
  // this field existed simply has no `ai=`, which reads as `unknown`; that is a real value, not a
133
133
  // compatibility shim.
134
- new ShimLogField(`ai=<${agent_event_1.AI_TYPES.join('|')}>`, '"ai=$AI"', 'WHICH coding agent made the call, from the one turn_id discriminator (adapters/detect-ai.ts)'),
134
+ new ShimLogField(`ai=<${hook_runtime_1.AI_TYPES.join('|')}>`, '"ai=$AI"', 'WHICH coding agent made the call, from the one turn_id discriminator (adapters/detect-ai.ts)'),
135
135
  new ShimLogField('tree=<name|primary>', '"tree=$WP_TREE"', 'git\'s own name for the worktree the CALL was made in, derived from the payload\'s cwd'),
136
136
  new ShimLogField(`layer=${l0_fault_codes_1.L0_LAYER}`, `"layer=${l0_fault_codes_1.L0_LAYER}"`, 'the layer that judged it — constant here, and the first half of the join key a deny cites'),
137
137
  new ShimLogField(`row=<${l0_fault_codes_1.L0_ROW_HANDED_DOWN}|${l0_fault_codes_1.L0_ROW_ALLOWLISTED}|${l0_fault_codes_1.L0_ROW_BLOCKED}>`, '"row=$_wp_row"', 'WHICH row of the three-row matrix this call took, read off the verdict (hand-down / allowlisted / blocked)'),
@@ -1 +1 @@
1
- {"version":3,"file":"shim-audit-log.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/bin/shim-audit-log.ts"],"names":[],"mappings":";;;AAAA,0DAAgG;AAChG,qDAAqD;AACrD,qDAA+C;AAE/C,2DAEgC;AAEhC,8EAA8E;AAC9E,mDAAmD;AACnD,8FAA8F;AAC9F,uGAAuG;AACvG,qGAAqG;AACrG,mGAAmG;AACnG,mDAAmD;AACnD,EAAE;AACF,qGAAqG;AACrG,mGAAmG;AACnG,uGAAuG;AACvG,EAAE;AACF,sGAAsG;AACtG,sGAAsG;AACtG,uGAAuG;AACvG,oGAAoG;AACpG,sGAAsG;AACtG,sGAAsG;AACtG,qGAAqG;AACrG,yFAAyF;AACzF,EAAE;AACF,iCAAiC;AACjC,oGAAoG;AACpG,sGAAsG;AACtG,wDAAwD;AACxD,oEAAoE;AACpE,8EAA8E;AAE9E;;;;;GAKG;AACU,QAAA,kBAAkB,GAAG,GAAG,GAAG,IAAI,CAAC;AAE7C;;;;;;GAMG;AACH,MAAa,cAAc;IAEV;IACA;IAFb,YACa,KAAa,EACb,KAAa;QADb,UAAK,GAAL,KAAK,CAAQ;QACb,UAAK,GAAL,KAAK,CAAQ;IACvB,CAAC;CACP;AALD,wCAKC;AAED;;;;;;;GAOG;AACU,QAAA,iBAAiB,GAA8B;IACxD,IAAI,cAAc,CAAC,gBAAgB,EAAE,8EAA8E,CAAC;IACpH,IAAI,cAAc,CAAC,gBAAgB,EAAE,kFAAkF,CAAC;IACxH,IAAI,cAAc,CAAC,YAAY,EAAE,4EAA4E,CAAC;IAC9G,IAAI,cAAc,CAAC,eAAe,EAAE,6EAA6E,CAAC;IAClH,IAAI,cAAc,CAAC,kBAA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c;;;;;;;;;;;;;;;;;qCAiBzC,gCAAiB,IAAI,6BAAc;;;;;;;;+BAQzC,gCAAiB,IAAI,iCAAkB,aAAa,6BAAc;;EAE/F,CAAC;AAEH;;;;;;;;;;;;;;;;;;GAkBG;AACU,QAAA,SAAS,GAAG;;;;EAIvB,0BAAkB;;;;;;;;;0BASM,4BAAc;;;;;;;;;;;;;;;;sBAgBlB,MAAM,CAAC,0BAAkB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA6BlC,mCAAkB;mCACG,mCAAkB,sBAAsB,+BAAc;MACnF,uBAAe;;EAEnB,CAAC","sourcesContent":["import { LOGS_STATE_DIR, WORKTREE_STATE_DIR, WEBPIECES_TMP_DIR } from '@webpieces/rules-config';\nimport { L0_SHIM_STREAM } from '../core/log-streams';\nimport { AI_TYPES } from '../core/agent-event';\n\nimport {\n L0_FAULT_NONE, L0_LAYER, L0_SH_FAULT_CODES, L0_ROW_ALLOWLISTED, L0_ROW_BLOCKED, L0_ROW_HANDED_DOWN,\n} from '../core/l0-fault-codes';\n\n// ---------------------------------------------------------------------------\n// THE L0 AUDIT LOG, in POSIX sh — the shim half of\n// `.webpieces/**/logs/L0-shim/<session>-<agent|coordinator>-<binName>.log`. The writer key is\n// the sh twin of ai-hook-rules' LogStream.writerFile(): wp-ai-guards-hook and wp-ai-rules-hook are run\n// IN PARALLEL by Claude Code on every file edit, so an unsplit name means two writers, one file, and\n// torn appends above PIPE_BUF. A payload with no session_id renders 'unknown', never a bare name —\n// there is no un-prefixed spelling on either side.\n//\n// Split out of ./shim.ts (which renders the shim body) purely so both stay readable; shim.ts splices\n// these fragments in verbatim and re-exports the constants. Like l0-allowlist.ts, this module must\n// stay dependency-light: the shim it renders has to work on a tree too broken to load the rule engine.\n//\n// ─── What changed, and why it is not just a bigger log ─────────────────────────────────────────────\n// This log used to be a FAULT log wearing an audit log's name. `wp_log` fired only on the fail-closed\n// path (ALLOW-READ / ALLOW-CONFIG / ALLOW-CURE / DENY*), so a HEALTHY call — the overwhelming majority\n// — exec'd the bin and recorded nothing at all. You could therefore never answer \"what did L0 do to\n// this tool call?\", only \"what did L0 do on the calls where L0 was already broken\". Absence of a line\n// meant either \"healthy\" or \"the shim never ran\", and those are the two answers you most need to tell\n// apart. Every path now logs exactly one line, including the pass-through, so the file can be diffed\n// against the documented matrix in guards/L0-tooling.md rather than merely spot-checked.\n//\n// Two more defects went with it:\n// • it wrote to a hardcoded `$ROOT/.webpieces/logs`, so every worktree's lines landed in one flat\n// file (or, worse, in whichever tree happened to hold the shim) instead of the per-tree namespace\n// the L1 binary has used since the state-dir split;\n// • it had NO rotation, on a file now written on EVERY tool call.\n// ---------------------------------------------------------------------------\n\n/**\n * Rotation threshold, in bytes — 512 KB, the SAME number and the same `.1.log` naming as\n * decision-log.ts / rejection-log.ts / main-sync-log.ts. Deliberately identical rather than merely\n * similar: two log families in one directory with two different retention rules is a trap for whoever\n * later tries to reason about how much history they still have.\n */\nexport const SHIM_LOG_MAX_BYTES = 512 * 1024;\n\n/**\n * One verdict label the shim can record, WITH what it means. Data-only → a class, per CLAUDE.md.\n *\n * The meaning travels with the label because guards/L0-tooling.md renders this table rather than\n * restating it: a bare `string[]` left the meanings in prose, and the prose is what went stale (the\n * hand-written doc documented `DENY-UNDECLARED` for releases while this array did not list it at all).\n */\nexport class ShimLogVerdict {\n constructor(\n readonly label: string,\n readonly means: string,\n ) {}\n}\n\n/**\n * The verdict vocabulary one shim invocation can record, and how each maps to guards/L0-tooling.md.\n *\n * The ALLOW-* and DENY-* labels are the ones this log has always used and are kept verbatim, so\n * anything already grepping them keeps working. `PASS-BIN-*` is the healthy case the log used to be\n * silent about, and `DENY-UNDECLARED` is fault U's — emitted by the shim since U existed, but missing\n * from this array until the generated doc started reading it.\n */\nexport const SHIM_LOG_VERDICTS: readonly ShimLogVerdict[] = [\n new ShimLogVerdict('PASS-BIN-ALLOW', 'no sh-side fault; the bin ran and exited 0 — matrix row 1, handed down to L1'),\n new ShimLogVerdict('PASS-BIN-BLOCK', 'no sh-side fault; the bin ran and exited 2 — matrix row 1, a LATER layer blocked'),\n new ShimLogVerdict('ALLOW-READ', 'allowlist entry 1 (any Read) — PASS, but terminal here (the bin never ran)'),\n new ShimLogVerdict('ALLOW-IGNORED', 'a Codex tool with nothing to judge (L0_IGNORED_TOOLS) — PASS, terminal here'),\n new ShimLogVerdict('ALLOW-CODEX-READ',\n 'the harness-gated entry: a read-shaped Bash command on CODEX, which has no Read tool — PASS, terminal here. '\n + 'It cannot appear on a claude-code line; if one ever does, the sh harness test (AI_TYPE_SH) misread the payload'),\n new ShimLogVerdict('ALLOW-CONFIG', 'allowlist entry 2 (a Write/Edit of webpieces.config.json) — PASS, terminal here'),\n new ShimLogVerdict('ALLOW-MANIFEST', 'allowlist entry 3 (a Write/Edit of pnpm-workspace.yaml or package.json) — PASS, terminal here'),\n new ShimLogVerdict('ALLOW-CURE', 'a Bash entry of the allowlist matched — ALLOW'),\n new ShimLogVerdict('DENY', 'fault X, not on the allowlist — BLOCK_AI_CURE'),\n new ShimLogVerdict('DENY-UNDECLARED', 'fault U, not on the allowlist — BLOCK_AI_CURE'),\n new ShimLogVerdict('DENY-STALE', 'fault D, not on the allowlist — BLOCK_AI_CURE'),\n new ShimLogVerdict('DENY-BROKEN', 'fault K, not on the allowlist — BLOCK_AI_CURE'),\n];\n\n/**\n * The sh-side L0 fault codes, IMPORTED from the one codebook (../core/l0-fault-codes) rather than\n * retyped here — the letters in this file and the letters in `L0_FAULTS` have to be the same letters or\n * the log cannot be reconciled against the matrix. `-` means \"no sh-side fault\": the shim cannot\n * classify S / C / Y, which the BINARY detects and stamps onto its OWN streams with the same `fault=`\n * field, so a `-` here is a statement about this layer only, never a claim that nothing was wrong.\n */\nexport const SHIM_LOG_FAULTS = [...L0_SH_FAULT_CODES, L0_FAULT_NONE] as const;\n\n/**\n * One FIELD of the audit line: how it reads on disk, the sh expression that produces it, and what it\n * answers. Data-only → a class, per CLAUDE.md.\n */\nexport class ShimLogField {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n readonly label: string,\n /** The sh word spliced into the printf below — the ONE place this field's value is spelled. */\n readonly shValue: string,\n readonly means: string,\n /**\n * True for a field that is printed only SOMETIMES (`bin=`, and only when it differs from\n * `shim=`). Such a field carries its OWN trailing tab in its sh value and therefore renders\n * with NO separator of its own — `%s%s` glues it to the next field, so an empty value leaves\n * the line one field shorter rather than leaving a stray tab behind.\n */\n readonly optional: boolean = false,\n ) {}\n}\n\n/**\n * THE LINE, as data. The printf below is BUILT from this array and guards/L0-tooling.md RENDERS it, so\n * a field cannot be added, dropped or reordered without both the shim and the doc changing with it.\n *\n * That is not decoration: `shim=`/`bin=` were inserted mid-line (deliberately breaking positional\n * readers rather than appending where a stale parser keeps working), then `layer=`/`row=` joined them,\n * and the hand-written doc went on describing a 7-field line with no `U` in its fault set the whole time.\n */\nexport const SHIM_LOG_FIELDS: readonly ShimLogField[] = [\n new ShimLogField('<iso-ts>', `\"$(date '+%Y-%m-%dT%H:%M:%S%z' 2>/dev/null)\"`,\n 'when the shim judged the call, local time with offset'),\n new ShimLogField('<bin-name>', '\"$BIN_NAME\"',\n 'WHICH hook ran - wp-ai-guards-hook or wp-ai-rules-hook; Claude Code runs them in parallel'),\n new ShimLogField('<tool>', '\"$TOOL\"', 'the PreToolUse tool name (Bash, Read, Write, Edit, apply_patch, …)'),\n // WHICH HARNESS. Inserted MID-LINE rather than appended, which is this format's house style and is\n // deliberate: a positional reader that has not been updated fails loudly here instead of silently\n // reading the wrong column forever (see this array's own header). The values are the `AiType`\n // union's, produced by AI_TYPE_SH — one vocabulary across all five streams. A row written before\n // this field existed simply has no `ai=`, which reads as `unknown`; that is a real value, not a\n // compatibility shim.\n new ShimLogField(`ai=<${AI_TYPES.join('|')}>`, '\"ai=$AI\"',\n 'WHICH coding agent made the call, from the one turn_id discriminator (adapters/detect-ai.ts)'),\n new ShimLogField('tree=<name|primary>', '\"tree=$WP_TREE\"',\n 'git\\'s own name for the worktree the CALL was made in, derived from the payload\\'s cwd'),\n new ShimLogField(`layer=${L0_LAYER}`, `\"layer=${L0_LAYER}\"`,\n 'the layer that judged it — constant here, and the first half of the join key a deny cites'),\n new ShimLogField(`row=<${L0_ROW_HANDED_DOWN}|${L0_ROW_ALLOWLISTED}|${L0_ROW_BLOCKED}>`, '\"row=$_wp_row\"',\n 'WHICH row of the three-row matrix this call took, read off the verdict (hand-down / allowlisted / blocked)'),\n new ShimLogField('shim=<root>', '\"shim=$ROOT\"',\n 'WHICH COPY of ai-hook.sh ran, resolved from $0 — against tree= it is the straddle detector'),\n new ShimLogField('bin=<root>', '\"$_wp_bin\"',\n 'WHICH TREE supplied the binary — printed ONLY when it differs from shim=, so its presence IS the borrow',\n true),\n new ShimLogField(`fault=<${SHIM_LOG_FAULTS.join('|')}>`, '\"fault=$1\"',\n 'the sh-side L0 fault, or `-`; S/C/Y are the binary\\'s and are stamped on ITS streams'),\n new ShimLogField('<VERDICT>', '\"$2\"', 'one of the verdict labels below — kept adjacent to the command'),\n new ShimLogField('<command>', '\"$CMD_LOG\"',\n 'the command PREFIX (the audit spelling; the DECISION reads $CMD, which fails closed on a quote)'),\n];\n\n/**\n * The writer's `printf`, assembled from SHIM_LOG_FIELDS — one `%s` per field, in the same order, and a\n * tab after every field EXCEPT an optional one (which carries its own). Retyping either half is what\n * let the format and its documentation disagree, so neither half is retyped anywhere.\n */\nexport const SHIM_LOG_PRINTF =\n `printf '${SHIM_LOG_FIELDS.map(\n (f: ShimLogField, i: number): string => '%s' + (i === SHIM_LOG_FIELDS.length - 1 ? '' : (f.optional ? '' : '\\\\t')),\n ).join('')}\\\\n' `\n + `${SHIM_LOG_FIELDS.map((f: ShimLogField): string => f.shValue).join(' ')} >> \"$_wp_f\"`;\n\n/**\n * Shell fragment: derive WHERE this call's log belongs — the sh TWIN of `DotWebpieces.local()` +\n * `worktreeName()` + `primaryRoot()` in @webpieces/rules-config.\n *\n * sh cannot import TypeScript, so this derivation is duplicated by necessity; the mitigation is\n * `shim-audit-log.spec.ts`, which runs THIS function through a real /bin/sh in real git worktrees and\n * asserts it returns exactly what `dotWebpieces.worktreeName()` returns. If the two ever disagree the\n * lock goes red rather than the logs quietly splitting in half.\n *\n * It asks git the SAME question the TS side asks — `--git-dir` vs `--git-common-dir`, which differ if\n * and only if this is a linked worktree — but in ONE `rev-parse` (it accepts both flags and prints a\n * line each) rather than two, because this runs on the blocking path of every tool call.\n *\n * The tree is derived from the PAYLOAD's `cwd` (Claude Code documents it as the working directory the\n * hook was invoked from), not from `$ROOT`. `$ROOT` is where the shim FILE lives and stays the anchor\n * for what the drift guard MEASURES — this fragment changes only where the log is WRITTEN.\n *\n * Fails soft, exactly like the TS side: when git cannot answer, the log collapses to\n * `<cwd>/.webpieces/logs`, which is the pre-change behaviour.\n */\nexport const RESOLVE_LOG_DIR_SH = `wp_resolve_log_dir() {\n _wp_rp=\"$(git -C \"$WP_CWD\" rev-parse --git-dir --git-common-dir 2>/dev/null)\"\n _wp_gd=\"$(printf '%s\\\\n' \"$_wp_rp\" | sed -n 1p)\"\n _wp_cd=\"$(printf '%s\\\\n' \"$_wp_rp\" | sed -n 2p)\"\n if [ -z \"$_wp_gd\" ] || [ -z \"$_wp_cd\" ]; then\n WP_TREE=primary; WP_LOG_DIR=\"$WP_CWD/${WEBPIECES_TMP_DIR}/${LOGS_STATE_DIR}\"\n WP_PRIMARY_LOG_DIR=\"$WP_LOG_DIR\"; return 0\n fi\n # git prints a BARE .git from the primary clone and an absolute path from a linked worktree; the TS\n # twin runs path.resolve(cwd, printed), so do the same before comparing or taking a basename.\n case \"$_wp_gd\" in /*) : ;; *) _wp_gd=\"$WP_CWD/$_wp_gd\" ;; esac\n case \"$_wp_cd\" in /*) : ;; *) _wp_cd=\"$WP_CWD/$_wp_cd\" ;; esac\n # The primary clone's root is the parent of the SHARED git dir — declining any layout whose shared\n # dir is not named .git (a bare repo, --separate-git-dir), same test as primaryRoot().\n _wp_primary=\"$WP_CWD\"\n case \"$_wp_cd\" in\n */.git) [ -d \"\\${_wp_cd%/*}\" ] && _wp_primary=\"\\${_wp_cd%/*}\" ;;\n esac\n # The PRIMARY clone's log dir, resolved on both branches. A deny that has to tell a human WHERE the\n # audit trail is (the inverse-drift escalation in shim.ts) must be able to name both the tree it is\n # standing in and the primary — a subagent has no reach into the second one, so the deny has to quote\n # that path rather than send anyone to go and look.\n WP_PRIMARY_LOG_DIR=\"$_wp_primary/${WEBPIECES_TMP_DIR}/${LOGS_STATE_DIR}\"\n if [ \"$_wp_gd\" = \"$_wp_cd\" ]; then\n WP_TREE=primary\n WP_LOG_DIR=\"$WP_PRIMARY_LOG_DIR\"\n else\n # git's OWN name for the worktree (the basename of <primary>/.git/worktrees/<name>), not the\n # directory's basename — two worktrees under different parents may share a directory name.\n WP_TREE=\"\\${_wp_gd##*/}\"\n WP_LOG_DIR=\"$_wp_primary/${WEBPIECES_TMP_DIR}/${WORKTREE_STATE_DIR}/$WP_TREE/${LOGS_STATE_DIR}\"\n fi\n}`;\n\n/**\n * Shell fragment: the audit-log writer itself — `wp_log <fault> <verdict>`, one tab-separated line.\n *\n * FORMAT: SHIM_LOG_FIELDS, tab-separated, append-only — that array IS the format, and SHIM_LOG_PRINTF\n * is built from it, so neither this docblock nor guards/L0-tooling.md can describe a line the shim does\n * not write.\n *\n * `tree=` and `fault=` are the two fields that make the file reconcilable against guards/L0-tooling.md:\n * the first says WHICH checkout produced the line (a shared log across seven worktrees is otherwise\n * unreadable), the second says which of the sh-side faults the shim detected. The verdict\n * keeps its historical spelling and stays adjacent to the command, so `grep 'DENY-STALE\\\\t'` still\n * finds what it always found.\n *\n * NEVER breaks or blocks the hook: the whole body is wrapped so a failure of any kind — unwritable\n * directory, read-only filesystem, missing `git` — is swallowed, and nothing is ever written to\n * stdout (stdout is the PreToolUse decision channel; a stray byte there corrupts allow/deny).\n *\n * The log dir is resolved LAZILY on first use so a call that never logs never pays for the git probe.\n */\nexport const WP_LOG_SH = `WP_TREE=\"\"\nWP_LOG_DIR=\"\"\nWP_PRIMARY_LOG_DIR=\"\"\nWP_TAB=\"$(printf '\\\\t')\" # one real tab, so the OPTIONAL bin= field can carry its own separator\n${RESOLVE_LOG_DIR_SH}\nwp_clean() { # one path segment from an UNTRUSTED payload id — twin of LogStream's segment()\n printf '%s' \"$1\" | tr -c 'A-Za-z0-9._-' '_' | sed -e 's/\\\\.\\\\{2,\\\\}/_/g' -e 's/^\\\\.\\\\{1,\\\\}/_/' | cut -c1-64\n}\nwp_log() { # $1 = L0 fault code (D|X|K|-), $2 = verdict label\n {\n [ -n \"$WP_LOG_DIR\" ] || wp_resolve_log_dir\n # The LAYER is the directory and the WRITER is the file — same layout the TS writers use, spelled\n # from the same constant so the two halves cannot drift apart.\n _wp_sd=\"$WP_LOG_DIR/${L0_SHIM_STREAM}\"\n mkdir -p \"$_wp_sd\" 2>/dev/null || return 0\n # Same writer key as LogStream.writerFile(): <session>-<agent|coordinator>-<hook>.log. $BIN_NAME\n # IS the hook discriminator here (wp-ai-guards-hook vs wp-ai-rules-hook), and Claude Code runs those\n # two IN PARALLEL on every file edit — without this prefix they append to ONE file and tear above\n # PIPE_BUF. An empty session id renders 'unknown' — this has no bare-name branch, matching\n # LogStream.writerFile(), which has none either.\n # ALWAYS prefixed - a missing session_id renders as 'unknown', never as the shared bare name.\n # Gating this on a non-empty id would drop both parallel hooks back onto one file, which is the\n # torn-append case this exists to remove. Twin of LogStream.writerFile(), which has no bare branch.\n _wp_pfx=\"$(wp_clean \"\\${WP_SID:-unknown}\")-$(wp_clean \"\\${WP_AID:-coordinator}\")-$BIN_NAME\"\n _wp_f=\"$_wp_sd/\\${_wp_pfx}.log\"\n # Rotate at the SAME 512 KB into the SAME .1.log sibling as every JS-side webpieces log. This runs\n # on every tool call, so it is one wc and no more; a size we cannot read counts as 0 (no rotation).\n _wp_sz=\"$(wc -c < \"$_wp_f\" 2>/dev/null | tr -d ' ')\"\n case \"$_wp_sz\" in ''|*[!0-9]*) _wp_sz=0 ;; esac\n [ \"$_wp_sz\" -gt ${String(SHIM_LOG_MAX_BYTES)} ] && mv -f \"$_wp_f\" \"$_wp_sd/\\${_wp_pfx}.1.log\" 2>/dev/null\n # shim= and bin= are the two facts this log could not previously answer, and they are the ones that\n # decide whether a tree was governed by its OWN release or a borrowed one:\n # shim= WHICH COPY OF ai-hook.sh RAN — $ROOT, resolved from $0. The file is TRACKED, so every\n # worktree carries the version at ITS commit; settings.json registers it ABSOLUTE, so the copy\n # that runs is the SESSION ROOT's. Logged rather than assumed, on EVERY line: compared against\n # tree= it is the STRADDLE detector (tree=agent-X shim=<repo> = standing in one tree, judged by\n # another), and that pair varies constantly.\n # bin= WHICH TREE SUPPLIED THE BINARY — $BIN_ROOT, the upward walk's answer.\n #\n # bin= IS PRINTED ONLY WHEN IT DIFFERS FROM shim=, so its mere PRESENCE is the diagnostic (\"the binary\n # came from a different tree than the shim\") instead of ~50 bytes repeated on every line. Measured\n # across 549 logged lines: it differed on 39, every one a worktree agent's first few calls before it\n # ran pnpm install — after that they matched for the rest of that agent's life. And since the hooks\n # went ABSOLUTE, shim= is always the MAIN tree, so the two can now only differ when the main tree\n # itself has no node_modules (a fresh clone before install). ~7% of lines then, near 0% going forward.\n # A unit test asserts the field appears if and only if the roots differ, so it cannot quietly become\n # unconditional noise again.\n _wp_bin=\"\"\n [ \"$BIN_ROOT\" != \"$ROOT\" ] && _wp_bin=\"bin=$BIN_ROOT$WP_TAB\"\n # layer= and row= are the JOIN KEYS, and they are here so the join is REAL rather than promised.\n # Every L0 deny now opens '[<guard>] (layer=L0 fault=<code> row=<n>)' and cites \"the same coordinates\n # the audit line carries\" — which was true of the JS half (MATRIX_L0_BLOCK, via decision-log) and\n # FALSE of this one, which carried 'fault=' alone. Fixing the message instead of the line would have\n # left 'grep 'layer=L0 row=3'' finding one half of L0 and silently missing the other four faults.\n #\n # 'row=' is NOT a constant: it is the row of the three-row matrix this call actually took, read off\n # the verdict — hand-down, allowlisted, or blocked — exactly as L1 logs 'row=' from L1_ROWS. That is\n # what distinguishes it from the ~50 constant bytes 'bin=' used to spend above.\n _wp_row=${L0_ROW_HANDED_DOWN}\n case \"$2\" in ALLOW*) _wp_row=${L0_ROW_ALLOWLISTED} ;; DENY*) _wp_row=${L0_ROW_BLOCKED} ;; esac\n ${SHIM_LOG_PRINTF}\n } 2>/dev/null || true\n}`;\n"]}
1
+ {"version":3,"file":"shim-audit-log.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/bin/shim-audit-log.ts"],"names":[],"mappings":";;;AAAA,0DAAgG;AAChG,qDAAqD;AACrD,0DAAmD;AAEnD,2DAEgC;AAEhC,8EAA8E;AAC9E,mDAAmD;AACnD,8FAA8F;AAC9F,uGAAuG;AACvG,qGAAqG;AACrG,mGAAmG;AACnG,mDAAmD;AACnD,EAAE;AACF,qGAAqG;AACrG,mGAAmG;AACnG,uGAAuG;AACvG,EAAE;AACF,sGAAsG;AACtG,sGAAsG;AACtG,uGAAuG;AACvG,oGAAoG;AACpG,sGAAsG;AACtG,sGAAsG;AACtG,qGAAqG;AACrG,yFAAyF;AACzF,EAAE;AACF,iCAAiC;AACjC,oGAAoG;AACpG,sGAAsG;AACtG,wDAAwD;AACxD,oEAAoE;AACpE,8EAA8E;AAE9E;;;;;GAKG;AACU,QAAA,kBAAkB,GAAG,GAAG,GAAG,IAAI,CAAC;AAE7C;;;;;;GAMG;AACH,MAAa,cAAc;IAEV;IACA;IAFb,YACa,KAAa,EACb,KAAa;QADb,UAAK,GAAL,KAAK,CAAQ;QACb,UAAK,GAAL,KAAK,CAAQ;IACvB,CAAC;CACP;AALD,wCAKC;AAED;;;;;;;GAOG;AACU,QAAA,iBAAiB,GAA8B;IACxD,IAAI,cAAc,CAAC,gBAAgB,EAAE,8EAA8E,CAAC;IACpH,IAAI,cAAc,CAAC,gBAAgB,EAAE,kFAAkF,CAAC;IACxH,IAAI,cAAc,CAAC,YAAY,EAAE,4EAA4E,CAAC;IAC9G,IAAI,cAAc,CAAC,eA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,QAAA,kBAAkB,GAAG;;;;;2CAKS,gCAAiB,IAAI,6BAAc;;;;;;;;;;;;;;;;;qCAiBzC,gCAAiB,IAAI,6BAAc;;;;;;;;+BAQzC,gCAAiB,IAAI,iCAAkB,aAAa,6BAAc;;EAE/F,CAAC;AAEH;;;;;;;;;;;;;;;;;;GAkBG;AACU,QAAA,SAAS,GAAG;;;;EAIvB,0BAAkB;;;;;;;;;0BASM,4BAAc;;;;;;;;;;;;;;;;sBAgBlB,MAAM,CAAC,0BAAkB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA6BlC,mCAAkB;mCACG,mCAAkB,sBAAsB,+BAAc;MACnF,uBAAe;;EAEnB,CAAC","sourcesContent":["import { LOGS_STATE_DIR, WORKTREE_STATE_DIR, WEBPIECES_TMP_DIR } from '@webpieces/rules-config';\nimport { L0_SHIM_STREAM } from '../core/log-streams';\nimport { AI_TYPES } from '@webpieces/hook-runtime';\n\nimport {\n L0_FAULT_NONE, L0_LAYER, L0_SH_FAULT_CODES, L0_ROW_ALLOWLISTED, L0_ROW_BLOCKED, L0_ROW_HANDED_DOWN,\n} from '../core/l0-fault-codes';\n\n// ---------------------------------------------------------------------------\n// THE L0 AUDIT LOG, in POSIX sh — the shim half of\n// `.webpieces/**/logs/L0-shim/<session>-<agent|coordinator>-<binName>.log`. The writer key is\n// the sh twin of ai-hook-rules' LogStream.writerFile(): wp-ai-guards-hook and wp-ai-rules-hook are run\n// IN PARALLEL by Claude Code on every file edit, so an unsplit name means two writers, one file, and\n// torn appends above PIPE_BUF. A payload with no session_id renders 'unknown', never a bare name —\n// there is no un-prefixed spelling on either side.\n//\n// Split out of ./shim.ts (which renders the shim body) purely so both stay readable; shim.ts splices\n// these fragments in verbatim and re-exports the constants. Like l0-allowlist.ts, this module must\n// stay dependency-light: the shim it renders has to work on a tree too broken to load the rule engine.\n//\n// ─── What changed, and why it is not just a bigger log ─────────────────────────────────────────────\n// This log used to be a FAULT log wearing an audit log's name. `wp_log` fired only on the fail-closed\n// path (ALLOW-READ / ALLOW-CONFIG / ALLOW-CURE / DENY*), so a HEALTHY call — the overwhelming majority\n// — exec'd the bin and recorded nothing at all. You could therefore never answer \"what did L0 do to\n// this tool call?\", only \"what did L0 do on the calls where L0 was already broken\". Absence of a line\n// meant either \"healthy\" or \"the shim never ran\", and those are the two answers you most need to tell\n// apart. Every path now logs exactly one line, including the pass-through, so the file can be diffed\n// against the documented matrix in guards/L0-tooling.md rather than merely spot-checked.\n//\n// Two more defects went with it:\n// • it wrote to a hardcoded `$ROOT/.webpieces/logs`, so every worktree's lines landed in one flat\n// file (or, worse, in whichever tree happened to hold the shim) instead of the per-tree namespace\n// the L1 binary has used since the state-dir split;\n// • it had NO rotation, on a file now written on EVERY tool call.\n// ---------------------------------------------------------------------------\n\n/**\n * Rotation threshold, in bytes — 512 KB, the SAME number and the same `.1.log` naming as\n * decision-log.ts / rejection-log.ts / main-sync-log.ts. Deliberately identical rather than merely\n * similar: two log families in one directory with two different retention rules is a trap for whoever\n * later tries to reason about how much history they still have.\n */\nexport const SHIM_LOG_MAX_BYTES = 512 * 1024;\n\n/**\n * One verdict label the shim can record, WITH what it means. Data-only → a class, per CLAUDE.md.\n *\n * The meaning travels with the label because guards/L0-tooling.md renders this table rather than\n * restating it: a bare `string[]` left the meanings in prose, and the prose is what went stale (the\n * hand-written doc documented `DENY-UNDECLARED` for releases while this array did not list it at all).\n */\nexport class ShimLogVerdict {\n constructor(\n readonly label: string,\n readonly means: string,\n ) {}\n}\n\n/**\n * The verdict vocabulary one shim invocation can record, and how each maps to guards/L0-tooling.md.\n *\n * The ALLOW-* and DENY-* labels are the ones this log has always used and are kept verbatim, so\n * anything already grepping them keeps working. `PASS-BIN-*` is the healthy case the log used to be\n * silent about, and `DENY-UNDECLARED` is fault U's — emitted by the shim since U existed, but missing\n * from this array until the generated doc started reading it.\n */\nexport const SHIM_LOG_VERDICTS: readonly ShimLogVerdict[] = [\n new ShimLogVerdict('PASS-BIN-ALLOW', 'no sh-side fault; the bin ran and exited 0 — matrix row 1, handed down to L1'),\n new ShimLogVerdict('PASS-BIN-BLOCK', 'no sh-side fault; the bin ran and exited 2 — matrix row 1, a LATER layer blocked'),\n new ShimLogVerdict('ALLOW-READ', 'allowlist entry 1 (any Read) — PASS, but terminal here (the bin never ran)'),\n new ShimLogVerdict('ALLOW-IGNORED', 'a Codex tool with nothing to judge (L0_IGNORED_TOOLS) — PASS, terminal here'),\n new ShimLogVerdict('ALLOW-CODEX-READ',\n 'the harness-gated entry: a read-shaped Bash command on CODEX, which has no Read tool — PASS, terminal here. '\n + 'It cannot appear on a claude-code line; if one ever does, the sh harness test (AI_TYPE_SH) misread the payload'),\n new ShimLogVerdict('ALLOW-CONFIG', 'allowlist entry 2 (a Write/Edit of webpieces.config.json) — PASS, terminal here'),\n new ShimLogVerdict('ALLOW-MANIFEST', 'allowlist entry 3 (a Write/Edit of pnpm-workspace.yaml or package.json) — PASS, terminal here'),\n new ShimLogVerdict('ALLOW-CURE', 'a Bash entry of the allowlist matched — ALLOW'),\n new ShimLogVerdict('DENY', 'fault X, not on the allowlist — BLOCK_AI_CURE'),\n new ShimLogVerdict('DENY-UNDECLARED', 'fault U, not on the allowlist — BLOCK_AI_CURE'),\n new ShimLogVerdict('DENY-STALE', 'fault D, not on the allowlist — BLOCK_AI_CURE'),\n new ShimLogVerdict('DENY-BROKEN', 'fault K, not on the allowlist — BLOCK_AI_CURE'),\n];\n\n/**\n * The sh-side L0 fault codes, IMPORTED from the one codebook (../core/l0-fault-codes) rather than\n * retyped here — the letters in this file and the letters in `L0_FAULTS` have to be the same letters or\n * the log cannot be reconciled against the matrix. `-` means \"no sh-side fault\": the shim cannot\n * classify S / C / Y, which the BINARY detects and stamps onto its OWN streams with the same `fault=`\n * field, so a `-` here is a statement about this layer only, never a claim that nothing was wrong.\n */\nexport const SHIM_LOG_FAULTS = [...L0_SH_FAULT_CODES, L0_FAULT_NONE] as const;\n\n/**\n * One FIELD of the audit line: how it reads on disk, the sh expression that produces it, and what it\n * answers. Data-only → a class, per CLAUDE.md.\n */\nexport class ShimLogField {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n readonly label: string,\n /** The sh word spliced into the printf below — the ONE place this field's value is spelled. */\n readonly shValue: string,\n readonly means: string,\n /**\n * True for a field that is printed only SOMETIMES (`bin=`, and only when it differs from\n * `shim=`). Such a field carries its OWN trailing tab in its sh value and therefore renders\n * with NO separator of its own — `%s%s` glues it to the next field, so an empty value leaves\n * the line one field shorter rather than leaving a stray tab behind.\n */\n readonly optional: boolean = false,\n ) {}\n}\n\n/**\n * THE LINE, as data. The printf below is BUILT from this array and guards/L0-tooling.md RENDERS it, so\n * a field cannot be added, dropped or reordered without both the shim and the doc changing with it.\n *\n * That is not decoration: `shim=`/`bin=` were inserted mid-line (deliberately breaking positional\n * readers rather than appending where a stale parser keeps working), then `layer=`/`row=` joined them,\n * and the hand-written doc went on describing a 7-field line with no `U` in its fault set the whole time.\n */\nexport const SHIM_LOG_FIELDS: readonly ShimLogField[] = [\n new ShimLogField('<iso-ts>', `\"$(date '+%Y-%m-%dT%H:%M:%S%z' 2>/dev/null)\"`,\n 'when the shim judged the call, local time with offset'),\n new ShimLogField('<bin-name>', '\"$BIN_NAME\"',\n 'WHICH hook ran - wp-ai-guards-hook or wp-ai-rules-hook; Claude Code runs them in parallel'),\n new ShimLogField('<tool>', '\"$TOOL\"', 'the PreToolUse tool name (Bash, Read, Write, Edit, apply_patch, …)'),\n // WHICH HARNESS. Inserted MID-LINE rather than appended, which is this format's house style and is\n // deliberate: a positional reader that has not been updated fails loudly here instead of silently\n // reading the wrong column forever (see this array's own header). The values are the `AiType`\n // union's, produced by AI_TYPE_SH — one vocabulary across all five streams. A row written before\n // this field existed simply has no `ai=`, which reads as `unknown`; that is a real value, not a\n // compatibility shim.\n new ShimLogField(`ai=<${AI_TYPES.join('|')}>`, '\"ai=$AI\"',\n 'WHICH coding agent made the call, from the one turn_id discriminator (adapters/detect-ai.ts)'),\n new ShimLogField('tree=<name|primary>', '\"tree=$WP_TREE\"',\n 'git\\'s own name for the worktree the CALL was made in, derived from the payload\\'s cwd'),\n new ShimLogField(`layer=${L0_LAYER}`, `\"layer=${L0_LAYER}\"`,\n 'the layer that judged it — constant here, and the first half of the join key a deny cites'),\n new ShimLogField(`row=<${L0_ROW_HANDED_DOWN}|${L0_ROW_ALLOWLISTED}|${L0_ROW_BLOCKED}>`, '\"row=$_wp_row\"',\n 'WHICH row of the three-row matrix this call took, read off the verdict (hand-down / allowlisted / blocked)'),\n new ShimLogField('shim=<root>', '\"shim=$ROOT\"',\n 'WHICH COPY of ai-hook.sh ran, resolved from $0 — against tree= it is the straddle detector'),\n new ShimLogField('bin=<root>', '\"$_wp_bin\"',\n 'WHICH TREE supplied the binary — printed ONLY when it differs from shim=, so its presence IS the borrow',\n true),\n new ShimLogField(`fault=<${SHIM_LOG_FAULTS.join('|')}>`, '\"fault=$1\"',\n 'the sh-side L0 fault, or `-`; S/C/Y are the binary\\'s and are stamped on ITS streams'),\n new ShimLogField('<VERDICT>', '\"$2\"', 'one of the verdict labels below — kept adjacent to the command'),\n new ShimLogField('<command>', '\"$CMD_LOG\"',\n 'the command PREFIX (the audit spelling; the DECISION reads $CMD, which fails closed on a quote)'),\n];\n\n/**\n * The writer's `printf`, assembled from SHIM_LOG_FIELDS — one `%s` per field, in the same order, and a\n * tab after every field EXCEPT an optional one (which carries its own). Retyping either half is what\n * let the format and its documentation disagree, so neither half is retyped anywhere.\n */\nexport const SHIM_LOG_PRINTF =\n `printf '${SHIM_LOG_FIELDS.map(\n (f: ShimLogField, i: number): string => '%s' + (i === SHIM_LOG_FIELDS.length - 1 ? '' : (f.optional ? '' : '\\\\t')),\n ).join('')}\\\\n' `\n + `${SHIM_LOG_FIELDS.map((f: ShimLogField): string => f.shValue).join(' ')} >> \"$_wp_f\"`;\n\n/**\n * Shell fragment: derive WHERE this call's log belongs — the sh TWIN of `DotWebpieces.local()` +\n * `worktreeName()` + `primaryRoot()` in @webpieces/rules-config.\n *\n * sh cannot import TypeScript, so this derivation is duplicated by necessity; the mitigation is\n * `shim-audit-log.spec.ts`, which runs THIS function through a real /bin/sh in real git worktrees and\n * asserts it returns exactly what `dotWebpieces.worktreeName()` returns. If the two ever disagree the\n * lock goes red rather than the logs quietly splitting in half.\n *\n * It asks git the SAME question the TS side asks — `--git-dir` vs `--git-common-dir`, which differ if\n * and only if this is a linked worktree — but in ONE `rev-parse` (it accepts both flags and prints a\n * line each) rather than two, because this runs on the blocking path of every tool call.\n *\n * The tree is derived from the PAYLOAD's `cwd` (Claude Code documents it as the working directory the\n * hook was invoked from), not from `$ROOT`. `$ROOT` is where the shim FILE lives and stays the anchor\n * for what the drift guard MEASURES — this fragment changes only where the log is WRITTEN.\n *\n * Fails soft, exactly like the TS side: when git cannot answer, the log collapses to\n * `<cwd>/.webpieces/logs`, which is the pre-change behaviour.\n */\nexport const RESOLVE_LOG_DIR_SH = `wp_resolve_log_dir() {\n _wp_rp=\"$(git -C \"$WP_CWD\" rev-parse --git-dir --git-common-dir 2>/dev/null)\"\n _wp_gd=\"$(printf '%s\\\\n' \"$_wp_rp\" | sed -n 1p)\"\n _wp_cd=\"$(printf '%s\\\\n' \"$_wp_rp\" | sed -n 2p)\"\n if [ -z \"$_wp_gd\" ] || [ -z \"$_wp_cd\" ]; then\n WP_TREE=primary; WP_LOG_DIR=\"$WP_CWD/${WEBPIECES_TMP_DIR}/${LOGS_STATE_DIR}\"\n WP_PRIMARY_LOG_DIR=\"$WP_LOG_DIR\"; return 0\n fi\n # git prints a BARE .git from the primary clone and an absolute path from a linked worktree; the TS\n # twin runs path.resolve(cwd, printed), so do the same before comparing or taking a basename.\n case \"$_wp_gd\" in /*) : ;; *) _wp_gd=\"$WP_CWD/$_wp_gd\" ;; esac\n case \"$_wp_cd\" in /*) : ;; *) _wp_cd=\"$WP_CWD/$_wp_cd\" ;; esac\n # The primary clone's root is the parent of the SHARED git dir — declining any layout whose shared\n # dir is not named .git (a bare repo, --separate-git-dir), same test as primaryRoot().\n _wp_primary=\"$WP_CWD\"\n case \"$_wp_cd\" in\n */.git) [ -d \"\\${_wp_cd%/*}\" ] && _wp_primary=\"\\${_wp_cd%/*}\" ;;\n esac\n # The PRIMARY clone's log dir, resolved on both branches. A deny that has to tell a human WHERE the\n # audit trail is (the inverse-drift escalation in shim.ts) must be able to name both the tree it is\n # standing in and the primary — a subagent has no reach into the second one, so the deny has to quote\n # that path rather than send anyone to go and look.\n WP_PRIMARY_LOG_DIR=\"$_wp_primary/${WEBPIECES_TMP_DIR}/${LOGS_STATE_DIR}\"\n if [ \"$_wp_gd\" = \"$_wp_cd\" ]; then\n WP_TREE=primary\n WP_LOG_DIR=\"$WP_PRIMARY_LOG_DIR\"\n else\n # git's OWN name for the worktree (the basename of <primary>/.git/worktrees/<name>), not the\n # directory's basename — two worktrees under different parents may share a directory name.\n WP_TREE=\"\\${_wp_gd##*/}\"\n WP_LOG_DIR=\"$_wp_primary/${WEBPIECES_TMP_DIR}/${WORKTREE_STATE_DIR}/$WP_TREE/${LOGS_STATE_DIR}\"\n fi\n}`;\n\n/**\n * Shell fragment: the audit-log writer itself — `wp_log <fault> <verdict>`, one tab-separated line.\n *\n * FORMAT: SHIM_LOG_FIELDS, tab-separated, append-only — that array IS the format, and SHIM_LOG_PRINTF\n * is built from it, so neither this docblock nor guards/L0-tooling.md can describe a line the shim does\n * not write.\n *\n * `tree=` and `fault=` are the two fields that make the file reconcilable against guards/L0-tooling.md:\n * the first says WHICH checkout produced the line (a shared log across seven worktrees is otherwise\n * unreadable), the second says which of the sh-side faults the shim detected. The verdict\n * keeps its historical spelling and stays adjacent to the command, so `grep 'DENY-STALE\\\\t'` still\n * finds what it always found.\n *\n * NEVER breaks or blocks the hook: the whole body is wrapped so a failure of any kind — unwritable\n * directory, read-only filesystem, missing `git` — is swallowed, and nothing is ever written to\n * stdout (stdout is the PreToolUse decision channel; a stray byte there corrupts allow/deny).\n *\n * The log dir is resolved LAZILY on first use so a call that never logs never pays for the git probe.\n */\nexport const WP_LOG_SH = `WP_TREE=\"\"\nWP_LOG_DIR=\"\"\nWP_PRIMARY_LOG_DIR=\"\"\nWP_TAB=\"$(printf '\\\\t')\" # one real tab, so the OPTIONAL bin= field can carry its own separator\n${RESOLVE_LOG_DIR_SH}\nwp_clean() { # one path segment from an UNTRUSTED payload id — twin of LogStream's segment()\n printf '%s' \"$1\" | tr -c 'A-Za-z0-9._-' '_' | sed -e 's/\\\\.\\\\{2,\\\\}/_/g' -e 's/^\\\\.\\\\{1,\\\\}/_/' | cut -c1-64\n}\nwp_log() { # $1 = L0 fault code (D|X|K|-), $2 = verdict label\n {\n [ -n \"$WP_LOG_DIR\" ] || wp_resolve_log_dir\n # The LAYER is the directory and the WRITER is the file — same layout the TS writers use, spelled\n # from the same constant so the two halves cannot drift apart.\n _wp_sd=\"$WP_LOG_DIR/${L0_SHIM_STREAM}\"\n mkdir -p \"$_wp_sd\" 2>/dev/null || return 0\n # Same writer key as LogStream.writerFile(): <session>-<agent|coordinator>-<hook>.log. $BIN_NAME\n # IS the hook discriminator here (wp-ai-guards-hook vs wp-ai-rules-hook), and Claude Code runs those\n # two IN PARALLEL on every file edit — without this prefix they append to ONE file and tear above\n # PIPE_BUF. An empty session id renders 'unknown' — this has no bare-name branch, matching\n # LogStream.writerFile(), which has none either.\n # ALWAYS prefixed - a missing session_id renders as 'unknown', never as the shared bare name.\n # Gating this on a non-empty id would drop both parallel hooks back onto one file, which is the\n # torn-append case this exists to remove. Twin of LogStream.writerFile(), which has no bare branch.\n _wp_pfx=\"$(wp_clean \"\\${WP_SID:-unknown}\")-$(wp_clean \"\\${WP_AID:-coordinator}\")-$BIN_NAME\"\n _wp_f=\"$_wp_sd/\\${_wp_pfx}.log\"\n # Rotate at the SAME 512 KB into the SAME .1.log sibling as every JS-side webpieces log. This runs\n # on every tool call, so it is one wc and no more; a size we cannot read counts as 0 (no rotation).\n _wp_sz=\"$(wc -c < \"$_wp_f\" 2>/dev/null | tr -d ' ')\"\n case \"$_wp_sz\" in ''|*[!0-9]*) _wp_sz=0 ;; esac\n [ \"$_wp_sz\" -gt ${String(SHIM_LOG_MAX_BYTES)} ] && mv -f \"$_wp_f\" \"$_wp_sd/\\${_wp_pfx}.1.log\" 2>/dev/null\n # shim= and bin= are the two facts this log could not previously answer, and they are the ones that\n # decide whether a tree was governed by its OWN release or a borrowed one:\n # shim= WHICH COPY OF ai-hook.sh RAN — $ROOT, resolved from $0. The file is TRACKED, so every\n # worktree carries the version at ITS commit; settings.json registers it ABSOLUTE, so the copy\n # that runs is the SESSION ROOT's. Logged rather than assumed, on EVERY line: compared against\n # tree= it is the STRADDLE detector (tree=agent-X shim=<repo> = standing in one tree, judged by\n # another), and that pair varies constantly.\n # bin= WHICH TREE SUPPLIED THE BINARY — $BIN_ROOT, the upward walk's answer.\n #\n # bin= IS PRINTED ONLY WHEN IT DIFFERS FROM shim=, so its mere PRESENCE is the diagnostic (\"the binary\n # came from a different tree than the shim\") instead of ~50 bytes repeated on every line. Measured\n # across 549 logged lines: it differed on 39, every one a worktree agent's first few calls before it\n # ran pnpm install — after that they matched for the rest of that agent's life. And since the hooks\n # went ABSOLUTE, shim= is always the MAIN tree, so the two can now only differ when the main tree\n # itself has no node_modules (a fresh clone before install). ~7% of lines then, near 0% going forward.\n # A unit test asserts the field appears if and only if the roots differ, so it cannot quietly become\n # unconditional noise again.\n _wp_bin=\"\"\n [ \"$BIN_ROOT\" != \"$ROOT\" ] && _wp_bin=\"bin=$BIN_ROOT$WP_TAB\"\n # layer= and row= are the JOIN KEYS, and they are here so the join is REAL rather than promised.\n # Every L0 deny now opens '[<guard>] (layer=L0 fault=<code> row=<n>)' and cites \"the same coordinates\n # the audit line carries\" — which was true of the JS half (MATRIX_L0_BLOCK, via decision-log) and\n # FALSE of this one, which carried 'fault=' alone. Fixing the message instead of the line would have\n # left 'grep 'layer=L0 row=3'' finding one half of L0 and silently missing the other four faults.\n #\n # 'row=' is NOT a constant: it is the row of the three-row matrix this call actually took, read off\n # the verdict — hand-down, allowlisted, or blocked — exactly as L1 logs 'row=' from L1_ROWS. That is\n # what distinguishes it from the ~50 constant bytes 'bin=' used to spend above.\n _wp_row=${L0_ROW_HANDED_DOWN}\n case \"$2\" in ALLOW*) _wp_row=${L0_ROW_ALLOWLISTED} ;; DENY*) _wp_row=${L0_ROW_BLOCKED} ;; esac\n ${SHIM_LOG_PRINTF}\n } 2>/dev/null || true\n}`;\n"]}
@@ -1,4 +1,4 @@
1
- import { AiType } from './agent-event';
1
+ import { AiType } from '@webpieces/hook-runtime';
2
2
  /**
3
3
  * WHICH HARNESS this hook process is serving, for the four JS-side audit streams.
4
4
  *
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.aiTypeContext = exports.AiTypeContext = void 0;
4
- const agent_event_1 = require("./agent-event");
4
+ const hook_runtime_1 = require("@webpieces/hook-runtime");
5
5
  /**
6
6
  * WHICH HARNESS this hook process is serving, for the four JS-side audit streams.
7
7
  *
@@ -33,7 +33,7 @@ class AiTypeContext {
33
33
  }
34
34
  /** The `ai=` field's value — the harness, or `unknown` when nothing established one. */
35
35
  forLog() {
36
- return this.aiType ?? agent_event_1.AI_TYPE_UNKNOWN;
36
+ return this.aiType ?? hook_runtime_1.AI_TYPE_UNKNOWN;
37
37
  }
38
38
  }
39
39
  exports.AiTypeContext = AiTypeContext;
@@ -1 +1 @@
1
- {"version":3,"file":"ai-type-context.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/core/ai-type-context.ts"],"names":[],"mappings":";;;AAAA,+CAAwD;AAExD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAa,aAAa;IACd,MAAM,GAAkB,IAAI,CAAC;IAErC,0EAA0E;IAC1E,QAAQ,CAAC,MAAc;QACnB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACzB,CAAC;IAED,wFAAwF;IACxF,MAAM;QACF,OAAO,IAAI,CAAC,MAAM,IAAI,6BAAe,CAAC;IAC1C,CAAC;CACJ;AAZD,sCAYC;AAED;;;GAGG;AACU,QAAA,aAAa,GAAG,IAAI,aAAa,EAAE,CAAC","sourcesContent":["import { AiType, AI_TYPE_UNKNOWN } from './agent-event';\n\n/**\n * WHICH HARNESS this hook process is serving, for the four JS-side audit streams.\n *\n * ─── Why a process-wide holder and not a parameter ────────────────────────────────────────────────\n * One hook process handles exactly one tool call, so the harness is a property of the PROCESS, not of\n * any individual log line. Threading it as a parameter instead would have meant a new argument on\n * `logGuardDecision()`, `logL1Decision()`, `InvocationLog.finish()` and `logRejection()`, which between\n * them are constructed at fourteen call sites across eight guard modules — none of which has any\n * business knowing what a harness is. That is the identical argument `LogStream`'s docblock makes for\n * the session/agent/hook identity, and this is the identical shape: identified ONCE by the adapter that\n * parsed the payload, read by every writer downstream.\n *\n * ─── Why it is NOT folded into StreamIdentity ─────────────────────────────────────────────────────\n * `StreamIdentity` is defined as \"the three fields that make a log FILENAME unique\", and it crosses a\n * process boundary on argv (the detached main-sync refresher). The harness is neither: it never appears\n * in a filename, and a fourth field would have to be threaded through that argv round trip to mean\n * anything. Two small values with two clear jobs beat one value that answers two different questions.\n *\n * ─── `unknown` is a value ─────────────────────────────────────────────────────────────────────────\n * A writer reached before any payload was parsed — the openclaw plugin, a library consumer, a spec —\n * renders `ai=unknown`, and so does every row written by a release older than this field. That is a real\n * value to count, not an absence and not a back-compat shim: see AI_TYPE_UNKNOWN.\n */\nexport class AiTypeContext {\n private aiType: AiType | null = null;\n\n /** Called once per invocation, by the adapter that parsed the payload. */\n identify(aiType: AiType): void {\n this.aiType = aiType;\n }\n\n /** The `ai=` field's value — the harness, or `unknown` when nothing established one. */\n forLog(): string {\n return this.aiType ?? AI_TYPE_UNKNOWN;\n }\n}\n\n/**\n * Process-wide instance, for the reason given above and in LogStream's own docblock: one process, one\n * tool call, one harness.\n */\nexport const aiTypeContext = new AiTypeContext();\n"]}
1
+ {"version":3,"file":"ai-type-context.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/core/ai-type-context.ts"],"names":[],"mappings":";;;AAAA,0DAAkE;AAElE;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAa,aAAa;IACd,MAAM,GAAkB,IAAI,CAAC;IAErC,0EAA0E;IAC1E,QAAQ,CAAC,MAAc;QACnB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACzB,CAAC;IAED,wFAAwF;IACxF,MAAM;QACF,OAAO,IAAI,CAAC,MAAM,IAAI,8BAAe,CAAC;IAC1C,CAAC;CACJ;AAZD,sCAYC;AAED;;;GAGG;AACU,QAAA,aAAa,GAAG,IAAI,aAAa,EAAE,CAAC","sourcesContent":["import { AiType, AI_TYPE_UNKNOWN } from '@webpieces/hook-runtime';\n\n/**\n * WHICH HARNESS this hook process is serving, for the four JS-side audit streams.\n *\n * ─── Why a process-wide holder and not a parameter ────────────────────────────────────────────────\n * One hook process handles exactly one tool call, so the harness is a property of the PROCESS, not of\n * any individual log line. Threading it as a parameter instead would have meant a new argument on\n * `logGuardDecision()`, `logL1Decision()`, `InvocationLog.finish()` and `logRejection()`, which between\n * them are constructed at fourteen call sites across eight guard modules — none of which has any\n * business knowing what a harness is. That is the identical argument `LogStream`'s docblock makes for\n * the session/agent/hook identity, and this is the identical shape: identified ONCE by the adapter that\n * parsed the payload, read by every writer downstream.\n *\n * ─── Why it is NOT folded into StreamIdentity ─────────────────────────────────────────────────────\n * `StreamIdentity` is defined as \"the three fields that make a log FILENAME unique\", and it crosses a\n * process boundary on argv (the detached main-sync refresher). The harness is neither: it never appears\n * in a filename, and a fourth field would have to be threaded through that argv round trip to mean\n * anything. Two small values with two clear jobs beat one value that answers two different questions.\n *\n * ─── `unknown` is a value ─────────────────────────────────────────────────────────────────────────\n * A writer reached before any payload was parsed — the openclaw plugin, a library consumer, a spec —\n * renders `ai=unknown`, and so does every row written by a release older than this field. That is a real\n * value to count, not an absence and not a back-compat shim: see AI_TYPE_UNKNOWN.\n */\nexport class AiTypeContext {\n private aiType: AiType | null = null;\n\n /** Called once per invocation, by the adapter that parsed the payload. */\n identify(aiType: AiType): void {\n this.aiType = aiType;\n }\n\n /** The `ai=` field's value — the harness, or `unknown` when nothing established one. */\n forLog(): string {\n return this.aiType ?? AI_TYPE_UNKNOWN;\n }\n}\n\n/**\n * Process-wide instance, for the reason given above and in LogStream's own docblock: one process, one\n * tool call, one harness.\n */\nexport const aiTypeContext = new AiTypeContext();\n"]}
@@ -1,4 +1,4 @@
1
- import { FileOperation } from './agent-event';
1
+ import { FileOperation } from '@webpieces/hook-runtime';
2
2
  /**
3
3
  * Parses Codex's `apply_patch` envelope into the same `FileOperation[]` the rest of the hook already
4
4
  * understands, so a Codex edit is judged by the identical rules a Claude edit is.
@@ -3,7 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ApplyPatchParser = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const path = tslib_1.__importStar(require("path"));
6
- const agent_event_1 = require("./agent-event");
6
+ const hook_runtime_1 = require("@webpieces/hook-runtime");
7
7
  const types_1 = require("./types");
8
8
  const BEGIN_PATCH = '*** Begin Patch';
9
9
  const END_PATCH = '*** End Patch';
@@ -53,7 +53,7 @@ class ApplyPatchParser {
53
53
  index = this.parseAdd(body, index, cwd, ops);
54
54
  }
55
55
  else if (line.startsWith(DELETE_FILE)) {
56
- ops.push(new agent_event_1.FileOperation('Delete', new types_1.NormalizedToolInput(this.resolve(line.slice(DELETE_FILE.length), cwd), [])));
56
+ ops.push(new hook_runtime_1.FileOperation('Delete', new types_1.NormalizedToolInput(this.resolve(line.slice(DELETE_FILE.length), cwd), [])));
57
57
  index += 1;
58
58
  }
59
59
  else if (line.startsWith(UPDATE_FILE)) {
@@ -84,7 +84,7 @@ class ApplyPatchParser {
84
84
  content.push(line.slice(1));
85
85
  index += 1;
86
86
  }
87
- ops.push(new agent_event_1.FileOperation('Write', new types_1.NormalizedToolInput(filePath, [new types_1.NormalizedEdit('', content.join('\n'))])));
87
+ ops.push(new hook_runtime_1.FileOperation('Write', new types_1.NormalizedToolInput(filePath, [new types_1.NormalizedEdit('', content.join('\n'))])));
88
88
  return index;
89
89
  }
90
90
  /**
@@ -139,7 +139,7 @@ class ApplyPatchParser {
139
139
  if (edits.length === 0) {
140
140
  throw new types_1.InformAiError(`[apply-patch] '${UPDATE_FILE.trim()}' section for ${filePath} carries no '@@' hunk — refusing to allow an edit whose content could not be read.`);
141
141
  }
142
- ops.push(new agent_event_1.FileOperation('Edit', new types_1.NormalizedToolInput(filePath, edits)));
142
+ ops.push(new hook_runtime_1.FileOperation('Edit', new types_1.NormalizedToolInput(filePath, edits)));
143
143
  return index;
144
144
  }
145
145
  resolve(rawPath, cwd) {
@@ -1 +1 @@
1
- {"version":3,"file":"apply-patch-parse.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/core/apply-patch-parse.ts"],"names":[],"mappings":";;;;AAAA,mDAA6B;AAE7B,+CAA8C;AAC9C,mCAA6E;AAE7E,MAAM,WAAW,GAAG,iBAAiB,CAAC;AACtC,MAAM,SAAS,GAAG,eAAe,CAAC;AAClC,MAAM,QAAQ,GAAG,gBAAgB,CAAC;AAClC,MAAM,WAAW,GAAG,mBAAmB,CAAC;AACxC,MAAM,WAAW,GAAG,mBAAmB,CAAC;AACxC,MAAM,OAAO,GAAG,eAAe,CAAC;AAChC,MAAM,WAAW,GAAG,IAAI,CAAC;AAEzB;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAa,gBAAgB;IACzB,KAAK,CAAC,OAAe,EAAE,GAAW;QAC9B,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAClC,MAAM,KAAK,GAAG,KAAK,CAAC,SAAS,CAAC,CAAC,CAAS,EAAW,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,KAAK,WAAW,CAAC,CAAC;QAChF,IAAI,KAAK,GAAG,CAAC,EAAE,CAAC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KAAK,CAAC,IAAI,CAAC,IAAI,sBAAc,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAC7E,CAAC;QACD,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACrB,MAAM,IAAI,qBAAa,CAAC,kBAAkB,WAAW,CAAC,IAAI,EAAE,iBAAiB,QAAQ,oFAAoF,CAAC,CAAC;QAC/K,CAAC;QACD,GAAG,CAAC,IAAI,CAAC,IAAI,2BAAa,CAAC,MAAM,EAAE,IAAI,2BAAmB,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC;QAC9E,OAAO,KAAK,CAAC;IACjB,CAAC;IAEO,OAAO,CAAC,OAAe,EAAE,GAAW;QACxC,MAAM,OAAO,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC;QAC/B,IAAI,OAAO,KAAK,EAAE,EAAE,CAAC;YACjB,MAAM,IAAI,qBAAa,CAAC,qDAAqD,CAAC,CAAC;QACnF,CAAC;QACD,OAAO,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;IAC3E,CAAC;CACJ;AAhHD,4CAgHC","sourcesContent":["import * as path from 'path';\n\nimport { FileOperation } from './agent-event';\nimport { NormalizedEdit, NormalizedToolInput, InformAiError } from './types';\n\nconst BEGIN_PATCH = '*** Begin Patch';\nconst END_PATCH = '*** End Patch';\nconst ADD_FILE = '*** Add File: ';\nconst UPDATE_FILE = '*** Update File: ';\nconst DELETE_FILE = '*** Delete File: ';\nconst MOVE_TO = '*** Move to: ';\nconst HUNK_HEADER = '@@';\n\n/**\n * Parses Codex's `apply_patch` envelope into the same `FileOperation[]` the rest of the hook already\n * understands, so a Codex edit is judged by the identical rules a Claude edit is.\n *\n * The grammar is MEASURED from a live codex-cli 0.151.0 session, not inferred from a diff format it\n * resembles. Two properties of it drive every design choice here:\n *\n * - ONE envelope carries MANY files with MIXED operations, which is why the result is a LIST of\n * `FileOperation` (each with its own kind) rather than one kind for the call.\n * - Hunk headers are a BARE `@@` with NO line numbers. A unified-diff `@@ -1,3 +1,4 @@` is therefore\n * not a stricter spelling of the same thing — it is an envelope we have never seen, and guessing at\n * it is how a guard silently judges the wrong bytes. It is rejected.\n *\n * Paths are sometimes relative and sometimes absolute (measured: subagents used relative, the\n * coordinator absolute), so a relative path is resolved against the payload's `cwd`.\n *\n * FAIL CLOSED. Every malformed envelope THROWS `InformAiError`, which the hook's one top-level handler\n * turns into a deny naming the offending line. A parser that \"did its best\" on an envelope it did not\n * understand would hand the rule engine a subset of the real edit and allow the rest unjudged, which is\n * strictly worse than refusing the call.\n */\nexport class ApplyPatchParser {\n parse(command: string, cwd: string): readonly FileOperation[] {\n const lines = command.split('\\n');\n const begin = lines.findIndex((l: string): boolean => l.trim() === BEGIN_PATCH);\n if (begin < 0) {\n throw new InformAiError(`[apply-patch] envelope has no '${BEGIN_PATCH}' line — refusing to judge a patch this parser does not recognise.`);\n }\n const end = lines.findIndex((l: string): boolean => l.trim() === END_PATCH);\n if (end < 0 || end < begin) {\n throw new InformAiError(`[apply-patch] envelope has no '${END_PATCH}' line after '${BEGIN_PATCH}' — refusing to judge a truncated patch.`);\n }\n\n const body = lines.slice(begin + 1, end);\n const ops: FileOperation[] = [];\n let index = 0;\n while (index < body.length) {\n const line = body[index];\n if (line.startsWith(ADD_FILE)) {\n index = this.parseAdd(body, index, cwd, ops);\n } else if (line.startsWith(DELETE_FILE)) {\n ops.push(new FileOperation('Delete', new NormalizedToolInput(this.resolve(line.slice(DELETE_FILE.length), cwd), [])));\n index += 1;\n } else if (line.startsWith(UPDATE_FILE)) {\n index = this.parseUpdate(body, index, cwd, ops);\n } else if (line.trim() === '') {\n index += 1;\n } else {\n throw new InformAiError(`[apply-patch] unexpected line outside any file section: ${JSON.stringify(line)}`);\n }\n }\n if (ops.length === 0) {\n throw new InformAiError('[apply-patch] envelope names no files — refusing to allow a patch whose targets could not be read.');\n }\n return ops;\n }\n\n /** `*** Add File: <p>` plus a body of `+` lines → a Write of the joined body. */\n private parseAdd(body: readonly string[], start: number, cwd: string, ops: FileOperation[]): number {\n const filePath = this.resolve(body[start].slice(ADD_FILE.length), cwd);\n const content: string[] = [];\n let index = start + 1;\n while (index < body.length && !body[index].startsWith('*** ')) {\n const line = body[index];\n if (!line.startsWith('+')) {\n throw new InformAiError(`[apply-patch] '${ADD_FILE.trim()}' body line must begin with '+', got ${JSON.stringify(line)}`);\n }\n content.push(line.slice(1));\n index += 1;\n }\n ops.push(new FileOperation('Write', new NormalizedToolInput(filePath, [new NormalizedEdit('', content.join('\\n'))])));\n return index;\n }\n\n /**\n * `*** Update File: <p>`, an optional `*** Move to: <q>`, then one or more bare-`@@` hunks.\n *\n * A `Move to` makes the DESTINATION the judged path. That is the file whose bytes will exist after\n * the call, so it is the one a path-scoped rule must see; judging the source would let a rename\n * into a guarded directory land unjudged.\n */\n private parseUpdate(body: readonly string[], start: number, cwd: string, ops: FileOperation[]): number {\n let index = start + 1;\n let filePath = this.resolve(body[start].slice(UPDATE_FILE.length), cwd);\n if (index < body.length && body[index].startsWith(MOVE_TO)) {\n filePath = this.resolve(body[index].slice(MOVE_TO.length), cwd);\n index += 1;\n }\n const edits: NormalizedEdit[] = [];\n while (index < body.length && !body[index].startsWith('*** ')) {\n const header = body[index];\n if (header.trim() !== HUNK_HEADER) {\n throw new InformAiError(`[apply-patch] malformed hunk header ${JSON.stringify(header)} — a Codex hunk header is a bare '@@' with no line numbers.`);\n }\n index += 1;\n const oldLines: string[] = [];\n const newLines: string[] = [];\n while (index < body.length && !body[index].startsWith('*** ') && body[index].trim() !== HUNK_HEADER) {\n const line = body[index];\n // A bare empty line is a CONTEXT line whose content is empty — the leading space is\n // routinely stripped by whatever carried the patch, so treating it as malformed would\n // deny ordinary edits to files with blank lines.\n if (line === '') {\n oldLines.push('');\n newLines.push('');\n } else if (line.startsWith(' ')) {\n oldLines.push(line.slice(1));\n newLines.push(line.slice(1));\n } else if (line.startsWith('-')) {\n oldLines.push(line.slice(1));\n } else if (line.startsWith('+')) {\n newLines.push(line.slice(1));\n } else {\n throw new InformAiError(`[apply-patch] hunk line must begin with ' ', '-' or '+', got ${JSON.stringify(line)}`);\n }\n index += 1;\n }\n edits.push(new NormalizedEdit(oldLines.join('\\n'), newLines.join('\\n')));\n }\n if (edits.length === 0) {\n throw new InformAiError(`[apply-patch] '${UPDATE_FILE.trim()}' section for ${filePath} carries no '@@' hunk — refusing to allow an edit whose content could not be read.`);\n }\n ops.push(new FileOperation('Edit', new NormalizedToolInput(filePath, edits)));\n return index;\n }\n\n private resolve(rawPath: string, cwd: string): string {\n const trimmed = rawPath.trim();\n if (trimmed === '') {\n throw new InformAiError('[apply-patch] a file directive named an empty path.');\n }\n return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);\n }\n}\n"]}
1
+ {"version":3,"file":"apply-patch-parse.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/core/apply-patch-parse.ts"],"names":[],"mappings":";;;;AAAA,mDAA6B;AAE7B,0DAAwD;AACxD,mCAA6E;AAE7E,MAAM,WAAW,GAAG,iBAAiB,CAAC;AACtC,MAAM,SAAS,GAAG,eAAe,CAAC;AAClC,MAAM,QAAQ,GAAG,gBAAgB,CAAC;AAClC,MAAM,WAAW,GAAG,mBAAmB,CAAC;AACxC,MAAM,WAAW,GAAG,mBAAmB,CAAC;AACxC,MAAM,OAAO,GAAG,eAAe,CAAC;AAChC,MAAM,WAAW,GAAG,IAAI,CAAC;AAEzB;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAa,gBAAgB;IACzB,KAAK,CAAC,OAAe,EAAE,GAAW;QAC9B,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAClC,MAAM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C;oBACJ,MAAM,IAAI,qBAAa,CAAC,gEAAgE,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;gBACpH,CAAC;gBACD,KAAK,IAAI,CAAC,CAAC;YACf,CAAC;YACD,KAAK,CAAC,IAAI,CAAC,IAAI,sBAAc,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAC7E,CAAC;QACD,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACrB,MAAM,IAAI,qBAAa,CAAC,kBAAkB,WAAW,CAAC,IAAI,EAAE,iBAAiB,QAAQ,oFAAoF,CAAC,CAAC;QAC/K,CAAC;QACD,GAAG,CAAC,IAAI,CAAC,IAAI,4BAAa,CAAC,MAAM,EAAE,IAAI,2BAAmB,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC;QAC9E,OAAO,KAAK,CAAC;IACjB,CAAC;IAEO,OAAO,CAAC,OAAe,EAAE,GAAW;QACxC,MAAM,OAAO,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC;QAC/B,IAAI,OAAO,KAAK,EAAE,EAAE,CAAC;YACjB,MAAM,IAAI,qBAAa,CAAC,qDAAqD,CAAC,CAAC;QACnF,CAAC;QACD,OAAO,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;IAC3E,CAAC;CACJ;AAhHD,4CAgHC","sourcesContent":["import * as path from 'path';\n\nimport { FileOperation } from '@webpieces/hook-runtime';\nimport { NormalizedEdit, NormalizedToolInput, InformAiError } from './types';\n\nconst BEGIN_PATCH = '*** Begin Patch';\nconst END_PATCH = '*** End Patch';\nconst ADD_FILE = '*** Add File: ';\nconst UPDATE_FILE = '*** Update File: ';\nconst DELETE_FILE = '*** Delete File: ';\nconst MOVE_TO = '*** Move to: ';\nconst HUNK_HEADER = '@@';\n\n/**\n * Parses Codex's `apply_patch` envelope into the same `FileOperation[]` the rest of the hook already\n * understands, so a Codex edit is judged by the identical rules a Claude edit is.\n *\n * The grammar is MEASURED from a live codex-cli 0.151.0 session, not inferred from a diff format it\n * resembles. Two properties of it drive every design choice here:\n *\n * - ONE envelope carries MANY files with MIXED operations, which is why the result is a LIST of\n * `FileOperation` (each with its own kind) rather than one kind for the call.\n * - Hunk headers are a BARE `@@` with NO line numbers. A unified-diff `@@ -1,3 +1,4 @@` is therefore\n * not a stricter spelling of the same thing — it is an envelope we have never seen, and guessing at\n * it is how a guard silently judges the wrong bytes. It is rejected.\n *\n * Paths are sometimes relative and sometimes absolute (measured: subagents used relative, the\n * coordinator absolute), so a relative path is resolved against the payload's `cwd`.\n *\n * FAIL CLOSED. Every malformed envelope THROWS `InformAiError`, which the hook's one top-level handler\n * turns into a deny naming the offending line. A parser that \"did its best\" on an envelope it did not\n * understand would hand the rule engine a subset of the real edit and allow the rest unjudged, which is\n * strictly worse than refusing the call.\n */\nexport class ApplyPatchParser {\n parse(command: string, cwd: string): readonly FileOperation[] {\n const lines = command.split('\\n');\n const begin = lines.findIndex((l: string): boolean => l.trim() === BEGIN_PATCH);\n if (begin < 0) {\n throw new InformAiError(`[apply-patch] envelope has no '${BEGIN_PATCH}' line — refusing to judge a patch this parser does not recognise.`);\n }\n const end = lines.findIndex((l: string): boolean => l.trim() === END_PATCH);\n if (end < 0 || end < begin) {\n throw new InformAiError(`[apply-patch] envelope has no '${END_PATCH}' line after '${BEGIN_PATCH}' — refusing to judge a truncated patch.`);\n }\n\n const body = lines.slice(begin + 1, end);\n const ops: FileOperation[] = [];\n let index = 0;\n while (index < body.length) {\n const line = body[index];\n if (line.startsWith(ADD_FILE)) {\n index = this.parseAdd(body, index, cwd, ops);\n } else if (line.startsWith(DELETE_FILE)) {\n ops.push(new FileOperation('Delete', new NormalizedToolInput(this.resolve(line.slice(DELETE_FILE.length), cwd), [])));\n index += 1;\n } else if (line.startsWith(UPDATE_FILE)) {\n index = this.parseUpdate(body, index, cwd, ops);\n } else if (line.trim() === '') {\n index += 1;\n } else {\n throw new InformAiError(`[apply-patch] unexpected line outside any file section: ${JSON.stringify(line)}`);\n }\n }\n if (ops.length === 0) {\n throw new InformAiError('[apply-patch] envelope names no files — refusing to allow a patch whose targets could not be read.');\n }\n return ops;\n }\n\n /** `*** Add File: <p>` plus a body of `+` lines → a Write of the joined body. */\n private parseAdd(body: readonly string[], start: number, cwd: string, ops: FileOperation[]): number {\n const filePath = this.resolve(body[start].slice(ADD_FILE.length), cwd);\n const content: string[] = [];\n let index = start + 1;\n while (index < body.length && !body[index].startsWith('*** ')) {\n const line = body[index];\n if (!line.startsWith('+')) {\n throw new InformAiError(`[apply-patch] '${ADD_FILE.trim()}' body line must begin with '+', got ${JSON.stringify(line)}`);\n }\n content.push(line.slice(1));\n index += 1;\n }\n ops.push(new FileOperation('Write', new NormalizedToolInput(filePath, [new NormalizedEdit('', content.join('\\n'))])));\n return index;\n }\n\n /**\n * `*** Update File: <p>`, an optional `*** Move to: <q>`, then one or more bare-`@@` hunks.\n *\n * A `Move to` makes the DESTINATION the judged path. That is the file whose bytes will exist after\n * the call, so it is the one a path-scoped rule must see; judging the source would let a rename\n * into a guarded directory land unjudged.\n */\n private parseUpdate(body: readonly string[], start: number, cwd: string, ops: FileOperation[]): number {\n let index = start + 1;\n let filePath = this.resolve(body[start].slice(UPDATE_FILE.length), cwd);\n if (index < body.length && body[index].startsWith(MOVE_TO)) {\n filePath = this.resolve(body[index].slice(MOVE_TO.length), cwd);\n index += 1;\n }\n const edits: NormalizedEdit[] = [];\n while (index < body.length && !body[index].startsWith('*** ')) {\n const header = body[index];\n if (header.trim() !== HUNK_HEADER) {\n throw new InformAiError(`[apply-patch] malformed hunk header ${JSON.stringify(header)} — a Codex hunk header is a bare '@@' with no line numbers.`);\n }\n index += 1;\n const oldLines: string[] = [];\n const newLines: string[] = [];\n while (index < body.length && !body[index].startsWith('*** ') && body[index].trim() !== HUNK_HEADER) {\n const line = body[index];\n // A bare empty line is a CONTEXT line whose content is empty — the leading space is\n // routinely stripped by whatever carried the patch, so treating it as malformed would\n // deny ordinary edits to files with blank lines.\n if (line === '') {\n oldLines.push('');\n newLines.push('');\n } else if (line.startsWith(' ')) {\n oldLines.push(line.slice(1));\n newLines.push(line.slice(1));\n } else if (line.startsWith('-')) {\n oldLines.push(line.slice(1));\n } else if (line.startsWith('+')) {\n newLines.push(line.slice(1));\n } else {\n throw new InformAiError(`[apply-patch] hunk line must begin with ' ', '-' or '+', got ${JSON.stringify(line)}`);\n }\n index += 1;\n }\n edits.push(new NormalizedEdit(oldLines.join('\\n'), newLines.join('\\n')));\n }\n if (edits.length === 0) {\n throw new InformAiError(`[apply-patch] '${UPDATE_FILE.trim()}' section for ${filePath} carries no '@@' hunk — refusing to allow an edit whose content could not be read.`);\n }\n ops.push(new FileOperation('Edit', new NormalizedToolInput(filePath, edits)));\n return index;\n }\n\n private resolve(rawPath: string, cwd: string): string {\n const trimmed = rawPath.trim();\n if (trimmed === '') {\n throw new InformAiError('[apply-patch] a file directive named an empty path.');\n }\n return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { AiType } from './agent-event';
1
+ import { AiType } from '@webpieces/hook-runtime';
2
2
  import { ToolKind, NormalizedToolInput, BlockedResult, HookMode, Rule, Violation, EditContext, FileContext, BashContext } from './types';
3
3
  export declare function effectiveBashCwd(command: string, cwd: string): string;
4
4
  export declare function isGitOrGhCommand(command: string): boolean;