@webpieces/agent-workflow-rules 0.4.916 → 0.4.918

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 +1 -1
  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 +1 -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 +8 -8
  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 +3 -3
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webpieces/agent-workflow-rules",
3
- "version": "0.4.916",
3
+ "version": "0.4.918",
4
4
  "description": "Independent workflow guards, guard hook, installation and shim management for AI coding agents.",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -24,20 +24,20 @@
24
24
  "directory": "packages/tooling/agent-workflow-rules"
25
25
  },
26
26
  "dependencies": {
27
- "@webpieces/hook-runtime": "0.4.916",
28
- "@webpieces/rules-config": "0.4.916",
27
+ "@webpieces/hook-runtime": "0.4.918",
28
+ "@webpieces/rules-config": "0.4.918",
29
29
  "inversify": "7.10.4",
30
30
  "reflect-metadata": "0.2.2",
31
- "@webpieces/tooling-common": "0.4.916",
32
- "@webpieces/repo-workflow-core": "0.4.916",
31
+ "@webpieces/tooling-common": "0.4.918",
32
+ "@webpieces/repo-workflow-core": "0.4.918",
33
33
  "tslib": "2.8.1",
34
- "@webpieces/rules-sdk": "0.4.916"
34
+ "@webpieces/rules-sdk": "0.4.918"
35
35
  },
36
36
  "publishConfig": {
37
37
  "access": "public"
38
38
  },
39
39
  "devDependencies": {
40
- "@webpieces/tooling-testkit": "0.4.916"
40
+ "@webpieces/tooling-testkit": "0.4.918"
41
41
  },
42
42
  "types": "./src/index.d.ts",
43
43
  "bin": {
@@ -18,7 +18,7 @@ export declare const CODEX_SUBAGENT_RULE = "codex-subagent-no-write-in-shared-tr
18
18
  * "hand the edit back to the coordinator" option and wrote all five verdicts itself, and the gate
19
19
  * accepted them (issue #863). So a verdict is never a patch: every reviewer SUBMITS it through
20
20
  * `pnpm wp-write-review`, a Bash call this guard does not see, and a blocked write under
21
- * `.webpieces-logs/pr-review/` names that bin — and NEVER offers the coordinator hand-back, because a
21
+ * `.webpieces/pr-review/` names that bin — and NEVER offers the coordinator hand-back, because a
22
22
  * coordinator writing a reviewer's verdict is precisely the forgery the gate refuses.
23
23
  *
24
24
  * NOT a configurable rule yet, and that is deliberate. A rule registered with the engine must have an
@@ -34,7 +34,7 @@ export declare class CodexSubagentSharedTreeGuard {
34
34
  */
35
35
  check(event: AgentHookEvent, root: string): BlockedResult | null;
36
36
  /**
37
- * A write under `.webpieces-logs/pr-review/` — a verdict, or anything beside one. There is exactly one
37
+ * A write under `.webpieces/pr-review/` — a verdict, or anything beside one. There is exactly one
38
38
  * route for it, and it is not a patch. No "hand it to the coordinator" option: the coordinator may
39
39
  * never write a reviewer's verdict, and `wp-finish-upsert-pr` rejects one that did not come through
40
40
  * the bin.
@@ -25,7 +25,7 @@ exports.CODEX_SUBAGENT_RULE = 'codex-subagent-no-write-in-shared-tree';
25
25
  * "hand the edit back to the coordinator" option and wrote all five verdicts itself, and the gate
26
26
  * accepted them (issue #863). So a verdict is never a patch: every reviewer SUBMITS it through
27
27
  * `pnpm wp-write-review`, a Bash call this guard does not see, and a blocked write under
28
- * `.webpieces-logs/pr-review/` names that bin — and NEVER offers the coordinator hand-back, because a
28
+ * `.webpieces/pr-review/` names that bin — and NEVER offers the coordinator hand-back, because a
29
29
  * coordinator writing a reviewer's verdict is precisely the forgery the gate refuses.
30
30
  *
31
31
  * NOT a configurable rule yet, and that is deliberate. A rule registered with the engine must have an
@@ -62,7 +62,7 @@ class CodexSubagentSharedTreeGuard {
62
62
  return new hook_runtime_1.BlockedResult((0, rules_config_1.renderRuleFailForAi)(error));
63
63
  }
64
64
  /**
65
- * A write under `.webpieces-logs/pr-review/` — a verdict, or anything beside one. There is exactly one
65
+ * A write under `.webpieces/pr-review/` — a verdict, or anything beside one. There is exactly one
66
66
  * route for it, and it is not a patch. No "hand it to the coordinator" option: the coordinator may
67
67
  * never write a reviewer's verdict, and `wp-finish-upsert-pr` rejects one that did not come through
68
68
  * the bin.
@@ -1 +1 @@
1
- {"version":3,"file":"codex-subagent-guard.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/adapters/codex-subagent-guard.ts"],"names":[],"mappings":";;;;AAAA,mDAA6B;AAE7B,0DAAqF;AACrF,8DAA6E;AAC7E,sEAAiE;AAGjE,0DAAwD;AAE3C,QAAA,mBAAmB,GAAG,wCAAwC,CAAC;AAE5E;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,MAAa,4BAA4B;IACrC;;;OAGG;IACH,KAAK,CAAC,KAAqB,EAAE,IAAY;QACrC,IAAI,KAAK,CAAC,MAAM,KAAK,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AC,IAAA,kCAAmB,EAAC,KAAK,CAAC,CAAC,CAAC;IACzD,CAAC;IAED;;;;;OAKG;IACK,iBAAiB,CAAC,OAAe;QACrC,OAAO,IAAI,4BAAa,CACpB,2BAAmB,EACnB,sDAAsD,OAAO,MAAM;YACnE,oEAAoE,qCAAgB,UAAU;YAC9F,wGAAwG;YACxG,8BAA8B,EAC9B,SAAS,EACT,SAAS,EACT;YACI,IAAI,qBAAM,CAAC,0CAA0C,qCAAgB,wEAAwE,EAAE,IAAI,CAAC;SACvJ,CACJ,CAAC;IACN,CAAC;IAEO,aAAa,CAAC,QAAgB,EAAE,IAAY;QAChD,MAAM,SAAS,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,kCAAiB,EAAE,8BAAa,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC;QAC/E,OAAO,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,UAAU,CAAC,SAAS,CAAC,CAAC;IACxD,CAAC;IAEO,QAAQ,CAAC,QAAgB,EAAE,IAAY;QAC3C,MAAM,WAAW,GAAG,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC;QACrE,OAAO,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC;IAC1D,CAAC;CACJ;AA7DD,oEA6DC","sourcesContent":["import * as path from 'path';\n\nimport { Option, RuleFailError, renderRuleFailForAi } from '@webpieces/rules-config';\nimport { PR_REVIEW_DIR, WEBPIECES_TMP_DIR } from '@webpieces/tooling-common';\nimport { WRITE_REVIEW_BIN } from '@webpieces/repo-workflow-core';\n\nimport { AgentHookEvent, FileOperation } from '@webpieces/hook-runtime';\nimport { BlockedResult } from '@webpieces/hook-runtime';\n\nexport const CODEX_SUBAGENT_RULE = 'codex-subagent-no-write-in-shared-tree';\n\n/**\n * A Codex SUBAGENT may not write into the tree it shares with its coordinator.\n *\n * This exists because of a MEASURED structural gap, not a style preference. Claude Code can hand a\n * subagent its own git worktree (`isolation: \"worktree\"`), so two agents editing at once are editing\n * two different checkouts. Codex cannot: `spawn_agent`'s schema is\n * `{fork_turns?, message, model?, reasoning_effort?, task_name}` — there is no cwd, workdir or\n * worktree parameter — and cwd resets to the repo root before every command, so a subagent cannot even\n * put itself somewhere else. Every Codex subagent therefore writes into the coordinator's checkout,\n * and concurrent subagents write into each other's.\n *\n * Reviewers WRITE too, and that is not a side detail: one verdict per checklist is a reviewer's whole\n * output. An earlier comment here said \"reviewers are unaffected: they only read\", and it was false —\n * this guard blocked a Codex reviewer's `review-<id>.json`, the coordinator then took this guard's own\n * \"hand the edit back to the coordinator\" option and wrote all five verdicts itself, and the gate\n * accepted them (issue #863). So a verdict is never a patch: every reviewer SUBMITS it through\n * `pnpm wp-write-review`, a Bash call this guard does not see, and a blocked write under\n * `.webpieces-logs/pr-review/` names that bin — and NEVER offers the coordinator hand-back, because a\n * coordinator writing a reviewer's verdict is precisely the forgery the gate refuses.\n *\n * NOT a configurable rule yet, and that is deliberate. A rule registered with the engine must have an\n * entry in webpieces.config.json, and the validator that would accept a new key is a RELEASE behind\n * the source that defines it — adding both at once rejects the key as unknown and blocks every tool\n * call in the repo. So the guard ships here, gated on `aiType === 'codex'`, and becomes a config-keyed\n * rule in the follow-up PR that lands after the publish.\n */\nexport class CodexSubagentSharedTreeGuard {\n /**\n * Returns a block when a Codex SUBAGENT's patch targets a file inside `root`, else null.\n * Claude Code events return null unconditionally — the harness has real isolation.\n */\n check(event: AgentHookEvent, root: string): BlockedResult | null {\n if (event.aiType !== 'codex') return null;\n if (event.agentId === '') return null;\n const inside = event.files.filter((f: FileOperation): boolean => this.isInside(f.input.filePath, root));\n if (inside.length === 0) return null;\n const targets = inside.map((f: FileOperation): string => path.relative(root, f.input.filePath)).join(', ');\n if (inside.some((f: FileOperation): boolean => this.isReviewState(f.input.filePath, root))) {\n return new BlockedResult(renderRuleFailForAi(this.verdictWriteError(targets)));\n }\n const worktree = path.join(path.dirname(root), 'wt-<task-name>');\n const error = new RuleFailError(\n CODEX_SUBAGENT_RULE,\n `A Codex subagent is writing into the tree it shares with its coordinator: ${targets}\\n\\n` +\n `Codex cannot spawn a subagent into its own checkout — spawn_agent takes no cwd or worktree, ` +\n `and cwd resets to the repo root before every command — so this edit lands in the same files ` +\n `the coordinator and every sibling subagent are editing.`,\n undefined,\n undefined,\n [\n new Option(`Give this agent its own checkout and address every file by ABSOLUTE path inside it: git worktree add ${worktree} -b <branch>`, true),\n new Option('Hand the edit back to the coordinator and have this agent report what to change instead of changing it'),\n ],\n );\n return new BlockedResult(renderRuleFailForAi(error));\n }\n\n /**\n * A write under `.webpieces-logs/pr-review/` — a verdict, or anything beside one. There is exactly one\n * route for it, and it is not a patch. No \"hand it to the coordinator\" option: the coordinator may\n * never write a reviewer's verdict, and `wp-finish-upsert-pr` rejects one that did not come through\n * the bin.\n */\n private verdictWriteError(targets: string): RuleFailError {\n return new RuleFailError(\n CODEX_SUBAGENT_RULE,\n `A Codex subagent is writing review state directly: ${targets}\\n\\n` +\n `A reviewer verdict is never written as a file. Submit it through ${WRITE_REVIEW_BIN}, which ` +\n `validates it and records who wrote it — a review-round<N>-<id>.json written any other way is rejected ` +\n `by pnpm wp-finish-upsert-pr.`,\n undefined,\n undefined,\n [\n new Option(`Submit the verdict JSON on stdin: pnpm ${WRITE_REVIEW_BIN} --checklist <id> <<'EOF' … EOF (or --file <a path OUTSIDE this tree>)`, true),\n ],\n );\n }\n\n private isReviewState(filePath: string, root: string): boolean {\n const reviewDir = path.join(root, WEBPIECES_TMP_DIR, PR_REVIEW_DIR) + path.sep;\n return path.resolve(filePath).startsWith(reviewDir);\n }\n\n private isInside(filePath: string, root: string): boolean {\n const rootWithSep = root.endsWith(path.sep) ? root : root + path.sep;\n return path.resolve(filePath).startsWith(rootWithSep);\n }\n}\n"]}
1
+ {"version":3,"file":"cod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AW,CAAC,CAAC;IAC1D,CAAC;CACJ;AA7DD,oEA6DC","sourcesContent":["import * as path from 'path';\n\nimport { Option, RuleFailError, renderRuleFailForAi } from '@webpieces/rules-config';\nimport { PR_REVIEW_DIR, WEBPIECES_TMP_DIR } from '@webpieces/tooling-common';\nimport { WRITE_REVIEW_BIN } from '@webpieces/repo-workflow-core';\n\nimport { AgentHookEvent, FileOperation } from '@webpieces/hook-runtime';\nimport { BlockedResult } from '@webpieces/hook-runtime';\n\nexport const CODEX_SUBAGENT_RULE = 'codex-subagent-no-write-in-shared-tree';\n\n/**\n * A Codex SUBAGENT may not write into the tree it shares with its coordinator.\n *\n * This exists because of a MEASURED structural gap, not a style preference. Claude Code can hand a\n * subagent its own git worktree (`isolation: \"worktree\"`), so two agents editing at once are editing\n * two different checkouts. Codex cannot: `spawn_agent`'s schema is\n * `{fork_turns?, message, model?, reasoning_effort?, task_name}` — there is no cwd, workdir or\n * worktree parameter — and cwd resets to the repo root before every command, so a subagent cannot even\n * put itself somewhere else. Every Codex subagent therefore writes into the coordinator's checkout,\n * and concurrent subagents write into each other's.\n *\n * Reviewers WRITE too, and that is not a side detail: one verdict per checklist is a reviewer's whole\n * output. An earlier comment here said \"reviewers are unaffected: they only read\", and it was false —\n * this guard blocked a Codex reviewer's `review-<id>.json`, the coordinator then took this guard's own\n * \"hand the edit back to the coordinator\" option and wrote all five verdicts itself, and the gate\n * accepted them (issue #863). So a verdict is never a patch: every reviewer SUBMITS it through\n * `pnpm wp-write-review`, a Bash call this guard does not see, and a blocked write under\n * `.webpieces/pr-review/` names that bin — and NEVER offers the coordinator hand-back, because a\n * coordinator writing a reviewer's verdict is precisely the forgery the gate refuses.\n *\n * NOT a configurable rule yet, and that is deliberate. A rule registered with the engine must have an\n * entry in webpieces.config.json, and the validator that would accept a new key is a RELEASE behind\n * the source that defines it — adding both at once rejects the key as unknown and blocks every tool\n * call in the repo. So the guard ships here, gated on `aiType === 'codex'`, and becomes a config-keyed\n * rule in the follow-up PR that lands after the publish.\n */\nexport class CodexSubagentSharedTreeGuard {\n /**\n * Returns a block when a Codex SUBAGENT's patch targets a file inside `root`, else null.\n * Claude Code events return null unconditionally — the harness has real isolation.\n */\n check(event: AgentHookEvent, root: string): BlockedResult | null {\n if (event.aiType !== 'codex') return null;\n if (event.agentId === '') return null;\n const inside = event.files.filter((f: FileOperation): boolean => this.isInside(f.input.filePath, root));\n if (inside.length === 0) return null;\n const targets = inside.map((f: FileOperation): string => path.relative(root, f.input.filePath)).join(', ');\n if (inside.some((f: FileOperation): boolean => this.isReviewState(f.input.filePath, root))) {\n return new BlockedResult(renderRuleFailForAi(this.verdictWriteError(targets)));\n }\n const worktree = path.join(path.dirname(root), 'wt-<task-name>');\n const error = new RuleFailError(\n CODEX_SUBAGENT_RULE,\n `A Codex subagent is writing into the tree it shares with its coordinator: ${targets}\\n\\n` +\n `Codex cannot spawn a subagent into its own checkout — spawn_agent takes no cwd or worktree, ` +\n `and cwd resets to the repo root before every command — so this edit lands in the same files ` +\n `the coordinator and every sibling subagent are editing.`,\n undefined,\n undefined,\n [\n new Option(`Give this agent its own checkout and address every file by ABSOLUTE path inside it: git worktree add ${worktree} -b <branch>`, true),\n new Option('Hand the edit back to the coordinator and have this agent report what to change instead of changing it'),\n ],\n );\n return new BlockedResult(renderRuleFailForAi(error));\n }\n\n /**\n * A write under `.webpieces/pr-review/` — a verdict, or anything beside one. There is exactly one\n * route for it, and it is not a patch. No \"hand it to the coordinator\" option: the coordinator may\n * never write a reviewer's verdict, and `wp-finish-upsert-pr` rejects one that did not come through\n * the bin.\n */\n private verdictWriteError(targets: string): RuleFailError {\n return new RuleFailError(\n CODEX_SUBAGENT_RULE,\n `A Codex subagent is writing review state directly: ${targets}\\n\\n` +\n `A reviewer verdict is never written as a file. Submit it through ${WRITE_REVIEW_BIN}, which ` +\n `validates it and records who wrote it — a review-round<N>-<id>.json written any other way is rejected ` +\n `by pnpm wp-finish-upsert-pr.`,\n undefined,\n undefined,\n [\n new Option(`Submit the verdict JSON on stdin: pnpm ${WRITE_REVIEW_BIN} --checklist <id> <<'EOF' … EOF (or --file <a path OUTSIDE this tree>)`, true),\n ],\n );\n }\n\n private isReviewState(filePath: string, root: string): boolean {\n const reviewDir = path.join(root, WEBPIECES_TMP_DIR, PR_REVIEW_DIR) + path.sep;\n return path.resolve(filePath).startsWith(reviewDir);\n }\n\n private isInside(filePath: string, root: string): boolean {\n const rootWithSep = root.endsWith(path.sep) ? root : root + path.sep;\n return path.resolve(filePath).startsWith(rootWithSep);\n }\n}\n"]}
@@ -50,7 +50,7 @@ export declare const GOLDEN_FIXTURES: readonly GoldenFixture[];
50
50
  /**
51
51
  * Builds ONE throwaway git repo per fixture and returns it with the payload's `<REPO>` resolved.
52
52
  *
53
- * A FRESH repo per fixture, not one shared: the hook writes `.webpieces-logs/` state (the decision log, the
53
+ * A FRESH repo per fixture, not one shared: the hook writes `.webpieces/` state (the decision log, the
54
54
  * main-sync cache) as it runs, so a shared tree would let fixture N's leftovers decide fixture N+1's
55
55
  * verdict — an order-dependent suite, which is the one kind of golden test worse than none.
56
56
  *
@@ -132,7 +132,7 @@ const CRASHING_RULE_MODULE = "throw new Error('boom from a custom rule module');
132
132
  /**
133
133
  * Builds ONE throwaway git repo per fixture and returns it with the payload's `<REPO>` resolved.
134
134
  *
135
- * A FRESH repo per fixture, not one shared: the hook writes `.webpieces-logs/` state (the decision log, the
135
+ * A FRESH repo per fixture, not one shared: the hook writes `.webpieces/` state (the decision log, the
136
136
  * main-sync cache) as it runs, so a shared tree would let fixture N's leftovers decide fixture N+1's
137
137
  * verdict — an order-dependent suite, which is the one kind of golden test worse than none.
138
138
  *
@@ -1 +1 @@
1
- {"version":3,"file":"hook-app-fixtures.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/adapters/hook-app-fixtures.ts"],"names":[],"mappings":";;;;AAAA,oDAO8B;AAC9B,4CAAgD;AAChD,gEAA2D;AAC3D,gEAA0D;AAC1D,iDAAyC;AACz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pieces/rules-sdk';\nimport { rulePackManifest } from '../rule-pack';\nimport { policyFixture } from '@webpieces/tooling-testkit';\nimport { specTempDirs } from '@webpieces/tooling-testkit';\nimport { execSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\n\nimport { HookMode } from '@webpieces/hook-runtime';\n\n/**\n * THE WIRE BYTES the golden tests drive, and the throwaway repo they are judged against.\n *\n * Everything here exists so a reader can see EXACTLY what a harness sends: the payloads are built from\n * the measured envelope key sets (see the fixture docs on GoldenFixture below), not from anything the\n * hook itself produces, and the repo is a real `git init` with a frozen webpieces.config.json rather\n * than whatever tree the suite happens to be running in. A golden computed against the live repo would\n * change verdict with the branch you are standing on.\n *\n * This is NOT a spec file, deliberately: `tsconfig.lib.json` excludes `*.spec.ts`, so a payload builder\n * living in one would never be type-checked by the build.\n */\n\n/** How one PreToolUse call is presented to the hook. Data class per CLAUDE.md rule 1. */\nexport class GoldenFixture {\n /** Stable key into `__goldens__/hook-app-goldens.json`. */\n readonly name: string;\n /** Which hook binary's mode — `guards` or `rules`. */\n readonly mode: HookMode;\n /**\n * The raw stdin bytes. A STRING, never an object, because malformed stdin is one of the fixtures\n * and a shape that cannot express \"not JSON\" would quietly drop the case that matters most.\n */\n readonly stdin: string;\n /** True ⇒ the fixture repo also gets a `rulesDir` whose one module throws when required. */\n readonly crashingRuntime: boolean;\n\n constructor(name: string, mode: HookMode, stdin: string, crashingRuntime: boolean = false) {\n this.name = name;\n this.mode = mode;\n this.stdin = stdin;\n this.crashingRuntime = crashingRuntime;\n }\n}\n\n/** A built fixture repo: where it lives, and the stdin bytes with `<REPO>` resolved into it. */\nexport class PreparedFixture {\n readonly repo: string;\n readonly root: string;\n readonly stdin: string;\n\n constructor(repo: string, root: string, stdin: string) {\n this.repo = repo;\n this.root = root;\n this.stdin = stdin;\n }\n}\n\n/**\n * The placeholder that stands for the fixture repo's absolute path, in BOTH directions: payloads are\n * written with it and it is substituted in before the run; golden bytes are compared with the real\n * path substituted back out. Guard reports legitimately name absolute paths (the git-workflow doc\n * pointer, the blocked file), and a golden that hard-coded one machine's `/var/folders/...` would be\n * a golden nobody else could run.\n */\nexport const REPO_TOKEN = '<REPO>';\n\nconst CLAUDE_ENVELOPE = {\n hook_event_name: 'PreToolUse',\n session_id: 'sess-golden',\n transcript_path: '/dev/null',\n cwd: REPO_TOKEN,\n};\n\n/**\n * The Codex additions, MEASURED from codex-cli 0.151.0: it uses Claude's key names and merely ADDS\n * `model`, `turn_id`, `tool_use_id` and `permission_mode`. `turn_id` is the one discriminator (see\n * detect-ai.ts). `agent_id` empty ⇒ the coordinator, populated ⇒ a subagent — identical semantics in\n * both harnesses.\n */\nconst CODEX_ENVELOPE = {\n ...CLAUDE_ENVELOPE,\n model: 'gpt-5-codex',\n turn_id: 'turn-golden',\n tool_use_id: 'call_1',\n permission_mode: 'default',\n agent_type: 'default',\n agent_id: '',\n};\n\n// Codex's edit tool. MEASURED: the tool is named `apply_patch`, it carries `tool_input.command` (not\n// file_path), hunk headers are a bare `@@`, and ONE patch may carry many files with mixed operations.\nconst PATCH_ADD_JS = '*** Begin Patch\\n*** Add File: src/foo.js\\n+var x = 1;\\n*** End Patch\\n';\nconst PATCH_ADD_TS =\n '*** Begin Patch\\n*** Add File: scripts/added.ts\\n+export const b = 2;\\n*** End Patch\\n';\n\n/**\n * Serializes ONE PreToolUse envelope to the bytes a harness would put on stdin. A class rather than a\n * module-scope function because that is the repo rule, and the one instance below is built at module\n * load so the fixture table can stay a plain literal list.\n */\nclass WirePayload {\n // webpieces-disable no-any-unknown -- these objects ARE the wire envelope; JSON.stringify of a plain object is the payload under test, and naming a type for it would assert a shape the fixtures exist to state literally\n write(\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n envelope: Record<string, unknown>,\n toolName: string,\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n toolInput: Record<string, unknown>,\n ): string {\n return JSON.stringify({ ...envelope, tool_name: toolName, tool_input: toolInput });\n }\n}\n\nconst WIRE = new WirePayload();\n\n/**\n * ONE fixture per row of the coverage the composed pipeline had none of before: for BOTH harnesses a\n * Bash deny (the ANSI-red systemMessage), a file-tool deny (NO systemMessage), an allow, a read-only\n * tool, malformed stdin, and a fail-closed crash.\n */\nexport const GOLDEN_FIXTURES: readonly GoldenFixture[] = [\n // ── Claude Code ────────────────────────────────────────────────────────────────────────────────\n // A Bash deny. `git merge` is blocked on every branch, so this verdict does not depend on repo\n // state — and a Bash deny is the ONE case that carries the red `systemMessage`.\n new GoldenFixture(\n 'claude/bash-deny',\n 'guards',\n WIRE.write(CLAUDE_ENVELOPE, 'Bash', { command: 'git merge main' }),\n ),\n new GoldenFixture(\n 'claude/bash-allow',\n 'guards',\n WIRE.write(CLAUDE_ENVELOPE, 'Bash', { command: 'echo hi' }),\n ),\n // The read-only tool: log-and-allow, and the only guard that can deny it is a stale `main`.\n new GoldenFixture(\n 'claude/read-allow',\n 'guards',\n WIRE.write(CLAUDE_ENVELOPE, 'Read', { file_path: `${REPO_TOKEN}/f.txt` }),\n ),\n // Write / Edit / MultiEdit denies — all three must emit NO systemMessage.\n new GoldenFixture('claude/malformed', 'guards', 'not json at all'),\n\n // ── Codex ──────────────────────────────────────────────────────────────────────────────────────\n new GoldenFixture(\n 'codex/bash-deny',\n 'guards',\n WIRE.write(CODEX_ENVELOPE, 'Bash', { command: 'git merge main' }),\n ),\n new GoldenFixture(\n 'codex/bash-allow',\n 'guards',\n WIRE.write(CODEX_ENVELOPE, 'Bash', { command: 'echo hi' }),\n ),\n // Codex has no Read tool: a read arrives as `Bash` running a pager, which read parity turns into a\n // read-scoped verdict ON TOP of the bash guards.\n new GoldenFixture(\n 'codex/read-allow',\n 'guards',\n WIRE.write(CODEX_ENVELOPE, 'Bash', { command: `sed -n '1,240p' ${REPO_TOKEN}/f.txt` }),\n ),\n new GoldenFixture('codex/malformed', 'guards', '{\"turn_id\": broken'),\n];\n\n// A rules module that blows up the moment it is required — the shortest honest way to reach the hook's\n// fail-closed boundary from OUTSIDE the hook, i.e. without stubbing anything the pipeline owns.\nconst CRASHING_RULE_MODULE = \"throw new Error('boom from a custom rule module');\\n\";\n\n/**\n * Builds ONE throwaway git repo per fixture and returns it with the payload's `<REPO>` resolved.\n *\n * A FRESH repo per fixture, not one shared: the hook writes `.webpieces-logs/` state (the decision log, the\n * main-sync cache) as it runs, so a shared tree would let fixture N's leftovers decide fixture N+1's\n * verdict — an order-dependent suite, which is the one kind of golden test worse than none.\n *\n * `realpathSync` matters on macOS: `os.tmpdir()` hands back `/var/folders/...` which resolves to\n * `/private/var/...`, and the L1 location guard compares the payload's cwd against the resolved repo\n * root. Without it every fixture denies with \"run git from the repo root\" instead of the verdict under\n * test.\n */\nexport class GoldenRepoBuilder {\n private readonly configJson: string;\n\n constructor() {\n this.configJson = fs.readFileSync(\n path.join(__dirname, '__goldens__', 'fixture-webpieces.config.json'),\n 'utf8',\n );\n }\n\n build(fixture: GoldenFixture): PreparedFixture {\n const root = specTempDirs.makeReal('wp-hook-golden-');\n const repo = path.join(root, 'repo');\n fs.mkdirSync(repo);\n this.git(repo, 'init -q -b main');\n // The developer's own commit hooks would otherwise fire inside this throwaway repo.\n this.git(repo, 'config core.hooksPath /dev/null');\n this.git(repo, 'config user.email t@t.co');\n this.git(repo, 'config user.name tester');\n const manifests = policyFixture\n .manifests()\n .map((pack: RulePackManifest) =>\n pack.packageName === rulePackManifest.packageName ? rulePackManifest : pack,\n );\n if (fixture.crashingRuntime) {\n const seed = Object.assign(new ConfigObject(), { mode: 'ON' });\n const definition = new OwnedRuleDefinition(\n 'client-crash',\n { mode: new FieldDef('string', ['ON', 'OFF']) },\n 1,\n {},\n seed,\n 'rules',\n new RuleHelp('Client failure fixture', 'Repair {configFile}.'),\n );\n manifests.push(\n new RulePackManifest(\n '@client/crash',\n '1.0.0-fixture',\n 3,\n [definition],\n [\n new RuleContribution(\n 'client-crash',\n '@client/crash',\n 'source-hook',\n './crash-runtime.cjs',\n ),\n ],\n [],\n [],\n ),\n );\n }\n policyFixture.writeOwnerConfig(repo, JSON.parse(this.repoConfig(fixture)), manifests);\n fs.writeFileSync(path.join(repo, 'f.txt'), 'hello\\n');\n fs.mkdirSync(path.join(repo, 'scripts'));\n fs.writeFileSync(path.join(repo, 'scripts', 'ok.ts'), 'const a = 1;\\n');\n if (fixture.crashingRuntime) {\n fs.writeFileSync(path.join(repo, 'crash-runtime.cjs'), CRASHING_RULE_MODULE);\n }\n this.git(repo, 'add -A');\n this.git(repo, 'commit -qm init');\n // A local origin/main, so `origin/main..<branch>` resolves exactly as it does in a real clone.\n this.git(repo, 'update-ref refs/remotes/origin/main HEAD');\n // A feature branch, because that is where an agent actually works.\n this.git(repo, 'checkout -q -b dean/fixture');\n return new PreparedFixture(repo, root, fixture.stdin.split(REPO_TOKEN).join(repo));\n }\n\n private repoConfig(fixture: GoldenFixture): string {\n if (!fixture.crashingRuntime) return this.configJson;\n // webpieces-disable no-any-unknown -- the frozen fixture config is data on disk; re-parsing it into a named type here would be a second declaration of a file whose whole point is being literal\n const parsed = JSON.parse(this.configJson) as Record<string, unknown>;\n (parsed['rules'] as Record<string, ConfigObject>)['client-crash'] = Object.assign(\n new ConfigObject(),\n { mode: 'ON' },\n );\n return JSON.stringify(parsed, null, 4);\n }\n\n private git(repo: string, args: string): void {\n execSync(`git ${args}`, { cwd: repo, encoding: 'utf8' });\n }\n}\n"]}
1
+ {"version":3,"file":"hook-app-fixtures.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/adapters/hook-app-fixtures.ts"],"names":[],"mappings":";;;;AAAA,oDAO8B;AAC9B,4CAAgD;AAChD,gEAA2D;AAC3D,gEAA0D;AAC1D,iDAAyC;AACzC,+CAAyB;AAEzB,mDAA6B;AAI7B;;;;;;;;;;;GAWG;AAEH,yFAAyF;AACzF,MAAa,aAAa;IACtB,2DAA2D;IAClD,IAAI,CAAS;IACtB,sDAAsD;IAC7C,IAAI,CAAW;IACxB;;;OAGG;I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AG,CAAC,IAAI,EAAE,iBAAiB,CAAC,CAAC;QAClC,+FAA+F;QAC/F,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,0CAA0C,CAAC,CAAC;QAC3D,mEAAmE;QACnE,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,6BAA6B,CAAC,CAAC;QAC9C,OAAO,IAAI,eAAe,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,kBAAU,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;IACvF,CAAC;IAEO,UAAU,CAAC,OAAsB;QACrC,IAAI,CAAC,OAAO,CAAC,eAAe;YAAE,OAAO,IAAI,CAAC,UAAU,CAAC;QACrD,iMAAiM;QACjM,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,UAAU,CAA4B,CAAC;QACrE,MAAM,CAAC,OAAO,CAAkC,CAAC,cAAc,CAAC,GAAG,MAAM,CAAC,MAAM,CAC7E,IAAI,wBAAY,EAAE,EAClB,EAAE,IAAI,EAAE,IAAI,EAAE,CACjB,CAAC;QACF,OAAO,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;IAC3C,CAAC;IAEO,GAAG,CAAC,IAAY,EAAE,IAAY;QAClC,IAAA,wBAAQ,EAAC,OAAO,IAAI,EAAE,EAAE,EAAE,GAAG,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC,CAAC;IAC7D,CAAC;CACJ;AApFD,8CAoFC","sourcesContent":["import {\n ConfigObject,\n FieldDef,\n OwnedRuleDefinition,\n RuleContribution,\n RuleHelp,\n RulePackManifest,\n} from '@webpieces/rules-sdk';\nimport { rulePackManifest } from '../rule-pack';\nimport { policyFixture } from '@webpieces/tooling-testkit';\nimport { specTempDirs } from '@webpieces/tooling-testkit';\nimport { execSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\n\nimport { HookMode } from '@webpieces/hook-runtime';\n\n/**\n * THE WIRE BYTES the golden tests drive, and the throwaway repo they are judged against.\n *\n * Everything here exists so a reader can see EXACTLY what a harness sends: the payloads are built from\n * the measured envelope key sets (see the fixture docs on GoldenFixture below), not from anything the\n * hook itself produces, and the repo is a real `git init` with a frozen webpieces.config.json rather\n * than whatever tree the suite happens to be running in. A golden computed against the live repo would\n * change verdict with the branch you are standing on.\n *\n * This is NOT a spec file, deliberately: `tsconfig.lib.json` excludes `*.spec.ts`, so a payload builder\n * living in one would never be type-checked by the build.\n */\n\n/** How one PreToolUse call is presented to the hook. Data class per CLAUDE.md rule 1. */\nexport class GoldenFixture {\n /** Stable key into `__goldens__/hook-app-goldens.json`. */\n readonly name: string;\n /** Which hook binary's mode — `guards` or `rules`. */\n readonly mode: HookMode;\n /**\n * The raw stdin bytes. A STRING, never an object, because malformed stdin is one of the fixtures\n * and a shape that cannot express \"not JSON\" would quietly drop the case that matters most.\n */\n readonly stdin: string;\n /** True ⇒ the fixture repo also gets a `rulesDir` whose one module throws when required. */\n readonly crashingRuntime: boolean;\n\n constructor(name: string, mode: HookMode, stdin: string, crashingRuntime: boolean = false) {\n this.name = name;\n this.mode = mode;\n this.stdin = stdin;\n this.crashingRuntime = crashingRuntime;\n }\n}\n\n/** A built fixture repo: where it lives, and the stdin bytes with `<REPO>` resolved into it. */\nexport class PreparedFixture {\n readonly repo: string;\n readonly root: string;\n readonly stdin: string;\n\n constructor(repo: string, root: string, stdin: string) {\n this.repo = repo;\n this.root = root;\n this.stdin = stdin;\n }\n}\n\n/**\n * The placeholder that stands for the fixture repo's absolute path, in BOTH directions: payloads are\n * written with it and it is substituted in before the run; golden bytes are compared with the real\n * path substituted back out. Guard reports legitimately name absolute paths (the git-workflow doc\n * pointer, the blocked file), and a golden that hard-coded one machine's `/var/folders/...` would be\n * a golden nobody else could run.\n */\nexport const REPO_TOKEN = '<REPO>';\n\nconst CLAUDE_ENVELOPE = {\n hook_event_name: 'PreToolUse',\n session_id: 'sess-golden',\n transcript_path: '/dev/null',\n cwd: REPO_TOKEN,\n};\n\n/**\n * The Codex additions, MEASURED from codex-cli 0.151.0: it uses Claude's key names and merely ADDS\n * `model`, `turn_id`, `tool_use_id` and `permission_mode`. `turn_id` is the one discriminator (see\n * detect-ai.ts). `agent_id` empty ⇒ the coordinator, populated ⇒ a subagent — identical semantics in\n * both harnesses.\n */\nconst CODEX_ENVELOPE = {\n ...CLAUDE_ENVELOPE,\n model: 'gpt-5-codex',\n turn_id: 'turn-golden',\n tool_use_id: 'call_1',\n permission_mode: 'default',\n agent_type: 'default',\n agent_id: '',\n};\n\n// Codex's edit tool. MEASURED: the tool is named `apply_patch`, it carries `tool_input.command` (not\n// file_path), hunk headers are a bare `@@`, and ONE patch may carry many files with mixed operations.\nconst PATCH_ADD_JS = '*** Begin Patch\\n*** Add File: src/foo.js\\n+var x = 1;\\n*** End Patch\\n';\nconst PATCH_ADD_TS =\n '*** Begin Patch\\n*** Add File: scripts/added.ts\\n+export const b = 2;\\n*** End Patch\\n';\n\n/**\n * Serializes ONE PreToolUse envelope to the bytes a harness would put on stdin. A class rather than a\n * module-scope function because that is the repo rule, and the one instance below is built at module\n * load so the fixture table can stay a plain literal list.\n */\nclass WirePayload {\n // webpieces-disable no-any-unknown -- these objects ARE the wire envelope; JSON.stringify of a plain object is the payload under test, and naming a type for it would assert a shape the fixtures exist to state literally\n write(\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n envelope: Record<string, unknown>,\n toolName: string,\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n toolInput: Record<string, unknown>,\n ): string {\n return JSON.stringify({ ...envelope, tool_name: toolName, tool_input: toolInput });\n }\n}\n\nconst WIRE = new WirePayload();\n\n/**\n * ONE fixture per row of the coverage the composed pipeline had none of before: for BOTH harnesses a\n * Bash deny (the ANSI-red systemMessage), a file-tool deny (NO systemMessage), an allow, a read-only\n * tool, malformed stdin, and a fail-closed crash.\n */\nexport const GOLDEN_FIXTURES: readonly GoldenFixture[] = [\n // ── Claude Code ────────────────────────────────────────────────────────────────────────────────\n // A Bash deny. `git merge` is blocked on every branch, so this verdict does not depend on repo\n // state — and a Bash deny is the ONE case that carries the red `systemMessage`.\n new GoldenFixture(\n 'claude/bash-deny',\n 'guards',\n WIRE.write(CLAUDE_ENVELOPE, 'Bash', { command: 'git merge main' }),\n ),\n new GoldenFixture(\n 'claude/bash-allow',\n 'guards',\n WIRE.write(CLAUDE_ENVELOPE, 'Bash', { command: 'echo hi' }),\n ),\n // The read-only tool: log-and-allow, and the only guard that can deny it is a stale `main`.\n new GoldenFixture(\n 'claude/read-allow',\n 'guards',\n WIRE.write(CLAUDE_ENVELOPE, 'Read', { file_path: `${REPO_TOKEN}/f.txt` }),\n ),\n // Write / Edit / MultiEdit denies — all three must emit NO systemMessage.\n new GoldenFixture('claude/malformed', 'guards', 'not json at all'),\n\n // ── Codex ──────────────────────────────────────────────────────────────────────────────────────\n new GoldenFixture(\n 'codex/bash-deny',\n 'guards',\n WIRE.write(CODEX_ENVELOPE, 'Bash', { command: 'git merge main' }),\n ),\n new GoldenFixture(\n 'codex/bash-allow',\n 'guards',\n WIRE.write(CODEX_ENVELOPE, 'Bash', { command: 'echo hi' }),\n ),\n // Codex has no Read tool: a read arrives as `Bash` running a pager, which read parity turns into a\n // read-scoped verdict ON TOP of the bash guards.\n new GoldenFixture(\n 'codex/read-allow',\n 'guards',\n WIRE.write(CODEX_ENVELOPE, 'Bash', { command: `sed -n '1,240p' ${REPO_TOKEN}/f.txt` }),\n ),\n new GoldenFixture('codex/malformed', 'guards', '{\"turn_id\": broken'),\n];\n\n// A rules module that blows up the moment it is required — the shortest honest way to reach the hook's\n// fail-closed boundary from OUTSIDE the hook, i.e. without stubbing anything the pipeline owns.\nconst CRASHING_RULE_MODULE = \"throw new Error('boom from a custom rule module');\\n\";\n\n/**\n * Builds ONE throwaway git repo per fixture and returns it with the payload's `<REPO>` resolved.\n *\n * A FRESH repo per fixture, not one shared: the hook writes `.webpieces/` state (the decision log, the\n * main-sync cache) as it runs, so a shared tree would let fixture N's leftovers decide fixture N+1's\n * verdict — an order-dependent suite, which is the one kind of golden test worse than none.\n *\n * `realpathSync` matters on macOS: `os.tmpdir()` hands back `/var/folders/...` which resolves to\n * `/private/var/...`, and the L1 location guard compares the payload's cwd against the resolved repo\n * root. Without it every fixture denies with \"run git from the repo root\" instead of the verdict under\n * test.\n */\nexport class GoldenRepoBuilder {\n private readonly configJson: string;\n\n constructor() {\n this.configJson = fs.readFileSync(\n path.join(__dirname, '__goldens__', 'fixture-webpieces.config.json'),\n 'utf8',\n );\n }\n\n build(fixture: GoldenFixture): PreparedFixture {\n const root = specTempDirs.makeReal('wp-hook-golden-');\n const repo = path.join(root, 'repo');\n fs.mkdirSync(repo);\n this.git(repo, 'init -q -b main');\n // The developer's own commit hooks would otherwise fire inside this throwaway repo.\n this.git(repo, 'config core.hooksPath /dev/null');\n this.git(repo, 'config user.email t@t.co');\n this.git(repo, 'config user.name tester');\n const manifests = policyFixture\n .manifests()\n .map((pack: RulePackManifest) =>\n pack.packageName === rulePackManifest.packageName ? rulePackManifest : pack,\n );\n if (fixture.crashingRuntime) {\n const seed = Object.assign(new ConfigObject(), { mode: 'ON' });\n const definition = new OwnedRuleDefinition(\n 'client-crash',\n { mode: new FieldDef('string', ['ON', 'OFF']) },\n 1,\n {},\n seed,\n 'rules',\n new RuleHelp('Client failure fixture', 'Repair {configFile}.'),\n );\n manifests.push(\n new RulePackManifest(\n '@client/crash',\n '1.0.0-fixture',\n 3,\n [definition],\n [\n new RuleContribution(\n 'client-crash',\n '@client/crash',\n 'source-hook',\n './crash-runtime.cjs',\n ),\n ],\n [],\n [],\n ),\n );\n }\n policyFixture.writeOwnerConfig(repo, JSON.parse(this.repoConfig(fixture)), manifests);\n fs.writeFileSync(path.join(repo, 'f.txt'), 'hello\\n');\n fs.mkdirSync(path.join(repo, 'scripts'));\n fs.writeFileSync(path.join(repo, 'scripts', 'ok.ts'), 'const a = 1;\\n');\n if (fixture.crashingRuntime) {\n fs.writeFileSync(path.join(repo, 'crash-runtime.cjs'), CRASHING_RULE_MODULE);\n }\n this.git(repo, 'add -A');\n this.git(repo, 'commit -qm init');\n // A local origin/main, so `origin/main..<branch>` resolves exactly as it does in a real clone.\n this.git(repo, 'update-ref refs/remotes/origin/main HEAD');\n // A feature branch, because that is where an agent actually works.\n this.git(repo, 'checkout -q -b dean/fixture');\n return new PreparedFixture(repo, root, fixture.stdin.split(REPO_TOKEN).join(repo));\n }\n\n private repoConfig(fixture: GoldenFixture): string {\n if (!fixture.crashingRuntime) return this.configJson;\n // webpieces-disable no-any-unknown -- the frozen fixture config is data on disk; re-parsing it into a named type here would be a second declaration of a file whose whole point is being literal\n const parsed = JSON.parse(this.configJson) as Record<string, unknown>;\n (parsed['rules'] as Record<string, ConfigObject>)['client-crash'] = Object.assign(\n new ConfigObject(),\n { mode: 'ON' },\n );\n return JSON.stringify(parsed, null, 4);\n }\n\n private git(repo: string, args: string): void {\n execSync(`git ${args}`, { cwd: repo, encoding: 'utf8' });\n }\n}\n"]}
@@ -71,7 +71,7 @@ function handleBash(event, cwd, mode) {
71
71
  // call-level outcome onto `calls/`. So this was the THIRD line for one block, and the worst of the
72
72
  // three: it re-resolved the root from `cwd` via RepoRootFinder, which is not necessarily the tree
73
73
  // the guard actually judged, so a `cd`-relocated command scattered one block across two different
74
- // `.webpieces-logs` directories.
74
+ // `.webpieces` directories.
75
75
  //
76
76
  // Bash deny → the event's kind is 'Bash', so denyJson adds the ANSI-red systemMessage (the only
77
77
  // field a Bash deny shows the human; permissionDecisionReason is invisible on Bash). See
@@ -158,9 +158,9 @@ function handleOneFile(event, file, cwd, mode) {
158
158
  // audit trail explains why a config edit on a bad branch was not blocked (see decision-log.ts).
159
159
  if (path.basename(input.filePath) === rules_config_1.CONFIG_FILENAME) {
160
160
  if (mode !== 'rules') {
161
- // `.webpieces-logs/` (the decision log + sync cache these two calls write) lives at the repo
161
+ // `.webpieces/` (the decision log + sync cache these two calls write) lives at the repo
162
162
  // root, not the AI's cwd — resolve it so a config edit from a subdir doesn't create a
163
- // stray `<subdir>/.webpieces-logs` tree.
163
+ // stray `<subdir>/.webpieces` tree.
164
164
  const root = new rules_config_2.RepoRootFinder().resolveRepoRoot(cwd);
165
165
  (0, decision_log_1.logGuardDecision)(root, new decision_log_1.GuardDecision('feature-branch-guard', file.toolKind, input.filePath, (0, decision_log_1.branchForLog)(root), 'ALLOW_EXEMPT', 'config-bypass (feature-branch-guard skipped)', '-', rules_config_4.L0_FAULT_NONE, (0, decision_log_1.matrixL2Row)('config-bypass (feature-branch-guard skipped)')));
166
166
  // The guard's own refresh trigger lives inside its check(), which we skip here — so warm
@@ -1 +1 @@
1
- {"version":3,"file":"hook-core.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/adapters/hook-core.ts"],"names":[],"mappings":";;AAqOA,8DAKC;AAoFD,kCA6DC;;AA3XD,mDAA6B;AAE7B,2CAAuD;AACvD,iEAAsE;AACtE,yDAAuE;AACvE,uDAAkI;AAClI,iEAAmE;AACnE,0DAA0D;AAC1D,0DAA8E;AAC9E,0DAAuF;AACvF,8DAA0D;AAC1D,0DAAwD;AAExD,iEAA6D;AAC7D,qDAAoE;AACpE,0DAAsE;AACtE,0DAA2E;AAC3E,0DAAwD;AACxD,0DAAuD;AACvD,iEAA2F;AAC3F,uEAAkE;AAClE,sCAAsF;AACtF,gEAA+D;AAC/D,8DAA8D;AAC9D,iDAA4E;AAC5E,mDAA+D;AAC/D,6DAAwD;AACxD,0DAA6E;AAW7E,MAAM,QAAQ,GAAG,IAAI,4BAAa,EAAE,CAAC;AACrC,MAAM,cAAc,GAAG,IAAI,mDAA4B,EAAE,CAAC;AAC1D,MAAM,uBAAuB,GAAG,IAAI,+CAAqB,EAAE,CAAC;AAE5D,kGAAkG;AAClG,kGAAkG;AAClG,sDAAsD;AACtD,0JAA0J;AAC1J,SAAS,YAA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,4BAAW,EAAC,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE,qBAAqB,CAAC,CAAC;IACpE,CAAC;IACD,OAAO,IAAA,4BAAW,EAAC,KAAK,EAAE,0DAA0D,KAAK,CAAC,OAAO,EAAE,EAAE,YAAY,CAAC,CAAC;AACvH,CAAC","sourcesContent":["import * as path from 'path';\n\nimport { run, runBash, runRead } from '../core/runner';\nimport { branchStateHangTimeoutFor } from '../core/main-sync-timeout';\nimport { logRejection, extractRuleNames } from '../core/rejection-log';\nimport { logGuardDecision, GuardDecision, branchForLog, invocationLog, MATRIX_L0_BLOCK, matrixL2Row } from '../core/decision-log';\nimport { triggerMainSyncRefresh } from '../core/main-sync-refresh';\nimport { CONFIG_FILENAME } from '@webpieces/rules-config';\nimport { RepoRootFinder, renderRuleFailForAi } from '@webpieces/rules-config';\nimport { NormalizedToolInput, HookMode, BlockedResult } from '@webpieces/hook-runtime';\nimport { InformAiError } from '@webpieces/tooling-common';\nimport { RuleFailError } from '@webpieces/rules-config';\nimport { AgentHookEvent, AiType, FileOperation } from '@webpieces/hook-runtime';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { emitDeny, emitAllow, denyOutcome } from './agent-response';\nimport { HookOutcome, HookTerminated } from '@webpieces/hook-runtime';\nimport { AgentPayload, AgentPayloadParser } from '@webpieces/hook-runtime';\nimport { AgentAdapters } from '@webpieces/hook-runtime';\nimport { detectAiType } from '@webpieces/hook-runtime';\nimport { CodexSubagentSharedTreeGuard, CODEX_SUBAGENT_RULE } from './codex-subagent-guard';\nimport { ReviewIdentityStamper } from './review-identity-stamper';\nimport { governingShimRoot, isAllowed, installedShimRulesVersion } from '../bin/shim';\nimport { managedSurfaceDrift } from '../bin/hook-registration';\nimport { shimStaleDenyReason } from '../bin/shim-deny-reason';\nimport { writeGuardMatrixDoc, guardMatrixPointer } from '../core/l0-matrix';\nimport { logStream, StreamIdentity } from '../core/log-stream';\nimport { aiTypeContext } from '../core/ai-type-context';\nimport { L0_FAULT_SHIM_STALE, L0_FAULT_NONE } from '@webpieces/rules-config';\n\n// Which category of rules this hook invocation runs. The hook is split into two independently\n// installable PreToolUse hooks; each runs ONE category (the runner filters by it), and both can\n// receive file AND bash payloads:\n// - 'rules' → code-style rules (file/edit scope). Bash payloads pass through (no code rules apply).\n// - 'guards' → hookGuards section: bash git/PR guards on Bash AND file guards (feature-branch-guard)\n// on Write/Edit, PLUS a log-and-allow audit of Read. Matcher is Write|Edit|MultiEdit|Bash|Read.\n// - 'all' → both categories, used by the openclaw plugin adapter (a single before_tool_call hook).\nexport type { HookMode };\n\nconst ADAPTERS = new AgentAdapters();\nconst SUBAGENT_GUARD = new CodexSubagentSharedTreeGuard();\nconst REVIEW_IDENTITY_STAMPER = new ReviewIdentityStamper();\n\n// The rule name for a block's audit line: the FIRST rule the report cites, or `fallback` when the\n// report opens with no `[rule]` header (a hand-written guard message). Comma-joined when a report\n// cites several, so `rule=` never silently drops one.\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction blockingRule(report: string, fallback: string): string {\n const names = extractRuleNames(report);\n return names.length > 0 ? names.join(',') : fallback;\n}\n\n// webpieces-disable no-function-outside-class -- sibling of handleRead()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction handleBash(event: AgentHookEvent, cwd: string, mode: HookMode): never {\n const command = event.bash === null ? '' : event.bash.command;\n if (command.trim() === '') { emitAllow(); }\n\n // READ PARITY, and it can only ever be reached from a Codex event: the adapter leaves `reads`\n // empty for Claude Code, which has a real `Read` tool and its own fast path. A Codex read arrives\n // as `Bash` running a pager, so without this the read guard and the `calls/` audit trail see none\n // of them. The command is STILL run through the bash guards below — this adds a verdict, it never\n // replaces one.\n for (const readPath of event.reads) {\n handleRead(event, readPath, cwd, mode);\n }\n\n // The HARNESS travels with the command. Fault C and fault Y are decided inside the runner, and\n // both consult the L0 allowlist — which since the gated entry exists cannot be asked without\n // knowing who is calling. `event.aiType` is the adapter's answer, the same one that routed this\n // call to the Codex read-parity loop above.\n const result = runBash(command, cwd, mode, event.aiType);\n if (!result) {\n // ALLOWED — so if this call submits a reviewer verdict, record who is submitting it before the\n // command runs. `wp-write-review` cannot learn that from its env (see ReviewIdentityStamper).\n REVIEW_IDENTITY_STAMPER.stamp(event, command, cwd);\n emitAllow();\n }\n // NO DECISION LINE HERE. This used to write a generic `bash-guard` line because a Bash deny once\n // had no audit trail at all — but every layer now records its own: L1 into `L1-location/` with its\n // row, L2's guards into `L2-decisions/` with their rule and cache, and emitDeny below stamps the\n // call-level outcome onto `calls/`. So this was the THIRD line for one block, and the worst of the\n // three: it re-resolved the root from `cwd` via RepoRootFinder, which is not necessarily the tree\n // the guard actually judged, so a `cd`-relocated command scattered one block across two different\n // `.webpieces-logs` directories.\n //\n // Bash deny → the event's kind is 'Bash', so denyJson adds the ANSI-red systemMessage (the only\n // field a Bash deny shows the human; permissionDecisionReason is invisible on Bash). See\n // agent-response.ts.\n emitDeny(event, result.report, blockingRule(result.report, 'bash-guard'), result.fault);\n}\n\n/**\n * The read-scoped guard pass. Returns normally to ALLOW; only calls emitDeny when the guard fires.\n *\n * Wrapped in its own catch that swallows into an allow. Every other path in this hook fails CLOSED,\n * and that is right for edits and shell commands — but a crash here would block the agent from\n * READING, which includes reading webpieces.config.json to turn the offending guard off. So this one\n * path deliberately inverts the policy: a broken read-guard degrades to a no-op, never to a wedge.\n */\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction handleRead(event: AgentHookEvent, filePath: string, cwd: string, mode: HookMode): void {\n if (filePath === '') return;\n let result: BlockedResult | null = null;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n result = runRead(filePath, cwd, mode);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return; // fail OPEN — see the doc comment\n }\n if (!result) return;\n logRejection('Read', new NormalizedToolInput(filePath, []), result, cwd);\n emitDeny(event, result.report, blockingRule(result.report, 'read-guard'), result.fault);\n}\n\n/**\n * Read-only tools (Read): audit-log, warm the main-sync cache, then run the ONE read-scoped guard\n * (read-stale-guard) and allow. Runs BEFORE the general rule engine — no code-style rule ever sees a\n * Read, and the only way this path can deny is a stale `main`. The audit trail still records every\n * file the AI opened (see setup.ts).\n *\n * Returns normally ONLY when the event is not a Read; otherwise it ends the invocation.\n */\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction handleReadFastPath(event: AgentHookEvent, cwd: string, mode: HookMode): void {\n if (event.kind !== 'Read') return;\n const readPath = event.reads.length > 0 ? event.reads[0] : '';\n if (mode !== 'rules') {\n invocationLog.begin(cwd, event.rawToolName, readPath);\n // Reads vastly outnumber edits, so refreshing here is what actually keeps the shared\n // main-sync cache warm for feature-branch-guard. Detached; never slows the read.\n triggerMainSyncRefresh(cwd, branchStateHangTimeoutFor(cwd));\n }\n handleRead(event, readPath, cwd, mode);\n emitAllow();\n}\n\n/**\n * The file/edit pipeline, run once per file the call touches.\n *\n * `event.files` is a LIST because ONE Codex `apply_patch` carries many files with mixed operations.\n * A Claude Code event always has exactly one entry, so the loop runs once and the behaviour is the\n * single-file behaviour it has always had.\n */\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleRead() in this module; the adapter is module-scope functions by design\nfunction handleFileTool(event: AgentHookEvent, cwd: string, mode: HookMode): never {\n if (event.files.length === 0) { emitAllow(); }\n\n // A Codex SUBAGENT writing into the tree it shares with its coordinator. Returns null for every\n // Claude Code event — that harness can hand a subagent its own worktree, and does.\n const subagentBlock = SUBAGENT_GUARD.check(event, new RepoRootFinder().resolveRepoRoot(cwd));\n if (subagentBlock) {\n emitDeny(event, subagentBlock.report, CODEX_SUBAGENT_RULE, subagentBlock.fault);\n }\n\n for (const file of event.files) {\n handleOneFile(event, file, cwd, mode);\n }\n emitAllow();\n}\n\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction handleOneFile(event: AgentHookEvent, file: FileOperation, cwd: string, mode: HookMode): void {\n const input = file.input;\n\n // Always allow edits to webpieces.config.json — it's the fix target when the config is broken.\n // This returns BEFORE run(), so feature-branch-guard never sees a config edit; record that so the\n // audit trail explains why a config edit on a bad branch was not blocked (see decision-log.ts).\n if (path.basename(input.filePath) === CONFIG_FILENAME) {\n if (mode !== 'rules') {\n // `.webpieces-logs/` (the decision log + sync cache these two calls write) lives at the repo\n // root, not the AI's cwd — resolve it so a config edit from a subdir doesn't create a\n // stray `<subdir>/.webpieces-logs` tree.\n const root = new RepoRootFinder().resolveRepoRoot(cwd);\n logGuardDecision(\n root,\n new GuardDecision('feature-branch-guard', file.toolKind, input.filePath, branchForLog(root), 'ALLOW_EXEMPT', 'config-bypass (feature-branch-guard skipped)', '-', L0_FAULT_NONE, matrixL2Row('config-bypass (feature-branch-guard skipped)')),\n );\n // The guard's own refresh trigger lives inside its check(), which we skip here — so warm\n // the cache directly, otherwise a session that only edits webpieces.config.json never\n // refreshes the sync status. Fire-and-forget; never blocks the edit.\n triggerMainSyncRefresh(root, branchStateHangTimeoutFor(cwd));\n }\n return;\n }\n\n const result = run(file.toolKind, input, cwd, mode);\n if (!result) return;\n\n logRejection(file.toolKind, input, result, cwd);\n // File-tool deny → the event's kind is 'File', so denyJson omits systemMessage (the reason\n // already renders red natively for these tools). See agent-response.ts.\n emitDeny(event, result.report, blockingRule(result.report, 'file-guard'), result.fault);\n}\n\n// What a stale committed shim lets through — now a thin adapter over the ONE L0 allowlist (isAllowed in\n// ../bin/shim), not a list of its own. A stale shim must NEVER trap the actions needed to recover: the\n// original \"block everything but the cures\" version also shadowed the always-allowed\n// webpieces.config.json edit (handleFileTool) and blocked reads, so a repo that ALSO needed its config\n// fixed would deadlock — blocked from editing the one file whose edit is normally always allowed, and\n// blocked from reading it to know how.\n//\n// It used to carry its OWN narrower list (isShimCureCommand: the three shim cures only), and that\n// narrowness was a defect, not a safety property: `pnpm install` and `git pull` — the two commands that\n// resolve the version disagreement underneath a stale shim — were denied. Consulting the shared\n// allowlist fixes that by construction.\n//\n// What is NOT a defect, and must not be \"fixed\": those cures rewrite the committed shim from the\n// INSTALLED binary's renderShim(), overwriting whatever was there. That is the invariant, not\n// collateral damage. The shim (D/X/K, in POSIX sh, pre-binary) and this binary (S/C/Y, in JS) are two\n// halves of ONE L0 and they exchange assumptions — the shim parses file_path and carries ALLOW-READ /\n// ALLOW-CONFIG entries this binary relies on. Pair a binary with a shim rendered by a DIFFERENT\n// release and L0 acquires holes that nothing reports. So the rule is absolute: the committed shim\n// equals renderShim() of the binary in node_modules, and a cure that forces that is the cure working.\n// See healShim's header, which states the same invariant from the other side.\n//\n// Corollary for anyone regenerating the shim in a webpieces PR: commit `templates/ai-hook.sh` (source,\n// locked to renderShim() by unit test) and leave `.claude/webpieces/ai-hook.sh` (generated artifact)\n// alone. In THIS repo the local source runs ahead of the pinned node_modules, so committing a shim\n// rendered from local source produces a commit whose shim and whose @webpieces pin come from different\n// releases — precisely the mismatch above. The artifact heals on the next upgrade; that is its job.\n//\n// - 'allow-cure' → a Bash cure on the allowlist: emitAllow directly, bypassing the git guards.\n// - 'pass' → a recovery action the normal flow already permits, so fall THROUGH and let it: ANY\n// Read (you must read to know how to fix — see handleRead, which itself fails open),\n// or an edit to webpieces.config.json (the always-allowed recovery target).\n// - 'deny' → all OTHER work: blocked until the committed shim matches renderShim() again.\nexport type ShimStaleDecision = 'allow-cure' | 'pass' | 'deny';\n// webpieces-disable no-function-outside-class -- pure decision helper beside the adapter's other module-scope functions; exported for direct unit testing.\nexport function shimStaleRecoveryDecision(toolName: string, command: string, filePath: string, aiType: AiType): ShimStaleDecision {\n const allowed = isAllowed(toolName, command, filePath, aiType);\n if (allowed === 'pass') return 'pass';\n if (allowed === 'allow') return 'allow-cure';\n return 'deny';\n}\n\n// MANAGED-HOOK-SURFACE self-guard, moved here from the rendered shim (2026-07-24) and widened from one\n// file to three (2026-08-07). The committed\n// .claude/webpieces/ai-hook.sh is webpieces-MANAGED and generated from renderShim(); if it no longer\n// matches, it was reverted / hand-edited / predates this binary, so its OWN fail-closed logic can't be\n// trusted. We are the CURRENT binary from node_modules — the trustworthy party — so WE decide here\n// instead of the (possibly stale) shim. It used to `cmp` itself inside the shim: a double-edged trap,\n// since the check lived in the very file it guarded and a fix could only ship by regenerating that\n// file. Now we fail closed on all real WORK while always leaving the recovery path open (see\n// shimStaleRecoveryDecision): the whole L0 allowlist, any Read, and editing webpieces.config.json. We deny +\n// tell the AI; we do NOT silently rewrite the file under it. 'rules' hook skips it (guards owns the\n// shim). Returns normally (pass / nothing to do) or exits via emitAllow/emitDeny.\n//\n// It asks the allowlist about the RAW WIRE FIELDS, not about the normalized event, and that ordering is\n// deliberate: L0 has to hold on a tree too broken to trust anything above it, including the adapters.\n// The raw fields are the same key names in both harnesses (measured), so one reading serves both, and\n// the answer cannot change because a normalizer changed. `event` is here only to decorate the deny.\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction enforceCommittedShim(payload: AgentPayload, event: AgentHookEvent, cwd: string, mode: HookMode): void {\n // ONE root for the whole decision, resolved from the RUNNING MODULE (governingShimRoot), never from\n // `cwd`: the shim file we compare and the renderShim() we compare it TO must come from the same\n // install, or the check straddles two trees and can never converge (see governingShimRoot's header).\n // `cwd` still selects where the L0 matrix doc is dropped — that is a \"where does the AI read\" question,\n // not part of the judgement.\n const shimRoot = governingShimRoot();\n if (mode === 'rules') return;\n // WHICH of the managed things moved — ai-hook.sh, either harness's hook registration\n // (.claude/settings.json, .codex/hooks.json), or the Claude settings' managed env entry (the\n // Bash-cwd pin that keeps a guard's verdict independent of where an earlier `cd` left the shell;\n // see managed-env.ts). Nothing validated the registration before it joined this\n // fault, so a settings file left on a superseded form silently changed WHO GOVERNS, with no signal\n // anywhere — which is the whole reason the registration is a drift surface and not just an install\n // step.\n const drifted = managedSurfaceDrift(shimRoot);\n if (drifted.length === 0) return;\n // The harness comes from the RAW envelope too — `detectAiType` asks one question of one key, so it\n // is as trustworthy here as the wire fields beside it, and it is the PRECISE test the shim's sh half\n // can only approximate. Reading it off the normalized event instead would put a normalizer between\n // L0 and its decision, which is the coupling the paragraph above exists to refuse.\n const decision = shimStaleRecoveryDecision(\n payload.tool_name, payload.tool_input.command ?? '', payload.tool_input.file_path ?? '',\n detectAiType(payload));\n if (decision === 'pass') return;\n if (decision === 'allow-cure') emitAllow();\n // Drop the L0 matrix doc where the AI can read it and point the deny at it — a Read is entry 1 of\n // the same allowlist, so the pointer is always followable. Best-effort: no doc → no pointer.\n const root = new RepoRootFinder().resolveRepoRoot(cwd);\n const docPath = writeGuardMatrixDoc(root);\n // WRITE THE AUDIT LINE HERE. This block happens BEFORE invocationLog.begin() — it has to, since a\n // stale shim invalidates everything downstream — so emitDeny's flush finds nothing pending and an\n // `S` storm left NO trace at all: the one fault most likely to block twenty consecutive tool calls\n // was the one fault the trail could not show. A decision line is the fix that costs no reordering.\n const target = payload.tool_input.command ?? payload.tool_input.file_path ?? '';\n logGuardDecision(\n root,\n new GuardDecision('committed-shim-stale', payload.tool_name, target, branchForLog(root), 'BLOCK_AI_CURE', 'L0 fault S (committed shim != renderShim)', '-', L0_FAULT_SHIM_STALE, MATRIX_L0_BLOCK),\n );\n // L0 fault S in GUARD_MATRIX.md's codebook — named as the blocking rule so the invocation line\n // says WHAT stopped the call, not merely that something did, and stamped as `fault=S` so the same\n // grep finds it here as in the sh half's `L0-shim/` stream.\n // A subagent is discriminated by `agent_id`, which BOTH harnesses populate on stdin only off the\n // main loop (main falls back to the session id / leaves it empty). Its cure differs: the hooks\n // blocking it resolve through CLAUDE_PROJECT_DIR, which names the MAIN tree.\n const inSubagent = event.agentId !== '';\n emitDeny(event, shimStaleDenyReason(installedShimRulesVersion(), shimRoot ?? '', drifted, inSubagent) + guardMatrixPointer(docPath), 'committed-shim-stale', L0_FAULT_SHIM_STALE);\n}\n\n/**\n * THE PIPELINE, from raw stdin bytes to the decision — the whole of `parse -> adapter -> runner ->\n * emit`, as ONE function returning ONE value.\n *\n * `mode` selects which tool kinds to validate; payloads outside the mode's scope pass through\n * (emitAllow). A block is a PreToolUse `permissionDecision:\"deny\"` JSON on stdout with exit 0 — see\n * agent-response.ts. Fails CLOSED on any unexpected crash (returns a deny) so a broken hook never\n * silently lets an edit through, and the reason surfaces in the agent's UI instead of being hidden on\n * a stderr+exit-2 block.\n *\n * It reads NO stdin, writes NO stdout and calls NO exit: those three couplings are ports owned by\n * HookApp (see hook-ports.ts), which is what makes the composed pipeline drivable from a test. This\n * function is what `runMain` was; it is not a second spelling of it — `runMain` is deleted, and\n * `HookApp.run()` is the only entry point.\n */\n// webpieces-disable no-function-outside-class -- the module-scope hook body itself, sibling of handleBash()/handleFileTool(); the adapter is module-scope functions by design and must stay callable from a tree too broken to build a DI container\nexport function runPipeline(raw: string, mode: HookMode): HookOutcome {\n // Captured as soon as the ENVELOPE parses so the fail-closed catch below can tell denyJson which\n // kind of call it is denying — a crash on a Bash call still gets the visible red systemMessage, a\n // crash on a file tool does not. Null (before parse / malformed input) → treated as non-Bash.\n let event: AgentHookEvent | null = null;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const payload = new AgentPayloadParser().parse(raw);\n if (!payload) { emitAllow(); }\n // The envelope shape first: it reads only `tool_name` and the identity fields, so it cannot\n // fail, and it is what the crash path needs. The full normalization below reads `tool_input`\n // and CAN fail (a malformed Codex patch envelope denies rather than being half-understood).\n event = ADAPTERS.envelope(payload);\n\n // BEFORE enforceCommittedShim(), which can itself write a BLOCK line. See LogStream for why\n // all three of session/agent/hook are needed to keep concurrent writers off one file.\n logStream.identify(new StreamIdentity(event.sessionId, event.agentId, mode));\n // Same moment, same reason: every JS-side stream stamps `ai=`, and the fault-S line written\n // inside enforceCommittedShim() is one of them. See AiTypeContext for why the harness is a\n // process-wide holder rather than a parameter on four writers.\n aiTypeContext.identify(event.aiType);\n\n // Prefer the payload cwd (the AI's actual working dir, follows a persisted `cd`) over\n // process.cwd(); they match today, but the payload is the authoritative signal and stays\n // correct if the hook is ever invoked from a fixed dir (e.g. via $CLAUDE_PROJECT_DIR).\n const cwd = payload.cwd ?? process.cwd();\n\n // Committed-shim self-guard: blocks real work while the committed shim is stale, but keeps the\n // recovery path open (cures, reads, config edit). See enforceCommittedShim / shimStaleRecoveryDecision.\n enforceCommittedShim(payload, event, cwd, mode);\n\n event = ADAPTERS.toEvent(payload, cwd);\n\n // Read-only tools: their own fast path, which never returns when it applies.\n handleReadFastPath(event, cwd, mode);\n\n // Per-invocation guard log (the `calls/` stream): tool + command/file + live branch +\n // main-sync-status snapshot, on EVERY guards call, for later cleanup automation. Best-effort;\n // never blocks the call. (The committed shim is no longer silently healed here — a mismatch is\n // reported by the self-guard above, not rewritten out from under the AI.)\n if (mode !== 'rules') {\n invocationLog.begin(cwd, event.rawToolName, logTarget(event));\n }\n\n if (event.kind === 'Bash') {\n // No code-style rule is bash-scoped, so the rules hook ignores Bash.\n if (mode === 'rules') { emitAllow(); }\n handleBash(event, cwd, mode);\n }\n\n // File payloads run in 'rules' (code-style), 'guards' (file-scoped guards like\n // feature-branch-guard), and 'all'. The runner filters to the right category.\n handleFileTool(event, cwd, mode);\n } catch (err: unknown) {\n const error = toError(err);\n // The pipeline's own terminal control flow, not a failure: emitAllow/emitDeny threw the answer\n // out to here from wherever they were called. Treating it as a crash would turn every allow\n // into a deny, so this branch comes FIRST and returns the carried outcome verbatim.\n if (error instanceof HookTerminated) return error.outcome;\n return denyForCrash(error, event);\n }\n}\n\n// What the `calls/` audit line names as the call's target: the command for a shell call, else the first\n// file it touches. A Codex `apply_patch` touching several files names the first — the rejection log and\n// the decision log carry the rest, per file.\n// webpieces-disable no-function-outside-class -- sibling of the module-scope hook entry points in this adapter\nfunction logTarget(event: AgentHookEvent): string {\n if (event.kind === 'Bash') return event.bash === null ? '' : event.bash.command;\n return event.files.length > 0 ? event.files[0].input.filePath : '';\n}\n\n/**\n * The fail-closed boundary for anything that escaped the hook body. An escaped RuleFailError (a rule\n * that threw past the runner's per-rule catch) or an InformAiError (bad config/stdin, or a Codex patch\n * envelope this parser refuses to guess at) both carry an AI-readable message; anything else is an\n * unexpected bug. All three DENY and surface their reason, because a hook that crashed established\n * nothing and must never be read as an allow.\n *\n * It BUILDS the deny (denyOutcome) rather than throwing it (emitDeny), because it is already inside\n * the catch that the throw would land in — see HookTerminated. Same bytes either way.\n */\n// webpieces-disable no-function-outside-class -- sibling of the module-scope hook entry points in this adapter; a lone class for one terminal boundary would break the file's shape\nfunction denyForCrash(error: Error, event: AgentHookEvent | null): HookOutcome {\n if (error instanceof RuleFailError) {\n return denyOutcome(event, renderRuleFailForAi(error), 'rule-crash');\n }\n if (error instanceof InformAiError) {\n return denyOutcome(event, error.message, 'bad-config-or-stdin');\n }\n return denyOutcome(event, `[ai-hooks] hook crashed unexpectedly — failing closed: ${error.message}`, 'hook-crash');\n}\n"]}
1
+ {"version":3,"file":"hook-core.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/adapters/hook-core.ts"],"names":[],"mappings":";;AAqOA,8DAKC;AAoFD,kCA6DC;;AA3XD,mDAA6B;AAE7B,2CAAuD;AACvD,iEAAsE;AACtE,yDAAuE;AACvE,uDAAkI;AAClI,iEAAmE;AACnE,0DAA0D;AAC1D,0DAA8E;AAC9E,0DAAuF;AACvF,8DAA0D;AAC1D,0DAAwD;AAExD,iEAA6D;AAC7D,qDAAoE;AACpE,0DAAsE;AACtE,0DAA2E;AAC3E,0DAAwD;AACxD,0DAAuD;AACvD,iEAA2F;AAC3F,uEAAkE;AAClE,sCAAsF;AACtF,gEAA+D;AAC/D,8DAA8D;AAC9D,iDAA4E;AAC5E,mDAA+D;AAC/D,6DAAwD;AACxD,0DAA6E;AAW7E,MAAM,QAAQ,GAAG,IAAI,4BAAa,EAAE,CAAC;AACrC,MAAM,cAAc,GAAG,IAAI,mDAA4B,EAAE,CAAC;AAC1D,MAAM,uBAAuB,GAAG,IAAI,+CAAq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,YAAY,CAAC,CAAC;IACxE,CAAC;IACD,IAAI,KAAK,YAAY,8BAAa,EAAE,CAAC;QACjC,OAAO,IAAA,4BAAW,EAAC,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE,qBAAqB,CAAC,CAAC;IACpE,CAAC;IACD,OAAO,IAAA,4BAAW,EAAC,KAAK,EAAE,0DAA0D,KAAK,CAAC,OAAO,EAAE,EAAE,YAAY,CAAC,CAAC;AACvH,CAAC","sourcesContent":["import * as path from 'path';\n\nimport { run, runBash, runRead } from '../core/runner';\nimport { branchStateHangTimeoutFor } from '../core/main-sync-timeout';\nimport { logRejection, extractRuleNames } from '../core/rejection-log';\nimport { logGuardDecision, GuardDecision, branchForLog, invocationLog, MATRIX_L0_BLOCK, matrixL2Row } from '../core/decision-log';\nimport { triggerMainSyncRefresh } from '../core/main-sync-refresh';\nimport { CONFIG_FILENAME } from '@webpieces/rules-config';\nimport { RepoRootFinder, renderRuleFailForAi } from '@webpieces/rules-config';\nimport { NormalizedToolInput, HookMode, BlockedResult } from '@webpieces/hook-runtime';\nimport { InformAiError } from '@webpieces/tooling-common';\nimport { RuleFailError } from '@webpieces/rules-config';\nimport { AgentHookEvent, AiType, FileOperation } from '@webpieces/hook-runtime';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { emitDeny, emitAllow, denyOutcome } from './agent-response';\nimport { HookOutcome, HookTerminated } from '@webpieces/hook-runtime';\nimport { AgentPayload, AgentPayloadParser } from '@webpieces/hook-runtime';\nimport { AgentAdapters } from '@webpieces/hook-runtime';\nimport { detectAiType } from '@webpieces/hook-runtime';\nimport { CodexSubagentSharedTreeGuard, CODEX_SUBAGENT_RULE } from './codex-subagent-guard';\nimport { ReviewIdentityStamper } from './review-identity-stamper';\nimport { governingShimRoot, isAllowed, installedShimRulesVersion } from '../bin/shim';\nimport { managedSurfaceDrift } from '../bin/hook-registration';\nimport { shimStaleDenyReason } from '../bin/shim-deny-reason';\nimport { writeGuardMatrixDoc, guardMatrixPointer } from '../core/l0-matrix';\nimport { logStream, StreamIdentity } from '../core/log-stream';\nimport { aiTypeContext } from '../core/ai-type-context';\nimport { L0_FAULT_SHIM_STALE, L0_FAULT_NONE } from '@webpieces/rules-config';\n\n// Which category of rules this hook invocation runs. The hook is split into two independently\n// installable PreToolUse hooks; each runs ONE category (the runner filters by it), and both can\n// receive file AND bash payloads:\n// - 'rules' → code-style rules (file/edit scope). Bash payloads pass through (no code rules apply).\n// - 'guards' → hookGuards section: bash git/PR guards on Bash AND file guards (feature-branch-guard)\n// on Write/Edit, PLUS a log-and-allow audit of Read. Matcher is Write|Edit|MultiEdit|Bash|Read.\n// - 'all' → both categories, used by the openclaw plugin adapter (a single before_tool_call hook).\nexport type { HookMode };\n\nconst ADAPTERS = new AgentAdapters();\nconst SUBAGENT_GUARD = new CodexSubagentSharedTreeGuard();\nconst REVIEW_IDENTITY_STAMPER = new ReviewIdentityStamper();\n\n// The rule name for a block's audit line: the FIRST rule the report cites, or `fallback` when the\n// report opens with no `[rule]` header (a hand-written guard message). Comma-joined when a report\n// cites several, so `rule=` never silently drops one.\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction blockingRule(report: string, fallback: string): string {\n const names = extractRuleNames(report);\n return names.length > 0 ? names.join(',') : fallback;\n}\n\n// webpieces-disable no-function-outside-class -- sibling of handleRead()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction handleBash(event: AgentHookEvent, cwd: string, mode: HookMode): never {\n const command = event.bash === null ? '' : event.bash.command;\n if (command.trim() === '') { emitAllow(); }\n\n // READ PARITY, and it can only ever be reached from a Codex event: the adapter leaves `reads`\n // empty for Claude Code, which has a real `Read` tool and its own fast path. A Codex read arrives\n // as `Bash` running a pager, so without this the read guard and the `calls/` audit trail see none\n // of them. The command is STILL run through the bash guards below — this adds a verdict, it never\n // replaces one.\n for (const readPath of event.reads) {\n handleRead(event, readPath, cwd, mode);\n }\n\n // The HARNESS travels with the command. Fault C and fault Y are decided inside the runner, and\n // both consult the L0 allowlist — which since the gated entry exists cannot be asked without\n // knowing who is calling. `event.aiType` is the adapter's answer, the same one that routed this\n // call to the Codex read-parity loop above.\n const result = runBash(command, cwd, mode, event.aiType);\n if (!result) {\n // ALLOWED — so if this call submits a reviewer verdict, record who is submitting it before the\n // command runs. `wp-write-review` cannot learn that from its env (see ReviewIdentityStamper).\n REVIEW_IDENTITY_STAMPER.stamp(event, command, cwd);\n emitAllow();\n }\n // NO DECISION LINE HERE. This used to write a generic `bash-guard` line because a Bash deny once\n // had no audit trail at all — but every layer now records its own: L1 into `L1-location/` with its\n // row, L2's guards into `L2-decisions/` with their rule and cache, and emitDeny below stamps the\n // call-level outcome onto `calls/`. So this was the THIRD line for one block, and the worst of the\n // three: it re-resolved the root from `cwd` via RepoRootFinder, which is not necessarily the tree\n // the guard actually judged, so a `cd`-relocated command scattered one block across two different\n // `.webpieces` directories.\n //\n // Bash deny → the event's kind is 'Bash', so denyJson adds the ANSI-red systemMessage (the only\n // field a Bash deny shows the human; permissionDecisionReason is invisible on Bash). See\n // agent-response.ts.\n emitDeny(event, result.report, blockingRule(result.report, 'bash-guard'), result.fault);\n}\n\n/**\n * The read-scoped guard pass. Returns normally to ALLOW; only calls emitDeny when the guard fires.\n *\n * Wrapped in its own catch that swallows into an allow. Every other path in this hook fails CLOSED,\n * and that is right for edits and shell commands — but a crash here would block the agent from\n * READING, which includes reading webpieces.config.json to turn the offending guard off. So this one\n * path deliberately inverts the policy: a broken read-guard degrades to a no-op, never to a wedge.\n */\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction handleRead(event: AgentHookEvent, filePath: string, cwd: string, mode: HookMode): void {\n if (filePath === '') return;\n let result: BlockedResult | null = null;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n result = runRead(filePath, cwd, mode);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return; // fail OPEN — see the doc comment\n }\n if (!result) return;\n logRejection('Read', new NormalizedToolInput(filePath, []), result, cwd);\n emitDeny(event, result.report, blockingRule(result.report, 'read-guard'), result.fault);\n}\n\n/**\n * Read-only tools (Read): audit-log, warm the main-sync cache, then run the ONE read-scoped guard\n * (read-stale-guard) and allow. Runs BEFORE the general rule engine — no code-style rule ever sees a\n * Read, and the only way this path can deny is a stale `main`. The audit trail still records every\n * file the AI opened (see setup.ts).\n *\n * Returns normally ONLY when the event is not a Read; otherwise it ends the invocation.\n */\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction handleReadFastPath(event: AgentHookEvent, cwd: string, mode: HookMode): void {\n if (event.kind !== 'Read') return;\n const readPath = event.reads.length > 0 ? event.reads[0] : '';\n if (mode !== 'rules') {\n invocationLog.begin(cwd, event.rawToolName, readPath);\n // Reads vastly outnumber edits, so refreshing here is what actually keeps the shared\n // main-sync cache warm for feature-branch-guard. Detached; never slows the read.\n triggerMainSyncRefresh(cwd, branchStateHangTimeoutFor(cwd));\n }\n handleRead(event, readPath, cwd, mode);\n emitAllow();\n}\n\n/**\n * The file/edit pipeline, run once per file the call touches.\n *\n * `event.files` is a LIST because ONE Codex `apply_patch` carries many files with mixed operations.\n * A Claude Code event always has exactly one entry, so the loop runs once and the behaviour is the\n * single-file behaviour it has always had.\n */\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleRead() in this module; the adapter is module-scope functions by design\nfunction handleFileTool(event: AgentHookEvent, cwd: string, mode: HookMode): never {\n if (event.files.length === 0) { emitAllow(); }\n\n // A Codex SUBAGENT writing into the tree it shares with its coordinator. Returns null for every\n // Claude Code event — that harness can hand a subagent its own worktree, and does.\n const subagentBlock = SUBAGENT_GUARD.check(event, new RepoRootFinder().resolveRepoRoot(cwd));\n if (subagentBlock) {\n emitDeny(event, subagentBlock.report, CODEX_SUBAGENT_RULE, subagentBlock.fault);\n }\n\n for (const file of event.files) {\n handleOneFile(event, file, cwd, mode);\n }\n emitAllow();\n}\n\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction handleOneFile(event: AgentHookEvent, file: FileOperation, cwd: string, mode: HookMode): void {\n const input = file.input;\n\n // Always allow edits to webpieces.config.json — it's the fix target when the config is broken.\n // This returns BEFORE run(), so feature-branch-guard never sees a config edit; record that so the\n // audit trail explains why a config edit on a bad branch was not blocked (see decision-log.ts).\n if (path.basename(input.filePath) === CONFIG_FILENAME) {\n if (mode !== 'rules') {\n // `.webpieces/` (the decision log + sync cache these two calls write) lives at the repo\n // root, not the AI's cwd — resolve it so a config edit from a subdir doesn't create a\n // stray `<subdir>/.webpieces` tree.\n const root = new RepoRootFinder().resolveRepoRoot(cwd);\n logGuardDecision(\n root,\n new GuardDecision('feature-branch-guard', file.toolKind, input.filePath, branchForLog(root), 'ALLOW_EXEMPT', 'config-bypass (feature-branch-guard skipped)', '-', L0_FAULT_NONE, matrixL2Row('config-bypass (feature-branch-guard skipped)')),\n );\n // The guard's own refresh trigger lives inside its check(), which we skip here — so warm\n // the cache directly, otherwise a session that only edits webpieces.config.json never\n // refreshes the sync status. Fire-and-forget; never blocks the edit.\n triggerMainSyncRefresh(root, branchStateHangTimeoutFor(cwd));\n }\n return;\n }\n\n const result = run(file.toolKind, input, cwd, mode);\n if (!result) return;\n\n logRejection(file.toolKind, input, result, cwd);\n // File-tool deny → the event's kind is 'File', so denyJson omits systemMessage (the reason\n // already renders red natively for these tools). See agent-response.ts.\n emitDeny(event, result.report, blockingRule(result.report, 'file-guard'), result.fault);\n}\n\n// What a stale committed shim lets through — now a thin adapter over the ONE L0 allowlist (isAllowed in\n// ../bin/shim), not a list of its own. A stale shim must NEVER trap the actions needed to recover: the\n// original \"block everything but the cures\" version also shadowed the always-allowed\n// webpieces.config.json edit (handleFileTool) and blocked reads, so a repo that ALSO needed its config\n// fixed would deadlock — blocked from editing the one file whose edit is normally always allowed, and\n// blocked from reading it to know how.\n//\n// It used to carry its OWN narrower list (isShimCureCommand: the three shim cures only), and that\n// narrowness was a defect, not a safety property: `pnpm install` and `git pull` — the two commands that\n// resolve the version disagreement underneath a stale shim — were denied. Consulting the shared\n// allowlist fixes that by construction.\n//\n// What is NOT a defect, and must not be \"fixed\": those cures rewrite the committed shim from the\n// INSTALLED binary's renderShim(), overwriting whatever was there. That is the invariant, not\n// collateral damage. The shim (D/X/K, in POSIX sh, pre-binary) and this binary (S/C/Y, in JS) are two\n// halves of ONE L0 and they exchange assumptions — the shim parses file_path and carries ALLOW-READ /\n// ALLOW-CONFIG entries this binary relies on. Pair a binary with a shim rendered by a DIFFERENT\n// release and L0 acquires holes that nothing reports. So the rule is absolute: the committed shim\n// equals renderShim() of the binary in node_modules, and a cure that forces that is the cure working.\n// See healShim's header, which states the same invariant from the other side.\n//\n// Corollary for anyone regenerating the shim in a webpieces PR: commit `templates/ai-hook.sh` (source,\n// locked to renderShim() by unit test) and leave `.claude/webpieces/ai-hook.sh` (generated artifact)\n// alone. In THIS repo the local source runs ahead of the pinned node_modules, so committing a shim\n// rendered from local source produces a commit whose shim and whose @webpieces pin come from different\n// releases — precisely the mismatch above. The artifact heals on the next upgrade; that is its job.\n//\n// - 'allow-cure' → a Bash cure on the allowlist: emitAllow directly, bypassing the git guards.\n// - 'pass' → a recovery action the normal flow already permits, so fall THROUGH and let it: ANY\n// Read (you must read to know how to fix — see handleRead, which itself fails open),\n// or an edit to webpieces.config.json (the always-allowed recovery target).\n// - 'deny' → all OTHER work: blocked until the committed shim matches renderShim() again.\nexport type ShimStaleDecision = 'allow-cure' | 'pass' | 'deny';\n// webpieces-disable no-function-outside-class -- pure decision helper beside the adapter's other module-scope functions; exported for direct unit testing.\nexport function shimStaleRecoveryDecision(toolName: string, command: string, filePath: string, aiType: AiType): ShimStaleDecision {\n const allowed = isAllowed(toolName, command, filePath, aiType);\n if (allowed === 'pass') return 'pass';\n if (allowed === 'allow') return 'allow-cure';\n return 'deny';\n}\n\n// MANAGED-HOOK-SURFACE self-guard, moved here from the rendered shim (2026-07-24) and widened from one\n// file to three (2026-08-07). The committed\n// .claude/webpieces/ai-hook.sh is webpieces-MANAGED and generated from renderShim(); if it no longer\n// matches, it was reverted / hand-edited / predates this binary, so its OWN fail-closed logic can't be\n// trusted. We are the CURRENT binary from node_modules — the trustworthy party — so WE decide here\n// instead of the (possibly stale) shim. It used to `cmp` itself inside the shim: a double-edged trap,\n// since the check lived in the very file it guarded and a fix could only ship by regenerating that\n// file. Now we fail closed on all real WORK while always leaving the recovery path open (see\n// shimStaleRecoveryDecision): the whole L0 allowlist, any Read, and editing webpieces.config.json. We deny +\n// tell the AI; we do NOT silently rewrite the file under it. 'rules' hook skips it (guards owns the\n// shim). Returns normally (pass / nothing to do) or exits via emitAllow/emitDeny.\n//\n// It asks the allowlist about the RAW WIRE FIELDS, not about the normalized event, and that ordering is\n// deliberate: L0 has to hold on a tree too broken to trust anything above it, including the adapters.\n// The raw fields are the same key names in both harnesses (measured), so one reading serves both, and\n// the answer cannot change because a normalizer changed. `event` is here only to decorate the deny.\n// webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design\nfunction enforceCommittedShim(payload: AgentPayload, event: AgentHookEvent, cwd: string, mode: HookMode): void {\n // ONE root for the whole decision, resolved from the RUNNING MODULE (governingShimRoot), never from\n // `cwd`: the shim file we compare and the renderShim() we compare it TO must come from the same\n // install, or the check straddles two trees and can never converge (see governingShimRoot's header).\n // `cwd` still selects where the L0 matrix doc is dropped — that is a \"where does the AI read\" question,\n // not part of the judgement.\n const shimRoot = governingShimRoot();\n if (mode === 'rules') return;\n // WHICH of the managed things moved — ai-hook.sh, either harness's hook registration\n // (.claude/settings.json, .codex/hooks.json), or the Claude settings' managed env entry (the\n // Bash-cwd pin that keeps a guard's verdict independent of where an earlier `cd` left the shell;\n // see managed-env.ts). Nothing validated the registration before it joined this\n // fault, so a settings file left on a superseded form silently changed WHO GOVERNS, with no signal\n // anywhere — which is the whole reason the registration is a drift surface and not just an install\n // step.\n const drifted = managedSurfaceDrift(shimRoot);\n if (drifted.length === 0) return;\n // The harness comes from the RAW envelope too — `detectAiType` asks one question of one key, so it\n // is as trustworthy here as the wire fields beside it, and it is the PRECISE test the shim's sh half\n // can only approximate. Reading it off the normalized event instead would put a normalizer between\n // L0 and its decision, which is the coupling the paragraph above exists to refuse.\n const decision = shimStaleRecoveryDecision(\n payload.tool_name, payload.tool_input.command ?? '', payload.tool_input.file_path ?? '',\n detectAiType(payload));\n if (decision === 'pass') return;\n if (decision === 'allow-cure') emitAllow();\n // Drop the L0 matrix doc where the AI can read it and point the deny at it — a Read is entry 1 of\n // the same allowlist, so the pointer is always followable. Best-effort: no doc → no pointer.\n const root = new RepoRootFinder().resolveRepoRoot(cwd);\n const docPath = writeGuardMatrixDoc(root);\n // WRITE THE AUDIT LINE HERE. This block happens BEFORE invocationLog.begin() — it has to, since a\n // stale shim invalidates everything downstream — so emitDeny's flush finds nothing pending and an\n // `S` storm left NO trace at all: the one fault most likely to block twenty consecutive tool calls\n // was the one fault the trail could not show. A decision line is the fix that costs no reordering.\n const target = payload.tool_input.command ?? payload.tool_input.file_path ?? '';\n logGuardDecision(\n root,\n new GuardDecision('committed-shim-stale', payload.tool_name, target, branchForLog(root), 'BLOCK_AI_CURE', 'L0 fault S (committed shim != renderShim)', '-', L0_FAULT_SHIM_STALE, MATRIX_L0_BLOCK),\n );\n // L0 fault S in GUARD_MATRIX.md's codebook — named as the blocking rule so the invocation line\n // says WHAT stopped the call, not merely that something did, and stamped as `fault=S` so the same\n // grep finds it here as in the sh half's `L0-shim/` stream.\n // A subagent is discriminated by `agent_id`, which BOTH harnesses populate on stdin only off the\n // main loop (main falls back to the session id / leaves it empty). Its cure differs: the hooks\n // blocking it resolve through CLAUDE_PROJECT_DIR, which names the MAIN tree.\n const inSubagent = event.agentId !== '';\n emitDeny(event, shimStaleDenyReason(installedShimRulesVersion(), shimRoot ?? '', drifted, inSubagent) + guardMatrixPointer(docPath), 'committed-shim-stale', L0_FAULT_SHIM_STALE);\n}\n\n/**\n * THE PIPELINE, from raw stdin bytes to the decision — the whole of `parse -> adapter -> runner ->\n * emit`, as ONE function returning ONE value.\n *\n * `mode` selects which tool kinds to validate; payloads outside the mode's scope pass through\n * (emitAllow). A block is a PreToolUse `permissionDecision:\"deny\"` JSON on stdout with exit 0 — see\n * agent-response.ts. Fails CLOSED on any unexpected crash (returns a deny) so a broken hook never\n * silently lets an edit through, and the reason surfaces in the agent's UI instead of being hidden on\n * a stderr+exit-2 block.\n *\n * It reads NO stdin, writes NO stdout and calls NO exit: those three couplings are ports owned by\n * HookApp (see hook-ports.ts), which is what makes the composed pipeline drivable from a test. This\n * function is what `runMain` was; it is not a second spelling of it — `runMain` is deleted, and\n * `HookApp.run()` is the only entry point.\n */\n// webpieces-disable no-function-outside-class -- the module-scope hook body itself, sibling of handleBash()/handleFileTool(); the adapter is module-scope functions by design and must stay callable from a tree too broken to build a DI container\nexport function runPipeline(raw: string, mode: HookMode): HookOutcome {\n // Captured as soon as the ENVELOPE parses so the fail-closed catch below can tell denyJson which\n // kind of call it is denying — a crash on a Bash call still gets the visible red systemMessage, a\n // crash on a file tool does not. Null (before parse / malformed input) → treated as non-Bash.\n let event: AgentHookEvent | null = null;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const payload = new AgentPayloadParser().parse(raw);\n if (!payload) { emitAllow(); }\n // The envelope shape first: it reads only `tool_name` and the identity fields, so it cannot\n // fail, and it is what the crash path needs. The full normalization below reads `tool_input`\n // and CAN fail (a malformed Codex patch envelope denies rather than being half-understood).\n event = ADAPTERS.envelope(payload);\n\n // BEFORE enforceCommittedShim(), which can itself write a BLOCK line. See LogStream for why\n // all three of session/agent/hook are needed to keep concurrent writers off one file.\n logStream.identify(new StreamIdentity(event.sessionId, event.agentId, mode));\n // Same moment, same reason: every JS-side stream stamps `ai=`, and the fault-S line written\n // inside enforceCommittedShim() is one of them. See AiTypeContext for why the harness is a\n // process-wide holder rather than a parameter on four writers.\n aiTypeContext.identify(event.aiType);\n\n // Prefer the payload cwd (the AI's actual working dir, follows a persisted `cd`) over\n // process.cwd(); they match today, but the payload is the authoritative signal and stays\n // correct if the hook is ever invoked from a fixed dir (e.g. via $CLAUDE_PROJECT_DIR).\n const cwd = payload.cwd ?? process.cwd();\n\n // Committed-shim self-guard: blocks real work while the committed shim is stale, but keeps the\n // recovery path open (cures, reads, config edit). See enforceCommittedShim / shimStaleRecoveryDecision.\n enforceCommittedShim(payload, event, cwd, mode);\n\n event = ADAPTERS.toEvent(payload, cwd);\n\n // Read-only tools: their own fast path, which never returns when it applies.\n handleReadFastPath(event, cwd, mode);\n\n // Per-invocation guard log (the `calls/` stream): tool + command/file + live branch +\n // main-sync-status snapshot, on EVERY guards call, for later cleanup automation. Best-effort;\n // never blocks the call. (The committed shim is no longer silently healed here — a mismatch is\n // reported by the self-guard above, not rewritten out from under the AI.)\n if (mode !== 'rules') {\n invocationLog.begin(cwd, event.rawToolName, logTarget(event));\n }\n\n if (event.kind === 'Bash') {\n // No code-style rule is bash-scoped, so the rules hook ignores Bash.\n if (mode === 'rules') { emitAllow(); }\n handleBash(event, cwd, mode);\n }\n\n // File payloads run in 'rules' (code-style), 'guards' (file-scoped guards like\n // feature-branch-guard), and 'all'. The runner filters to the right category.\n handleFileTool(event, cwd, mode);\n } catch (err: unknown) {\n const error = toError(err);\n // The pipeline's own terminal control flow, not a failure: emitAllow/emitDeny threw the answer\n // out to here from wherever they were called. Treating it as a crash would turn every allow\n // into a deny, so this branch comes FIRST and returns the carried outcome verbatim.\n if (error instanceof HookTerminated) return error.outcome;\n return denyForCrash(error, event);\n }\n}\n\n// What the `calls/` audit line names as the call's target: the command for a shell call, else the first\n// file it touches. A Codex `apply_patch` touching several files names the first — the rejection log and\n// the decision log carry the rest, per file.\n// webpieces-disable no-function-outside-class -- sibling of the module-scope hook entry points in this adapter\nfunction logTarget(event: AgentHookEvent): string {\n if (event.kind === 'Bash') return event.bash === null ? '' : event.bash.command;\n return event.files.length > 0 ? event.files[0].input.filePath : '';\n}\n\n/**\n * The fail-closed boundary for anything that escaped the hook body. An escaped RuleFailError (a rule\n * that threw past the runner's per-rule catch) or an InformAiError (bad config/stdin, or a Codex patch\n * envelope this parser refuses to guess at) both carry an AI-readable message; anything else is an\n * unexpected bug. All three DENY and surface their reason, because a hook that crashed established\n * nothing and must never be read as an allow.\n *\n * It BUILDS the deny (denyOutcome) rather than throwing it (emitDeny), because it is already inside\n * the catch that the throw would land in — see HookTerminated. Same bytes either way.\n */\n// webpieces-disable no-function-outside-class -- sibling of the module-scope hook entry points in this adapter; a lone class for one terminal boundary would break the file's shape\nfunction denyForCrash(error: Error, event: AgentHookEvent | null): HookOutcome {\n if (error instanceof RuleFailError) {\n return denyOutcome(event, renderRuleFailForAi(error), 'rule-crash');\n }\n if (error instanceof InformAiError) {\n return denyOutcome(event, error.message, 'bad-config-or-stdin');\n }\n return denyOutcome(event, `[ai-hooks] hook crashed unexpectedly — failing closed: ${error.message}`, 'hook-crash');\n}\n"]}
@@ -40,7 +40,7 @@ async function runDevHookInstall() {
40
40
  throw new rules_config_1.CliExitError(1, `[dev-hook-install] Local rules-config build not found at: ${distRulesConfigPath}\n Run \`pnpm nx run rules-config:build\` first.`);
41
41
  }
42
42
  const homeDir = (0, os_1.homedir)();
43
- const webpiecesDir = (0, path_1.join)(homeDir, '.webpieces-logs');
43
+ const webpiecesDir = (0, path_1.join)(homeDir, '.webpieces');
44
44
  const backupPath = (0, path_1.join)(webpiecesDir, 'dev-hook-backup.json');
45
45
  const claudeSettingsPath = (0, path_1.join)(homeDir, '.claude', 'settings.json');
46
46
  if ((0, fs_1.existsSync)(backupPath)) {
@@ -1 +1 @@
1
- {"version":3,"file":"dev-hook-install.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/bin/dev-hook-install.ts"],"names":[],"mappings":";;AA0CA,8CA4DC;AAtGD,2BAA6F;AAC7F,2BAA6B;AAC7B,+BAAqC;AAC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AAU,EAAC,YAAY,CAAC,EAAE,CAAC;QAC5B,IAAA,cAAS,EAAC,YAAY,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IACjD,CAAC;IACD,IAAA,kBAAa,EAAC,UAAU,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;IAElE,wFAAwF;IACxF,QAAQ,CAAC,KAAK,GAAG;QACb,UAAU,EAAE;YACR;gBACI,OAAO,EAAE,sBAAsB;gBAC/B,KAAK,EAAE,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,QAAQ,aAAa,EAAE,EAAE,CAAC;aACjE;YACD;gBACI,OAAO,EAAE,gCAAgC;gBACzC,KAAK,EAAE,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,QAAQ,cAAc,EAAE,EAAE,CAAC;aAClE;SACJ;KACJ,CAAC;IAEF,IAAA,cAAS,EAAC,IAAA,cAAO,EAAC,kBAAkB,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IAC5D,IAAA,kBAAa,EAAC,kBAAkB,EAAE,IAAI,CAAC,SAAS,CAAC,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;IAE5E,OAAO,CAAC,GAAG,CAAC,gCAAgC,aAAa,kBAAkB,cAAc,WAAW,CAAC,CAAC;IACtG,OAAO,CAAC,GAAG,CAAC,0GAA0G,CAAC,CAAC;AAC5H,CAAC;AAED,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM;IAAE,IAAA,sBAAO,EAAC,iBAAiB,CAAC,CAAC","sourcesContent":["import { existsSync, readFileSync, writeFileSync, mkdirSync, symlinkSync, rmSync } from 'fs';\nimport { homedir } from 'os';\nimport { join, dirname } from 'path';\nimport { runMain, CliExitError } from '@webpieces/rules-config';\n\ninterface HookEntry {\n matcher: string;\n hooks: Array<{ type: string; command: string }>;\n}\n\ninterface ClaudeSettings {\n hooks?: {\n PreToolUse?: HookEntry[];\n };\n // webpieces-disable no-any-unknown -- opaque settings bag; arbitrary keys allowed\n [key: string]: unknown;\n}\n\ninterface DevHookBackup {\n previousHooks: ClaudeSettings['hooks'] | null;\n}\n\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nfunction wireLocalRulesConfig(cwd: string, distRulesConfigPath: string): void {\n // Place the symlink in dist/packages/tooling/node_modules/ — one level above\n // the agent-workflow-rules package output but still below the workspace root node_modules.\n // Node's require() resolution walks up from the requiring file and finds this\n // node_modules entry before reaching the workspace root's stale published package.\n // This directory is NOT wiped by any individual package build (each build only\n // cleans its own output subfolder), so it survives a full workspace build too.\n const overrideDir = join(cwd, 'dist', 'packages', 'tooling', 'node_modules', '@webpieces');\n const overrideLink = join(overrideDir, 'rules-config');\n mkdirSync(overrideDir, { recursive: true });\n if (existsSync(overrideLink)) {\n rmSync(overrideLink, { recursive: true });\n }\n symlinkSync(distRulesConfigPath, overrideLink);\n}\n\n// NOTE: this is a dev-only tool, no longer a `wp-*` bin. Run it directly with node against the local\n// build: `node dist/packages/tooling/agent-workflow-rules/src/bin/dev-hook-install.js`.\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nexport async function runDevHookInstall(): Promise<void> {\n const cwd = process.cwd();\n // Mirror production .claude/settings.json: two independent PreToolUse hooks, one per category.\n const rulesHookPath = join(cwd, 'dist', 'packages', 'tooling', 'ai-hook-rules', 'src', 'adapters', 'rules-hook.js');\n const guardsHookPath = join(cwd, 'dist', 'packages', 'tooling', 'agent-workflow-rules', 'src', 'adapters', 'guards-hook.js');\n\n if (!existsSync(rulesHookPath)) {\n throw new CliExitError(1, `[dev-hook-install] Local build not found at: ${rulesHookPath}\\n Run \\`pnpm nx run ai-hook-rules:build\\` first.`);\n }\n if (!existsSync(guardsHookPath)) {\n throw new CliExitError(1, `[dev-hook-install] Local build not found at: ${guardsHookPath}\\n Run \\`pnpm nx run agent-workflow-rules:build\\` first.`);\n }\n\n const distRulesConfigPath = join(cwd, 'dist', 'packages', 'tooling', 'rules-config');\n if (!existsSync(distRulesConfigPath)) {\n throw new CliExitError(1, `[dev-hook-install] Local rules-config build not found at: ${distRulesConfigPath}\\n Run \\`pnpm nx run rules-config:build\\` first.`);\n }\n\n const homeDir = homedir();\n const webpiecesDir = join(homeDir, '.webpieces-logs');\n const backupPath = join(webpiecesDir, 'dev-hook-backup.json');\n const claudeSettingsPath = join(homeDir, '.claude', 'settings.json');\n\n if (existsSync(backupPath)) {\n throw new CliExitError(1, '[dev-hook-install] Dev hook is already installed (backup file exists).\\n Run `node dist/packages/tooling/agent-workflow-rules/src/bin/dev-hook-uninstall.js` first to remove the current dev hook.');\n }\n\n wireLocalRulesConfig(cwd, distRulesConfigPath);\n\n let settings: ClaudeSettings = {};\n if (existsSync(claudeSettingsPath)) {\n settings = JSON.parse(readFileSync(claudeSettingsPath, 'utf8')) as ClaudeSettings;\n }\n\n // Save whatever hooks exist now (may be undefined/null) so uninstall can restore them\n const backup: DevHookBackup = { previousHooks: settings.hooks ?? null };\n if (!existsSync(webpiecesDir)) {\n mkdirSync(webpiecesDir, { recursive: true });\n }\n writeFileSync(backupPath, JSON.stringify(backup, null, 4) + '\\n');\n\n // Mirror production wiring: rules hook on file tools, guards hook on file + Bash tools.\n settings.hooks = {\n PreToolUse: [\n {\n matcher: 'Write|Edit|MultiEdit',\n hooks: [{ type: 'command', command: `node ${rulesHookPath}` }],\n },\n {\n matcher: 'Write|Edit|MultiEdit|Bash|Read',\n hooks: [{ type: 'command', command: `node ${guardsHookPath}` }],\n },\n ],\n };\n\n mkdirSync(dirname(claudeSettingsPath), { recursive: true });\n writeFileSync(claudeSettingsPath, JSON.stringify(settings, null, 4) + '\\n');\n\n console.log(` Dev hooks installed → node ${rulesHookPath} (rules), node ${guardsHookPath} (guards)`);\n console.log(' Run `node dist/packages/tooling/agent-workflow-rules/src/bin/dev-hook-uninstall.js` when done testing.');\n}\n\nif (require.main === module) runMain(runDevHookInstall);\n"]}
1
+ {"version":3,"file":"dev-hook-install.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/bin/dev-hook-install.ts"],"names":[],"mappings":";;AA0CA,8CA4DC;AAtGD,2BAA6F;AAC7F,2BAA6B;AAC7B,+BAAqC;AACrC,0DAAgE;AAmBhE,gKAAgK;AAChK,SAAS,oBAAoB,CAAC,GAAW,EAAE,mBAA2B;IAClE,6EAA6E;IAC7E,2FAA2F;IAC3F,8EAA8E;IAC9E,mFAAmF;IACnF,+EAA+E;IAC/E,+EAA+E;IAC/E,MAAM,WAAW,GAAG,IAAA,WAAI,EAAC,GAAG,EAAE,MAAM,EAAE,UAAU,EAAE,SAAS,EAAE,cAAc,EAAE,YAAY,CAAC,CAAC;IAC3F,MAAM,YAAY,GAAG,IAAA,WAAI,EAAC,WAAW,EAAE,cAAc,CAAC,CAAC;IACvD,IAAA,cAAS,EAAC,WAAW,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IAC5C,IAAI,IAAA,eAAU,EAAC,YAAY,CAAC,EAAE,CAAC;QAC3B,IAAA,WAAM,EAAC,YAAY,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IAC9C,CAAC;IACD,IAAA,gBAAW,EAAC,mBAAmB,EAAE,YAAY,CAAC,CAAC;AACnD,CAAC;AAED,qGAAqG;AACrG,wFAAwF;AACxF,gKAAgK;AACzJ,KAAK,UAAU,iBAAiB;IACnC,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,EAAE,CAAC;IAC1B,+FAA+F;IAC/F,MAAM,aAAa,GAAG,IAAA,WAAI,EAAC,GAAG,EAAE,MAAM,EAAE,UAAU,EAAE,SAAS,EAAE,eAAe,EAAE,KAAK,EAAE,UAAU,EAAE,eAAe,CAAC,CAAC;IACpH,MAAM,cAAc,GAAG,IAA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;AAED,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM;IAAE,IAAA,sBAAO,EAAC,iBAAiB,CAAC,CAAC","sourcesContent":["import { existsSync, readFileSync, writeFileSync, mkdirSync, symlinkSync, rmSync } from 'fs';\nimport { homedir } from 'os';\nimport { join, dirname } from 'path';\nimport { runMain, CliExitError } from '@webpieces/rules-config';\n\ninterface HookEntry {\n matcher: string;\n hooks: Array<{ type: string; command: string }>;\n}\n\ninterface ClaudeSettings {\n hooks?: {\n PreToolUse?: HookEntry[];\n };\n // webpieces-disable no-any-unknown -- opaque settings bag; arbitrary keys allowed\n [key: string]: unknown;\n}\n\ninterface DevHookBackup {\n previousHooks: ClaudeSettings['hooks'] | null;\n}\n\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nfunction wireLocalRulesConfig(cwd: string, distRulesConfigPath: string): void {\n // Place the symlink in dist/packages/tooling/node_modules/ — one level above\n // the agent-workflow-rules package output but still below the workspace root node_modules.\n // Node's require() resolution walks up from the requiring file and finds this\n // node_modules entry before reaching the workspace root's stale published package.\n // This directory is NOT wiped by any individual package build (each build only\n // cleans its own output subfolder), so it survives a full workspace build too.\n const overrideDir = join(cwd, 'dist', 'packages', 'tooling', 'node_modules', '@webpieces');\n const overrideLink = join(overrideDir, 'rules-config');\n mkdirSync(overrideDir, { recursive: true });\n if (existsSync(overrideLink)) {\n rmSync(overrideLink, { recursive: true });\n }\n symlinkSync(distRulesConfigPath, overrideLink);\n}\n\n// NOTE: this is a dev-only tool, no longer a `wp-*` bin. Run it directly with node against the local\n// build: `node dist/packages/tooling/agent-workflow-rules/src/bin/dev-hook-install.js`.\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nexport async function runDevHookInstall(): Promise<void> {\n const cwd = process.cwd();\n // Mirror production .claude/settings.json: two independent PreToolUse hooks, one per category.\n const rulesHookPath = join(cwd, 'dist', 'packages', 'tooling', 'ai-hook-rules', 'src', 'adapters', 'rules-hook.js');\n const guardsHookPath = join(cwd, 'dist', 'packages', 'tooling', 'agent-workflow-rules', 'src', 'adapters', 'guards-hook.js');\n\n if (!existsSync(rulesHookPath)) {\n throw new CliExitError(1, `[dev-hook-install] Local build not found at: ${rulesHookPath}\\n Run \\`pnpm nx run ai-hook-rules:build\\` first.`);\n }\n if (!existsSync(guardsHookPath)) {\n throw new CliExitError(1, `[dev-hook-install] Local build not found at: ${guardsHookPath}\\n Run \\`pnpm nx run agent-workflow-rules:build\\` first.`);\n }\n\n const distRulesConfigPath = join(cwd, 'dist', 'packages', 'tooling', 'rules-config');\n if (!existsSync(distRulesConfigPath)) {\n throw new CliExitError(1, `[dev-hook-install] Local rules-config build not found at: ${distRulesConfigPath}\\n Run \\`pnpm nx run rules-config:build\\` first.`);\n }\n\n const homeDir = homedir();\n const webpiecesDir = join(homeDir, '.webpieces');\n const backupPath = join(webpiecesDir, 'dev-hook-backup.json');\n const claudeSettingsPath = join(homeDir, '.claude', 'settings.json');\n\n if (existsSync(backupPath)) {\n throw new CliExitError(1, '[dev-hook-install] Dev hook is already installed (backup file exists).\\n Run `node dist/packages/tooling/agent-workflow-rules/src/bin/dev-hook-uninstall.js` first to remove the current dev hook.');\n }\n\n wireLocalRulesConfig(cwd, distRulesConfigPath);\n\n let settings: ClaudeSettings = {};\n if (existsSync(claudeSettingsPath)) {\n settings = JSON.parse(readFileSync(claudeSettingsPath, 'utf8')) as ClaudeSettings;\n }\n\n // Save whatever hooks exist now (may be undefined/null) so uninstall can restore them\n const backup: DevHookBackup = { previousHooks: settings.hooks ?? null };\n if (!existsSync(webpiecesDir)) {\n mkdirSync(webpiecesDir, { recursive: true });\n }\n writeFileSync(backupPath, JSON.stringify(backup, null, 4) + '\\n');\n\n // Mirror production wiring: rules hook on file tools, guards hook on file + Bash tools.\n settings.hooks = {\n PreToolUse: [\n {\n matcher: 'Write|Edit|MultiEdit',\n hooks: [{ type: 'command', command: `node ${rulesHookPath}` }],\n },\n {\n matcher: 'Write|Edit|MultiEdit|Bash|Read',\n hooks: [{ type: 'command', command: `node ${guardsHookPath}` }],\n },\n ],\n };\n\n mkdirSync(dirname(claudeSettingsPath), { recursive: true });\n writeFileSync(claudeSettingsPath, JSON.stringify(settings, null, 4) + '\\n');\n\n console.log(` Dev hooks installed → node ${rulesHookPath} (rules), node ${guardsHookPath} (guards)`);\n console.log(' Run `node dist/packages/tooling/agent-workflow-rules/src/bin/dev-hook-uninstall.js` when done testing.');\n}\n\nif (require.main === module) runMain(runDevHookInstall);\n"]}
@@ -11,7 +11,7 @@ const rules_config_1 = require("@webpieces/rules-config");
11
11
  async function runDevHookUninstall() {
12
12
  const cwd = process.cwd();
13
13
  const homeDir = (0, os_1.homedir)();
14
- const backupPath = (0, path_1.join)(homeDir, '.webpieces-logs', 'dev-hook-backup.json');
14
+ const backupPath = (0, path_1.join)(homeDir, '.webpieces', 'dev-hook-backup.json');
15
15
  const claudeSettingsPath = (0, path_1.join)(homeDir, '.claude', 'settings.json');
16
16
  if (!(0, fs_1.existsSync)(backupPath)) {
17
17
  throw new rules_config_1.CliExitError(1, '[dev-hook-uninstall] No dev hook backup found — dev hook was not installed.');
@@ -1 +1 @@
1
- {"version":3,"file":"dev-hook-uninstall.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/bin/dev-hook-uninstall.ts"],"names":[],"mappings":";;AAyBA,kDAqCC;AA9DD,2BAAkF;AAClF,2BAA6B;AAC7B,+BAA4B;AAC5B,0DAAgE;AAmBhE,qGAAqG;AACrG,0FAA0F;AAC1F,gKAAgK;AACzJ,KAAK,UAAU,mBAAmB;IACrC,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,EAAE,CAAC;IAC1B,MAAM,OAAO,GAAG,IAAA,YAAO,GAAE,CAAC;IAC1B,MAAM,UAAU,GAAG,IAAA,WAAI,EAAC,OAAO,EAAE,iBAAiB,EAAE,sBAAsB,CAAC,CAAC;IAC5E,MAAM,kBAAkB,GA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AI,IAAA,eAAU,EAAC,WAAW,CAAC,IAAI,IAAA,gBAAW,EAAC,WAAW,CAAC,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACnE,IAAA,WAAM,EAAC,WAAW,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IAC7C,CAAC;IAED,OAAO,CAAC,GAAG,CAAC,2DAA2D,CAAC,CAAC;AAC7E,CAAC;AAED,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM;IAAE,IAAA,sBAAO,EAAC,mBAAmB,CAAC,CAAC","sourcesContent":["import { existsSync, readFileSync, writeFileSync, rmSync, readdirSync } from 'fs';\nimport { homedir } from 'os';\nimport { join } from 'path';\nimport { runMain, CliExitError } from '@webpieces/rules-config';\n\ninterface HookEntry {\n matcher: string;\n hooks: Array<{ type: string; command: string }>;\n}\n\ninterface ClaudeSettings {\n hooks?: {\n PreToolUse?: HookEntry[];\n };\n // webpieces-disable no-any-unknown -- opaque settings bag; arbitrary keys allowed\n [key: string]: unknown;\n}\n\ninterface DevHookBackup {\n previousHooks: ClaudeSettings['hooks'] | null;\n}\n\n// NOTE: this is a dev-only tool, no longer a `wp-*` bin. Run it directly with node against the local\n// build: `node dist/packages/tooling/agent-workflow-rules/src/bin/dev-hook-uninstall.js`.\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nexport async function runDevHookUninstall(): Promise<void> {\n const cwd = process.cwd();\n const homeDir = homedir();\n const backupPath = join(homeDir, '.webpieces-logs', 'dev-hook-backup.json');\n const claudeSettingsPath = join(homeDir, '.claude', 'settings.json');\n\n if (!existsSync(backupPath)) {\n throw new CliExitError(1, '[dev-hook-uninstall] No dev hook backup found — dev hook was not installed.');\n }\n\n const backup = JSON.parse(readFileSync(backupPath, 'utf8')) as DevHookBackup;\n\n let settings: ClaudeSettings = {};\n if (existsSync(claudeSettingsPath)) {\n settings = JSON.parse(readFileSync(claudeSettingsPath, 'utf8')) as ClaudeSettings;\n }\n\n if (backup.previousHooks === null) {\n delete settings.hooks;\n } else {\n settings.hooks = backup.previousHooks;\n }\n\n writeFileSync(claudeSettingsPath, JSON.stringify(settings, null, 4) + '\\n');\n rmSync(backupPath);\n\n // Remove the symlink created during install\n const overrideDir = join(cwd, 'dist', 'packages', 'tooling', 'node_modules', '@webpieces');\n const overrideLink = join(overrideDir, 'rules-config');\n if (existsSync(overrideLink)) {\n rmSync(overrideLink, { recursive: true });\n }\n if (existsSync(overrideDir) && readdirSync(overrideDir).length === 0) {\n rmSync(overrideDir, { recursive: true });\n }\n\n console.log(' Dev hook removed. Previous hook configuration restored.');\n}\n\nif (require.main === module) runMain(runDevHookUninstall);\n"]}
1
+ {"version":3,"file":"dev-hook-uninstall.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/bin/dev-hook-uninstall.ts"],"names":[],"mappings":";;AAyBA,kDAqCC;AA9DD,2BAAkF;AAClF,2BAA6B;AAC7B,+BAA4B;AAC5B,0DAAgE;AAmBhE,qGAAqG;AACrG,0FAA0F;AAC1F,gKAAgK;AACzJ,KAAK,UAAU,mBAAmB;IACrC,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,EAAE,CAAC;IAC1B,MAAM,OAAO,GAAG,IAAA,YAAO,GAAE,CAAC;IAC1B,MAAM,UAAU,GAAG,IAAA,WAAI,EAAC,OAAO,EAAE,YAAY,EAAE,sBAAsB,CAAC,CAAC;IACvE,MAAM,kBAAkB,GAAG,IAAA,WAAI,EAAC,OAAO,EAAE,SAAS,EAAE,eAAe,CAAC,CAAC;IAErE,IAAI,CAAC,IAAA,eAAU,EAAC,UAAU,CAAC,EAAE,CAAC;QAC1B,MAAM,IAAI,2BAAY,CAAC,CAAC,EAAE,6EAA6E,CAAC,CAAC;IAC7G,CAAC;IAED,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,IAAA,iBAAY,EAAC,UAAU,EAAE,MAAM,CAAC,CAAkB,CAAC;IAE7E,IAAI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AO,EAAC,mBAAmB,CAAC,CAAC","sourcesContent":["import { existsSync, readFileSync, writeFileSync, rmSync, readdirSync } from 'fs';\nimport { homedir } from 'os';\nimport { join } from 'path';\nimport { runMain, CliExitError } from '@webpieces/rules-config';\n\ninterface HookEntry {\n matcher: string;\n hooks: Array<{ type: string; command: string }>;\n}\n\ninterface ClaudeSettings {\n hooks?: {\n PreToolUse?: HookEntry[];\n };\n // webpieces-disable no-any-unknown -- opaque settings bag; arbitrary keys allowed\n [key: string]: unknown;\n}\n\ninterface DevHookBackup {\n previousHooks: ClaudeSettings['hooks'] | null;\n}\n\n// NOTE: this is a dev-only tool, no longer a `wp-*` bin. Run it directly with node against the local\n// build: `node dist/packages/tooling/agent-workflow-rules/src/bin/dev-hook-uninstall.js`.\n// webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container\nexport async function runDevHookUninstall(): Promise<void> {\n const cwd = process.cwd();\n const homeDir = homedir();\n const backupPath = join(homeDir, '.webpieces', 'dev-hook-backup.json');\n const claudeSettingsPath = join(homeDir, '.claude', 'settings.json');\n\n if (!existsSync(backupPath)) {\n throw new CliExitError(1, '[dev-hook-uninstall] No dev hook backup found — dev hook was not installed.');\n }\n\n const backup = JSON.parse(readFileSync(backupPath, 'utf8')) as DevHookBackup;\n\n let settings: ClaudeSettings = {};\n if (existsSync(claudeSettingsPath)) {\n settings = JSON.parse(readFileSync(claudeSettingsPath, 'utf8')) as ClaudeSettings;\n }\n\n if (backup.previousHooks === null) {\n delete settings.hooks;\n } else {\n settings.hooks = backup.previousHooks;\n }\n\n writeFileSync(claudeSettingsPath, JSON.stringify(settings, null, 4) + '\\n');\n rmSync(backupPath);\n\n // Remove the symlink created during install\n const overrideDir = join(cwd, 'dist', 'packages', 'tooling', 'node_modules', '@webpieces');\n const overrideLink = join(overrideDir, 'rules-config');\n if (existsSync(overrideLink)) {\n rmSync(overrideLink, { recursive: true });\n }\n if (existsSync(overrideDir) && readdirSync(overrideDir).length === 0) {\n rmSync(overrideDir, { recursive: true });\n }\n\n console.log(' Dev hook removed. Previous hook configuration restored.');\n}\n\nif (require.main === module) runMain(runDevHookUninstall);\n"]}
@@ -476,7 +476,7 @@ exports.L0_ALLOWLIST = [
476
476
  new l0_entry_1.L0AllowEntry('CODEX ONLY - a read-shaped Bash command (the harness has no Read tool): ' +
477
477
  `${[...harness_vocabulary_1.READ_COMMANDS].join(', ')}, or sed -n '<range>p'`, 'pass', false, l0_codex_read_1.CODEX_READ_BODY_ERE, l0_codex_read_1.CODEX_READ_BODY_JS, 'codex', new l0_entry_1.L0Call('Bash', l0_codex_read_1.CODEX_READ_CMD, ''), [
478
478
  new l0_entry_1.L0Call('Bash', 'cat webpieces.config.json', ''),
479
- new l0_entry_1.L0Call('Bash', 'head -50 .webpieces-logs/instruct-ai/webpieces.guard-matrix.md', ''),
479
+ new l0_entry_1.L0Call('Bash', 'head -50 .webpieces/instruct-ai/webpieces.guard-matrix.md', ''),
480
480
  new l0_entry_1.L0Call('Bash', 'tail -n 20 package.json', ''),
481
481
  new l0_entry_1.L0Call('Bash', "cat '/Users/dean hiller/repo/package.json'", ''),
482
482
  ]),