@webpieces/agent-workflow-rules 0.0.0-stage → 0.0.1

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 (299) hide show
  1. package/README.md +23 -2
  2. package/package.json +45 -4
  3. package/src/adapters/agent-response.d.ts +5 -0
  4. package/src/adapters/agent-response.js +86 -0
  5. package/src/adapters/agent-response.js.map +1 -0
  6. package/src/adapters/codex-subagent-guard.d.ts +45 -0
  7. package/src/adapters/codex-subagent-guard.js +88 -0
  8. package/src/adapters/codex-subagent-guard.js.map +1 -0
  9. package/src/adapters/guards-hook.d.ts +3 -0
  10. package/src/adapters/guards-hook.js +30 -0
  11. package/src/adapters/guards-hook.js.map +1 -0
  12. package/src/adapters/hook-app-fixtures.d.ts +68 -0
  13. package/src/adapters/hook-app-fixtures.js +170 -0
  14. package/src/adapters/hook-app-fixtures.js.map +1 -0
  15. package/src/adapters/hook-core.d.ts +22 -0
  16. package/src/adapters/hook-core.js +359 -0
  17. package/src/adapters/hook-core.js.map +1 -0
  18. package/src/adapters/hook-pipeline-evaluator.d.ts +5 -0
  19. package/src/adapters/hook-pipeline-evaluator.js +18 -0
  20. package/src/adapters/hook-pipeline-evaluator.js.map +1 -0
  21. package/src/adapters/review-identity-stamper.d.ts +20 -0
  22. package/src/adapters/review-identity-stamper.js +34 -0
  23. package/src/adapters/review-identity-stamper.js.map +1 -0
  24. package/src/bin/codex-trust.d.ts +105 -0
  25. package/src/bin/codex-trust.js +205 -0
  26. package/src/bin/codex-trust.js.map +1 -0
  27. package/src/bin/dev-hook-install.d.ts +1 -0
  28. package/src/bin/dev-hook-install.js +80 -0
  29. package/src/bin/dev-hook-install.js.map +1 -0
  30. package/src/bin/dev-hook-uninstall.d.ts +1 -0
  31. package/src/bin/dev-hook-uninstall.js +45 -0
  32. package/src/bin/dev-hook-uninstall.js.map +1 -0
  33. package/src/bin/hook-registration.d.ts +429 -0
  34. package/src/bin/hook-registration.js +661 -0
  35. package/src/bin/hook-registration.js.map +1 -0
  36. package/src/bin/install-entry.d.ts +19 -0
  37. package/src/bin/install-entry.js +128 -0
  38. package/src/bin/install-entry.js.map +1 -0
  39. package/src/bin/l0-allowlist.d.ts +46 -0
  40. package/src/bin/l0-allowlist.js +527 -0
  41. package/src/bin/l0-allowlist.js.map +1 -0
  42. package/src/bin/l0-codex-read.d.ts +20 -0
  43. package/src/bin/l0-codex-read.js +108 -0
  44. package/src/bin/l0-codex-read.js.map +1 -0
  45. package/src/bin/l0-decide.d.ts +49 -0
  46. package/src/bin/l0-decide.js +90 -0
  47. package/src/bin/l0-decide.js.map +1 -0
  48. package/src/bin/l0-entry.d.ts +103 -0
  49. package/src/bin/l0-entry.js +98 -0
  50. package/src/bin/l0-entry.js.map +1 -0
  51. package/src/bin/l0-ignored-tools.d.ts +38 -0
  52. package/src/bin/l0-ignored-tools.js +44 -0
  53. package/src/bin/l0-ignored-tools.js.map +1 -0
  54. package/src/bin/managed-env.d.ts +46 -0
  55. package/src/bin/managed-env.js +50 -0
  56. package/src/bin/managed-env.js.map +1 -0
  57. package/src/bin/neighbour-hooks.d.ts +42 -0
  58. package/src/bin/neighbour-hooks.js +177 -0
  59. package/src/bin/neighbour-hooks.js.map +1 -0
  60. package/src/bin/reviewer-agent.d.ts +19 -0
  61. package/src/bin/reviewer-agent.js +135 -0
  62. package/src/bin/reviewer-agent.js.map +1 -0
  63. package/src/bin/settings-shape.d.ts +37 -0
  64. package/src/bin/settings-shape.js +17 -0
  65. package/src/bin/settings-shape.js.map +1 -0
  66. package/src/bin/setup-config.d.ts +20 -0
  67. package/src/bin/setup-config.js +371 -0
  68. package/src/bin/setup-config.js.map +1 -0
  69. package/src/bin/setup.d.ts +78 -0
  70. package/src/bin/setup.js +411 -0
  71. package/src/bin/setup.js.map +1 -0
  72. package/src/bin/shim-audit-log.d.ts +119 -0
  73. package/src/bin/shim-audit-log.js +286 -0
  74. package/src/bin/shim-audit-log.js.map +1 -0
  75. package/src/bin/shim-deny-reason.d.ts +1 -0
  76. package/src/bin/shim-deny-reason.js +244 -0
  77. package/src/bin/shim-deny-reason.js.map +1 -0
  78. package/src/bin/shim-drift-fix.d.ts +1 -0
  79. package/src/bin/shim-drift-fix.js +73 -0
  80. package/src/bin/shim-drift-fix.js.map +1 -0
  81. package/src/bin/shim-testkit.d.ts +107 -0
  82. package/src/bin/shim-testkit.js +197 -0
  83. package/src/bin/shim-testkit.js.map +1 -0
  84. package/src/bin/shim-version-drift.d.ts +1 -0
  85. package/src/bin/shim-version-drift.js +164 -0
  86. package/src/bin/shim-version-drift.js.map +1 -0
  87. package/src/bin/shim.d.ts +16 -0
  88. package/src/bin/shim.js +641 -0
  89. package/src/bin/shim.js.map +1 -0
  90. package/src/bin/upgrade-shim.d.ts +18 -0
  91. package/src/bin/upgrade-shim.js +283 -0
  92. package/src/bin/upgrade-shim.js.map +1 -0
  93. package/src/configs/main-sync-guard-configs.d.ts +38 -0
  94. package/src/configs/main-sync-guard-configs.js +54 -0
  95. package/src/configs/main-sync-guard-configs.js.map +1 -0
  96. package/src/configs/rule-configs.d.ts +47 -0
  97. package/src/configs/rule-configs.js +96 -0
  98. package/src/configs/rule-configs.js.map +1 -0
  99. package/src/core/ai-type-context.d.ts +36 -0
  100. package/src/core/ai-type-context.js +45 -0
  101. package/src/core/ai-type-context.js.map +1 -0
  102. package/src/core/decision-log.d.ts +190 -0
  103. package/src/core/decision-log.js +409 -0
  104. package/src/core/decision-log.js.map +1 -0
  105. package/src/core/excluded-path-escape.d.ts +101 -0
  106. package/src/core/excluded-path-escape.js +236 -0
  107. package/src/core/excluded-path-escape.js.map +1 -0
  108. package/src/core/force-to-root.d.ts +32 -0
  109. package/src/core/force-to-root.js +60 -0
  110. package/src/core/force-to-root.js.map +1 -0
  111. package/src/core/guard-index-doc.d.ts +63 -0
  112. package/src/core/guard-index-doc.js +172 -0
  113. package/src/core/guard-index-doc.js.map +1 -0
  114. package/src/core/instruct-ai-writer.d.ts +1 -0
  115. package/src/core/instruct-ai-writer.js +6 -0
  116. package/src/core/instruct-ai-writer.js.map +1 -0
  117. package/src/core/l0-matrix.d.ts +102 -0
  118. package/src/core/l0-matrix.js +357 -0
  119. package/src/core/l0-matrix.js.map +1 -0
  120. package/src/core/l0-tooling-doc.d.ts +45 -0
  121. package/src/core/l0-tooling-doc.js +258 -0
  122. package/src/core/l0-tooling-doc.js.map +1 -0
  123. package/src/core/l1-doc.d.ts +7 -0
  124. package/src/core/l1-doc.js +340 -0
  125. package/src/core/l1-doc.js.map +1 -0
  126. package/src/core/l1-matrix-doc.d.ts +31 -0
  127. package/src/core/l1-matrix-doc.js +111 -0
  128. package/src/core/l1-matrix-doc.js.map +1 -0
  129. package/src/core/l1-rows.d.ts +167 -0
  130. package/src/core/l1-rows.js +262 -0
  131. package/src/core/l1-rows.js.map +1 -0
  132. package/src/core/l2-doc.d.ts +7 -0
  133. package/src/core/l2-doc.js +385 -0
  134. package/src/core/l2-doc.js.map +1 -0
  135. package/src/core/l2-matrix-doc.d.ts +23 -0
  136. package/src/core/l2-matrix-doc.js +72 -0
  137. package/src/core/l2-matrix-doc.js.map +1 -0
  138. package/src/core/l2-row.d.ts +54 -0
  139. package/src/core/l2-row.js +75 -0
  140. package/src/core/l2-row.js.map +1 -0
  141. package/src/core/l2-rows.d.ts +56 -0
  142. package/src/core/l2-rows.js +272 -0
  143. package/src/core/l2-rows.js.map +1 -0
  144. package/src/core/load-rules.d.ts +9 -0
  145. package/src/core/load-rules.js +65 -0
  146. package/src/core/load-rules.js.map +1 -0
  147. package/src/core/log-stream.d.ts +117 -0
  148. package/src/core/log-stream.js +156 -0
  149. package/src/core/log-stream.js.map +1 -0
  150. package/src/core/log-streams.d.ts +48 -0
  151. package/src/core/log-streams.js +55 -0
  152. package/src/core/log-streams.js.map +1 -0
  153. package/src/core/log-target.d.ts +21 -0
  154. package/src/core/log-target.js +29 -0
  155. package/src/core/log-target.js.map +1 -0
  156. package/src/core/main-sync-log.d.ts +16 -0
  157. package/src/core/main-sync-log.js +108 -0
  158. package/src/core/main-sync-log.js.map +1 -0
  159. package/src/core/main-sync-refresh.d.ts +39 -0
  160. package/src/core/main-sync-refresh.js +96 -0
  161. package/src/core/main-sync-refresh.js.map +1 -0
  162. package/src/core/main-sync-timeout.d.ts +33 -0
  163. package/src/core/main-sync-timeout.js +95 -0
  164. package/src/core/main-sync-timeout.js.map +1 -0
  165. package/src/core/matrix-cures.d.ts +12 -0
  166. package/src/core/matrix-cures.js +56 -0
  167. package/src/core/matrix-cures.js.map +1 -0
  168. package/src/core/missing-directory.d.ts +38 -0
  169. package/src/core/missing-directory.js +66 -0
  170. package/src/core/missing-directory.js.map +1 -0
  171. package/src/core/read-only-inspection.d.ts +34 -0
  172. package/src/core/read-only-inspection.js +88 -0
  173. package/src/core/read-only-inspection.js.map +1 -0
  174. package/src/core/rejection-log.d.ts +9 -0
  175. package/src/core/rejection-log.js +262 -0
  176. package/src/core/rejection-log.js.map +1 -0
  177. package/src/core/rules/branch-creation-guard.d.ts +113 -0
  178. package/src/core/rules/branch-creation-guard.js +425 -0
  179. package/src/core/rules/branch-creation-guard.js.map +1 -0
  180. package/src/core/rules/branch-switch-scan.d.ts +43 -0
  181. package/src/core/rules/branch-switch-scan.js +132 -0
  182. package/src/core/rules/branch-switch-scan.js.map +1 -0
  183. package/src/core/rules/build-output-pipe-guard.d.ts +56 -0
  184. package/src/core/rules/build-output-pipe-guard.js +120 -0
  185. package/src/core/rules/build-output-pipe-guard.js.map +1 -0
  186. package/src/core/rules/build-output-pipe-scan.d.ts +47 -0
  187. package/src/core/rules/build-output-pipe-scan.js +84 -0
  188. package/src/core/rules/build-output-pipe-scan.js.map +1 -0
  189. package/src/core/rules/cap-remedies.d.ts +39 -0
  190. package/src/core/rules/cap-remedies.js +59 -0
  191. package/src/core/rules/cap-remedies.js.map +1 -0
  192. package/src/core/rules/commit-message-substitution-guard.d.ts +72 -0
  193. package/src/core/rules/commit-message-substitution-guard.js +134 -0
  194. package/src/core/rules/commit-message-substitution-guard.js.map +1 -0
  195. package/src/core/rules/commit-message-substitution-scan.d.ts +42 -0
  196. package/src/core/rules/commit-message-substitution-scan.js +145 -0
  197. package/src/core/rules/commit-message-substitution-scan.js.map +1 -0
  198. package/src/core/rules/content-read-scan.d.ts +76 -0
  199. package/src/core/rules/content-read-scan.js +176 -0
  200. package/src/core/rules/content-read-scan.js.map +1 -0
  201. package/src/core/rules/cure-prefix-scan.d.ts +64 -0
  202. package/src/core/rules/cure-prefix-scan.js +133 -0
  203. package/src/core/rules/cure-prefix-scan.js.map +1 -0
  204. package/src/core/rules/feature-branch-guard.d.ts +121 -0
  205. package/src/core/rules/feature-branch-guard.js +327 -0
  206. package/src/core/rules/feature-branch-guard.js.map +1 -0
  207. package/src/core/rules/index.d.ts +1 -0
  208. package/src/core/rules/index.js +5 -0
  209. package/src/core/rules/index.js.map +1 -0
  210. package/src/core/rules/judged-tree.d.ts +66 -0
  211. package/src/core/rules/judged-tree.js +97 -0
  212. package/src/core/rules/judged-tree.js.map +1 -0
  213. package/src/core/rules/main-freshness.d.ts +37 -0
  214. package/src/core/rules/main-freshness.js +61 -0
  215. package/src/core/rules/main-freshness.js.map +1 -0
  216. package/src/core/rules/merge-in-progress-guard.d.ts +17 -0
  217. package/src/core/rules/merge-in-progress-guard.js +124 -0
  218. package/src/core/rules/merge-in-progress-guard.js.map +1 -0
  219. package/src/core/rules/merged-branch-bash-guard.d.ts +62 -0
  220. package/src/core/rules/merged-branch-bash-guard.js +171 -0
  221. package/src/core/rules/merged-branch-bash-guard.js.map +1 -0
  222. package/src/core/rules/merged-branch-message.d.ts +59 -0
  223. package/src/core/rules/merged-branch-message.js +137 -0
  224. package/src/core/rules/merged-branch-message.js.map +1 -0
  225. package/src/core/rules/pr-creation-or-push-guard.d.ts +26 -0
  226. package/src/core/rules/pr-creation-or-push-guard.js +150 -0
  227. package/src/core/rules/pr-creation-or-push-guard.js.map +1 -0
  228. package/src/core/rules/pr-merge-guard.d.ts +36 -0
  229. package/src/core/rules/pr-merge-guard.js +87 -0
  230. package/src/core/rules/pr-merge-guard.js.map +1 -0
  231. package/src/core/rules/read-stale-guard.d.ts +136 -0
  232. package/src/core/rules/read-stale-guard.js +328 -0
  233. package/src/core/rules/read-stale-guard.js.map +1 -0
  234. package/src/core/rules/recovery-allowlist.d.ts +49 -0
  235. package/src/core/rules/recovery-allowlist.js +187 -0
  236. package/src/core/rules/recovery-allowlist.js.map +1 -0
  237. package/src/core/rules/redirect-how-to-merge-main.d.ts +16 -0
  238. package/src/core/rules/redirect-how-to-merge-main.js +159 -0
  239. package/src/core/rules/redirect-how-to-merge-main.js.map +1 -0
  240. package/src/core/rules/stale-main-bash-guard.d.ts +198 -0
  241. package/src/core/rules/stale-main-bash-guard.js +363 -0
  242. package/src/core/rules/stale-main-bash-guard.js.map +1 -0
  243. package/src/core/rules/stale-main-message.d.ts +62 -0
  244. package/src/core/rules/stale-main-message.js +102 -0
  245. package/src/core/rules/stale-main-message.js.map +1 -0
  246. package/src/core/rules/tree-recovery.d.ts +92 -0
  247. package/src/core/rules/tree-recovery.js +165 -0
  248. package/src/core/rules/tree-recovery.js.map +1 -0
  249. package/src/core/rules/wait-spin-guard.d.ts +128 -0
  250. package/src/core/rules/wait-spin-guard.js +211 -0
  251. package/src/core/rules/wait-spin-guard.js.map +1 -0
  252. package/src/core/rules/wait-spin-scan.d.ts +118 -0
  253. package/src/core/rules/wait-spin-scan.js +203 -0
  254. package/src/core/rules/wait-spin-scan.js.map +1 -0
  255. package/src/core/rules/whole-repo-build-guard.d.ts +125 -0
  256. package/src/core/rules/whole-repo-build-guard.js +257 -0
  257. package/src/core/rules/whole-repo-build-guard.js.map +1 -0
  258. package/src/core/rules/whole-repo-build-scan.d.ts +28 -0
  259. package/src/core/rules/whole-repo-build-scan.js +198 -0
  260. package/src/core/rules/whole-repo-build-scan.js.map +1 -0
  261. package/src/core/runner.d.ts +19 -0
  262. package/src/core/runner.js +482 -0
  263. package/src/core/runner.js.map +1 -0
  264. package/src/core/session-call-history.d.ts +44 -0
  265. package/src/core/session-call-history.js +79 -0
  266. package/src/core/session-call-history.js.map +1 -0
  267. package/src/core/sync-main.d.ts +46 -0
  268. package/src/core/sync-main.js +176 -0
  269. package/src/core/sync-main.js.map +1 -0
  270. package/src/core/version-sync.d.ts +219 -0
  271. package/src/core/version-sync.js +558 -0
  272. package/src/core/version-sync.js.map +1 -0
  273. package/src/core/webpieces-versions.d.ts +98 -0
  274. package/src/core/webpieces-versions.js +206 -0
  275. package/src/core/webpieces-versions.js.map +1 -0
  276. package/src/core/workflow-hook-rules.d.ts +5 -0
  277. package/src/core/workflow-hook-rules.js +15 -0
  278. package/src/core/workflow-hook-rules.js.map +1 -0
  279. package/src/index.d.ts +11 -0
  280. package/src/index.js +28 -0
  281. package/src/index.js.map +1 -0
  282. package/src/policy-keys.d.ts +2 -0
  283. package/src/policy-keys.js +6 -0
  284. package/src/policy-keys.js.map +1 -0
  285. package/src/rule-migrations.d.ts +3 -0
  286. package/src/rule-migrations.js +22 -0
  287. package/src/rule-migrations.js.map +1 -0
  288. package/src/rule-pack.d.ts +2 -0
  289. package/src/rule-pack.js +20 -0
  290. package/src/rule-pack.js.map +1 -0
  291. package/src/rule-settings.d.ts +5 -0
  292. package/src/rule-settings.js +31 -0
  293. package/src/rule-settings.js.map +1 -0
  294. package/src/safeguard-catalog.d.ts +3 -0
  295. package/src/safeguard-catalog.js +16 -0
  296. package/src/safeguard-catalog.js.map +1 -0
  297. package/templates/ai-hook.sh +497 -0
  298. package/templates/claude-settings-hook.json +28 -0
  299. package/templates/webpieces-reviewer.md +60 -0
@@ -0,0 +1,170 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GoldenRepoBuilder = exports.GOLDEN_FIXTURES = exports.REPO_TOKEN = exports.PreparedFixture = exports.GoldenFixture = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const rule_pack_1 = require("../rule-pack");
6
+ const tooling_testkit_1 = require("@webpieces/tooling-testkit");
7
+ const tooling_testkit_2 = require("@webpieces/tooling-testkit");
8
+ const child_process_1 = require("child_process");
9
+ const fs = tslib_1.__importStar(require("fs"));
10
+ const path = tslib_1.__importStar(require("path"));
11
+ /**
12
+ * THE WIRE BYTES the golden tests drive, and the throwaway repo they are judged against.
13
+ *
14
+ * Everything here exists so a reader can see EXACTLY what a harness sends: the payloads are built from
15
+ * the measured envelope key sets (see the fixture docs on GoldenFixture below), not from anything the
16
+ * hook itself produces, and the repo is a real `git init` with a frozen webpieces.config.json rather
17
+ * than whatever tree the suite happens to be running in. A golden computed against the live repo would
18
+ * change verdict with the branch you are standing on.
19
+ *
20
+ * This is NOT a spec file, deliberately: `tsconfig.lib.json` excludes `*.spec.ts`, so a payload builder
21
+ * living in one would never be type-checked by the build.
22
+ */
23
+ /** How one PreToolUse call is presented to the hook. Data class per CLAUDE.md rule 1. */
24
+ class GoldenFixture {
25
+ /** Stable key into `__goldens__/hook-app-goldens.json`. */
26
+ name;
27
+ /** Which hook binary's mode — `guards` or `rules`. */
28
+ mode;
29
+ /**
30
+ * The raw stdin bytes. A STRING, never an object, because malformed stdin is one of the fixtures
31
+ * and a shape that cannot express "not JSON" would quietly drop the case that matters most.
32
+ */
33
+ stdin;
34
+ /** True ⇒ the fixture repo also gets a `rulesDir` whose one module throws when required. */
35
+ crashingRulesDir;
36
+ constructor(name, mode, stdin, crashingRulesDir = false) {
37
+ this.name = name;
38
+ this.mode = mode;
39
+ this.stdin = stdin;
40
+ this.crashingRulesDir = crashingRulesDir;
41
+ }
42
+ }
43
+ exports.GoldenFixture = GoldenFixture;
44
+ /** A built fixture repo: where it lives, and the stdin bytes with `<REPO>` resolved into it. */
45
+ class PreparedFixture {
46
+ repo;
47
+ root;
48
+ stdin;
49
+ constructor(repo, root, stdin) {
50
+ this.repo = repo;
51
+ this.root = root;
52
+ this.stdin = stdin;
53
+ }
54
+ }
55
+ exports.PreparedFixture = PreparedFixture;
56
+ /**
57
+ * The placeholder that stands for the fixture repo's absolute path, in BOTH directions: payloads are
58
+ * written with it and it is substituted in before the run; golden bytes are compared with the real
59
+ * path substituted back out. Guard reports legitimately name absolute paths (the git-workflow doc
60
+ * pointer, the blocked file), and a golden that hard-coded one machine's `/var/folders/...` would be
61
+ * a golden nobody else could run.
62
+ */
63
+ exports.REPO_TOKEN = '<REPO>';
64
+ const CLAUDE_ENVELOPE = { hook_event_name: 'PreToolUse', session_id: 'sess-golden', transcript_path: '/dev/null', cwd: exports.REPO_TOKEN };
65
+ /**
66
+ * The Codex additions, MEASURED from codex-cli 0.151.0: it uses Claude's key names and merely ADDS
67
+ * `model`, `turn_id`, `tool_use_id` and `permission_mode`. `turn_id` is the one discriminator (see
68
+ * detect-ai.ts). `agent_id` empty ⇒ the coordinator, populated ⇒ a subagent — identical semantics in
69
+ * both harnesses.
70
+ */
71
+ const CODEX_ENVELOPE = { ...CLAUDE_ENVELOPE, model: 'gpt-5-codex', turn_id: 'turn-golden', tool_use_id: 'call_1', permission_mode: 'default', agent_type: 'default', agent_id: '' };
72
+ // Codex's edit tool. MEASURED: the tool is named `apply_patch`, it carries `tool_input.command` (not
73
+ // file_path), hunk headers are a bare `@@`, and ONE patch may carry many files with mixed operations.
74
+ const PATCH_ADD_JS = '*** Begin Patch\n*** Add File: src/foo.js\n+var x = 1;\n*** End Patch\n';
75
+ const PATCH_ADD_TS = '*** Begin Patch\n*** Add File: scripts/added.ts\n+export const b = 2;\n*** End Patch\n';
76
+ /**
77
+ * Serializes ONE PreToolUse envelope to the bytes a harness would put on stdin. A class rather than a
78
+ * module-scope function because that is the repo rule, and the one instance below is built at module
79
+ * load so the fixture table can stay a plain literal list.
80
+ */
81
+ class WirePayload {
82
+ // 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
83
+ write(envelope, toolName, toolInput) {
84
+ return JSON.stringify({ ...envelope, tool_name: toolName, tool_input: toolInput });
85
+ }
86
+ }
87
+ const WIRE = new WirePayload();
88
+ /**
89
+ * ONE fixture per row of the coverage the composed pipeline had none of before: for BOTH harnesses a
90
+ * Bash deny (the ANSI-red systemMessage), a file-tool deny (NO systemMessage), an allow, a read-only
91
+ * tool, malformed stdin, and a fail-closed crash.
92
+ */
93
+ exports.GOLDEN_FIXTURES = [
94
+ // ── Claude Code ────────────────────────────────────────────────────────────────────────────────
95
+ // A Bash deny. `git merge` is blocked on every branch, so this verdict does not depend on repo
96
+ // state — and a Bash deny is the ONE case that carries the red `systemMessage`.
97
+ new GoldenFixture('claude/bash-deny', 'guards', WIRE.write(CLAUDE_ENVELOPE, 'Bash', { command: 'git merge main' })),
98
+ new GoldenFixture('claude/bash-allow', 'guards', WIRE.write(CLAUDE_ENVELOPE, 'Bash', { command: 'echo hi' })),
99
+ // The read-only tool: log-and-allow, and the only guard that can deny it is a stale `main`.
100
+ new GoldenFixture('claude/read-allow', 'guards', WIRE.write(CLAUDE_ENVELOPE, 'Read', { file_path: `${exports.REPO_TOKEN}/f.txt` })),
101
+ // Write / Edit / MultiEdit denies — all three must emit NO systemMessage.
102
+ new GoldenFixture('claude/malformed', 'guards', 'not json at all'),
103
+ // ── Codex ──────────────────────────────────────────────────────────────────────────────────────
104
+ new GoldenFixture('codex/bash-deny', 'guards', WIRE.write(CODEX_ENVELOPE, 'Bash', { command: 'git merge main' })),
105
+ new GoldenFixture('codex/bash-allow', 'guards', WIRE.write(CODEX_ENVELOPE, 'Bash', { command: 'echo hi' })),
106
+ // Codex has no Read tool: a read arrives as `Bash` running a pager, which read parity turns into a
107
+ // read-scoped verdict ON TOP of the bash guards.
108
+ new GoldenFixture('codex/read-allow', 'guards', WIRE.write(CODEX_ENVELOPE, 'Bash', { command: `sed -n '1,240p' ${exports.REPO_TOKEN}/f.txt` })),
109
+ new GoldenFixture('codex/malformed', 'guards', '{"turn_id": broken'),
110
+ ];
111
+ // A rules module that blows up the moment it is required — the shortest honest way to reach the hook's
112
+ // fail-closed boundary from OUTSIDE the hook, i.e. without stubbing anything the pipeline owns.
113
+ const CRASHING_RULE_MODULE = "throw new Error('boom from a custom rule module');\n";
114
+ /**
115
+ * Builds ONE throwaway git repo per fixture and returns it with the payload's `<REPO>` resolved.
116
+ *
117
+ * A FRESH repo per fixture, not one shared: the hook writes `.webpieces/` state (the decision log, the
118
+ * main-sync cache) as it runs, so a shared tree would let fixture N's leftovers decide fixture N+1's
119
+ * verdict — an order-dependent suite, which is the one kind of golden test worse than none.
120
+ *
121
+ * `realpathSync` matters on macOS: `os.tmpdir()` hands back `/var/folders/...` which resolves to
122
+ * `/private/var/...`, and the L1 location guard compares the payload's cwd against the resolved repo
123
+ * root. Without it every fixture denies with "run git from the repo root" instead of the verdict under
124
+ * test.
125
+ */
126
+ class GoldenRepoBuilder {
127
+ configJson;
128
+ constructor() {
129
+ this.configJson = fs.readFileSync(path.join(__dirname, '__goldens__', 'fixture-webpieces.config.json'), 'utf8');
130
+ }
131
+ build(fixture) {
132
+ const root = tooling_testkit_2.specTempDirs.makeReal('wp-hook-golden-');
133
+ const repo = path.join(root, 'repo');
134
+ fs.mkdirSync(repo);
135
+ this.git(repo, 'init -q -b main');
136
+ // The developer's own commit hooks would otherwise fire inside this throwaway repo.
137
+ this.git(repo, 'config core.hooksPath /dev/null');
138
+ this.git(repo, 'config user.email t@t.co');
139
+ this.git(repo, 'config user.name tester');
140
+ fs.writeFileSync(path.join(repo, 'webpieces.config.json'), this.repoConfig(fixture));
141
+ tooling_testkit_1.policyFixture.declareIn(repo, tooling_testkit_1.policyFixture.manifests().map(pack => pack.packageName === rule_pack_1.rulePackManifest.packageName ? rule_pack_1.rulePackManifest : pack));
142
+ fs.writeFileSync(path.join(repo, 'f.txt'), 'hello\n');
143
+ fs.mkdirSync(path.join(repo, 'scripts'));
144
+ fs.writeFileSync(path.join(repo, 'scripts', 'ok.ts'), 'const a = 1;\n');
145
+ if (fixture.crashingRulesDir) {
146
+ fs.mkdirSync(path.join(repo, 'wprules'));
147
+ fs.writeFileSync(path.join(repo, 'wprules', 'crash.js'), CRASHING_RULE_MODULE);
148
+ }
149
+ this.git(repo, 'add -A');
150
+ this.git(repo, 'commit -qm init');
151
+ // A local origin/main, so `origin/main..<branch>` resolves exactly as it does in a real clone.
152
+ this.git(repo, 'update-ref refs/remotes/origin/main HEAD');
153
+ // A feature branch, because that is where an agent actually works.
154
+ this.git(repo, 'checkout -q -b dean/fixture');
155
+ return new PreparedFixture(repo, root, fixture.stdin.split(exports.REPO_TOKEN).join(repo));
156
+ }
157
+ repoConfig(fixture) {
158
+ if (!fixture.crashingRulesDir)
159
+ return this.configJson;
160
+ // 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
161
+ const parsed = JSON.parse(this.configJson);
162
+ parsed['rulesDir'] = ['wprules'];
163
+ return JSON.stringify(parsed, null, 4);
164
+ }
165
+ git(repo, args) {
166
+ (0, child_process_1.execSync)(`git ${args}`, { cwd: repo, encoding: 'utf8' });
167
+ }
168
+ }
169
+ exports.GoldenRepoBuilder = GoldenRepoBuilder;
170
+ //# sourceMappingURL=hook-app-fixtures.js.map
@@ -0,0 +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,4CAAgD;AAChD,gEAA2D;AAC3D,gEAA0D;AAC1D,iDAAyC;AACzC,+CAAyB;AAEzB,mDAA6B;AAK7B;;;;;;;;;;;GAWG;AAEH,yFAAyF;AACzF,MAAa,aAAa;IACtB,2DAA2D;IAClD,IAAI,CAAS;IACtB,sDAAsD;IAC7C,IAAI,CAAW;IACxB;;;OAGG;IACM,KAAK,CAAS;IACvB,4FAA4F;IACnF,gBAAgB,CAAU;IAEnC,YAAY,IAAY,EAAE,IAAc,EAAE,KAAa,EAAE,mBAA4B,KAAK;QACtF,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAA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EO,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;AA7CD,8CA6CC","sourcesContent":["import { 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/**\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 crashingRulesDir: boolean;\n\n constructor(name: string, mode: HookMode, stdin: string, crashingRulesDir: boolean = false) {\n this.name = name;\n this.mode = mode;\n this.stdin = stdin;\n this.crashingRulesDir = crashingRulesDir;\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 = { hook_event_name: 'PreToolUse', session_id: 'sess-golden', transcript_path: '/dev/null', cwd: REPO_TOKEN };\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 = { ...CLAUDE_ENVELOPE, model: 'gpt-5-codex', turn_id: 'turn-golden', tool_use_id: 'call_1', permission_mode: 'default', agent_type: 'default', agent_id: '' };\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 = '*** 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(envelope: Record<string, unknown>, toolName: string, toolInput: Record<string, unknown>): 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('claude/bash-deny', 'guards', WIRE.write(CLAUDE_ENVELOPE, 'Bash', { command: 'git merge main' })),\n new GoldenFixture('claude/bash-allow', 'guards', WIRE.write(CLAUDE_ENVELOPE, 'Bash', { command: 'echo hi' })),\n // The read-only tool: log-and-allow, and the only guard that can deny it is a stale `main`.\n new GoldenFixture('claude/read-allow', 'guards', WIRE.write(CLAUDE_ENVELOPE, 'Read', { file_path: `${REPO_TOKEN}/f.txt` })),\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('codex/bash-deny', 'guards', WIRE.write(CODEX_ENVELOPE, 'Bash', { command: 'git merge main' })),\n new GoldenFixture('codex/bash-allow', 'guards', WIRE.write(CODEX_ENVELOPE, 'Bash', { command: 'echo hi' })),\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('codex/read-allow', 'guards', WIRE.write(CODEX_ENVELOPE, 'Bash', { command: `sed -n '1,240p' ${REPO_TOKEN}/f.txt` })),\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(path.join(__dirname, '__goldens__', 'fixture-webpieces.config.json'), 'utf8');\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 fs.writeFileSync(path.join(repo, 'webpieces.config.json'), this.repoConfig(fixture));\n policyFixture.declareIn(repo, policyFixture.manifests().map(pack => pack.packageName === rulePackManifest.packageName ? rulePackManifest : pack));\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.crashingRulesDir) {\n fs.mkdirSync(path.join(repo, 'wprules'));\n fs.writeFileSync(path.join(repo, 'wprules', 'crash.js'), 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.crashingRulesDir) 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['rulesDir'] = ['wprules'];\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"]}
@@ -0,0 +1,22 @@
1
+ import { HookMode } from '@webpieces/hook-runtime';
2
+ import { AiType } from '@webpieces/hook-runtime';
3
+ import { HookOutcome } from '@webpieces/hook-runtime';
4
+ export type { HookMode };
5
+ export type ShimStaleDecision = 'allow-cure' | 'pass' | 'deny';
6
+ export declare function shimStaleRecoveryDecision(toolName: string, command: string, filePath: string, aiType: AiType): ShimStaleDecision;
7
+ /**
8
+ * THE PIPELINE, from raw stdin bytes to the decision — the whole of `parse -> adapter -> runner ->
9
+ * emit`, as ONE function returning ONE value.
10
+ *
11
+ * `mode` selects which tool kinds to validate; payloads outside the mode's scope pass through
12
+ * (emitAllow). A block is a PreToolUse `permissionDecision:"deny"` JSON on stdout with exit 0 — see
13
+ * agent-response.ts. Fails CLOSED on any unexpected crash (returns a deny) so a broken hook never
14
+ * silently lets an edit through, and the reason surfaces in the agent's UI instead of being hidden on
15
+ * a stderr+exit-2 block.
16
+ *
17
+ * It reads NO stdin, writes NO stdout and calls NO exit: those three couplings are ports owned by
18
+ * HookApp (see hook-ports.ts), which is what makes the composed pipeline drivable from a test. This
19
+ * function is what `runMain` was; it is not a second spelling of it — `runMain` is deleted, and
20
+ * `HookApp.run()` is the only entry point.
21
+ */
22
+ export declare function runPipeline(raw: string, mode: HookMode): HookOutcome;
@@ -0,0 +1,359 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.shimStaleRecoveryDecision = shimStaleRecoveryDecision;
4
+ exports.runPipeline = runPipeline;
5
+ const tslib_1 = require("tslib");
6
+ const path = tslib_1.__importStar(require("path"));
7
+ const runner_1 = require("../core/runner");
8
+ const main_sync_timeout_1 = require("../core/main-sync-timeout");
9
+ const rejection_log_1 = require("../core/rejection-log");
10
+ const decision_log_1 = require("../core/decision-log");
11
+ const main_sync_refresh_1 = require("../core/main-sync-refresh");
12
+ const rules_config_1 = require("@webpieces/rules-config");
13
+ const rules_config_2 = require("@webpieces/rules-config");
14
+ const hook_runtime_1 = require("@webpieces/hook-runtime");
15
+ const tooling_common_1 = require("@webpieces/tooling-common");
16
+ const rules_config_3 = require("@webpieces/rules-config");
17
+ const to_error_1 = require("@webpieces/tooling-common/to-error");
18
+ const agent_response_1 = require("./agent-response");
19
+ const hook_runtime_2 = require("@webpieces/hook-runtime");
20
+ const hook_runtime_3 = require("@webpieces/hook-runtime");
21
+ const hook_runtime_4 = require("@webpieces/hook-runtime");
22
+ const hook_runtime_5 = require("@webpieces/hook-runtime");
23
+ const codex_subagent_guard_1 = require("./codex-subagent-guard");
24
+ const review_identity_stamper_1 = require("./review-identity-stamper");
25
+ const shim_1 = require("../bin/shim");
26
+ const hook_registration_1 = require("../bin/hook-registration");
27
+ const shim_deny_reason_1 = require("../bin/shim-deny-reason");
28
+ const l0_matrix_1 = require("../core/l0-matrix");
29
+ const log_stream_1 = require("../core/log-stream");
30
+ const ai_type_context_1 = require("../core/ai-type-context");
31
+ const rules_config_4 = require("@webpieces/rules-config");
32
+ const ADAPTERS = new hook_runtime_4.AgentAdapters();
33
+ const SUBAGENT_GUARD = new codex_subagent_guard_1.CodexSubagentSharedTreeGuard();
34
+ const REVIEW_IDENTITY_STAMPER = new review_identity_stamper_1.ReviewIdentityStamper();
35
+ // The rule name for a block's audit line: the FIRST rule the report cites, or `fallback` when the
36
+ // report opens with no `[rule]` header (a hand-written guard message). Comma-joined when a report
37
+ // cites several, so `rule=` never silently drops one.
38
+ // webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design
39
+ function blockingRule(report, fallback) {
40
+ const names = (0, rejection_log_1.extractRuleNames)(report);
41
+ return names.length > 0 ? names.join(',') : fallback;
42
+ }
43
+ // webpieces-disable no-function-outside-class -- sibling of handleRead()/handleFileTool() in this module; the adapter is module-scope functions by design
44
+ function handleBash(event, cwd, mode) {
45
+ const command = event.bash === null ? '' : event.bash.command;
46
+ if (command.trim() === '') {
47
+ (0, agent_response_1.emitAllow)();
48
+ }
49
+ // READ PARITY, and it can only ever be reached from a Codex event: the adapter leaves `reads`
50
+ // empty for Claude Code, which has a real `Read` tool and its own fast path. A Codex read arrives
51
+ // as `Bash` running a pager, so without this the read guard and the `calls/` audit trail see none
52
+ // of them. The command is STILL run through the bash guards below — this adds a verdict, it never
53
+ // replaces one.
54
+ for (const readPath of event.reads) {
55
+ handleRead(event, readPath, cwd, mode);
56
+ }
57
+ // The HARNESS travels with the command. Fault C and fault Y are decided inside the runner, and
58
+ // both consult the L0 allowlist — which since the gated entry exists cannot be asked without
59
+ // knowing who is calling. `event.aiType` is the adapter's answer, the same one that routed this
60
+ // call to the Codex read-parity loop above.
61
+ const result = (0, runner_1.runBash)(command, cwd, mode, event.aiType);
62
+ if (!result) {
63
+ // ALLOWED — so if this call submits a reviewer verdict, record who is submitting it before the
64
+ // command runs. `wp-write-review` cannot learn that from its env (see ReviewIdentityStamper).
65
+ REVIEW_IDENTITY_STAMPER.stamp(event, command, cwd);
66
+ (0, agent_response_1.emitAllow)();
67
+ }
68
+ // NO DECISION LINE HERE. This used to write a generic `bash-guard` line because a Bash deny once
69
+ // had no audit trail at all — but every layer now records its own: L1 into `L1-location/` with its
70
+ // row, L2's guards into `L2-decisions/` with their rule and cache, and emitDeny below stamps the
71
+ // call-level outcome onto `calls/`. So this was the THIRD line for one block, and the worst of the
72
+ // three: it re-resolved the root from `cwd` via RepoRootFinder, which is not necessarily the tree
73
+ // the guard actually judged, so a `cd`-relocated command scattered one block across two different
74
+ // `.webpieces` directories.
75
+ //
76
+ // Bash deny → the event's kind is 'Bash', so denyJson adds the ANSI-red systemMessage (the only
77
+ // field a Bash deny shows the human; permissionDecisionReason is invisible on Bash). See
78
+ // agent-response.ts.
79
+ (0, agent_response_1.emitDeny)(event, result.report, blockingRule(result.report, 'bash-guard'), result.fault);
80
+ }
81
+ /**
82
+ * The read-scoped guard pass. Returns normally to ALLOW; only calls emitDeny when the guard fires.
83
+ *
84
+ * Wrapped in its own catch that swallows into an allow. Every other path in this hook fails CLOSED,
85
+ * and that is right for edits and shell commands — but a crash here would block the agent from
86
+ * READING, which includes reading webpieces.config.json to turn the offending guard off. So this one
87
+ * path deliberately inverts the policy: a broken read-guard degrades to a no-op, never to a wedge.
88
+ */
89
+ // webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design
90
+ function handleRead(event, filePath, cwd, mode) {
91
+ if (filePath === '')
92
+ return;
93
+ let result = null;
94
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
95
+ try {
96
+ result = (0, runner_1.runRead)(filePath, cwd, mode);
97
+ }
98
+ catch (err) {
99
+ const error = (0, to_error_1.toError)(err);
100
+ void error;
101
+ return; // fail OPEN — see the doc comment
102
+ }
103
+ if (!result)
104
+ return;
105
+ (0, rejection_log_1.logRejection)('Read', new hook_runtime_1.NormalizedToolInput(filePath, []), result, cwd);
106
+ (0, agent_response_1.emitDeny)(event, result.report, blockingRule(result.report, 'read-guard'), result.fault);
107
+ }
108
+ /**
109
+ * Read-only tools (Read): audit-log, warm the main-sync cache, then run the ONE read-scoped guard
110
+ * (read-stale-guard) and allow. Runs BEFORE the general rule engine — no code-style rule ever sees a
111
+ * Read, and the only way this path can deny is a stale `main`. The audit trail still records every
112
+ * file the AI opened (see setup.ts).
113
+ *
114
+ * Returns normally ONLY when the event is not a Read; otherwise it ends the invocation.
115
+ */
116
+ // webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design
117
+ function handleReadFastPath(event, cwd, mode) {
118
+ if (event.kind !== 'Read')
119
+ return;
120
+ const readPath = event.reads.length > 0 ? event.reads[0] : '';
121
+ if (mode !== 'rules') {
122
+ decision_log_1.invocationLog.begin(cwd, event.rawToolName, readPath);
123
+ // Reads vastly outnumber edits, so refreshing here is what actually keeps the shared
124
+ // main-sync cache warm for feature-branch-guard. Detached; never slows the read.
125
+ (0, main_sync_refresh_1.triggerMainSyncRefresh)(cwd, (0, main_sync_timeout_1.branchStateHangTimeoutFor)(cwd));
126
+ }
127
+ handleRead(event, readPath, cwd, mode);
128
+ (0, agent_response_1.emitAllow)();
129
+ }
130
+ /**
131
+ * The file/edit pipeline, run once per file the call touches.
132
+ *
133
+ * `event.files` is a LIST because ONE Codex `apply_patch` carries many files with mixed operations.
134
+ * A Claude Code event always has exactly one entry, so the loop runs once and the behaviour is the
135
+ * single-file behaviour it has always had.
136
+ */
137
+ // webpieces-disable no-function-outside-class -- sibling of handleBash()/handleRead() in this module; the adapter is module-scope functions by design
138
+ function handleFileTool(event, cwd, mode) {
139
+ if (event.files.length === 0) {
140
+ (0, agent_response_1.emitAllow)();
141
+ }
142
+ // A Codex SUBAGENT writing into the tree it shares with its coordinator. Returns null for every
143
+ // Claude Code event — that harness can hand a subagent its own worktree, and does.
144
+ const subagentBlock = SUBAGENT_GUARD.check(event, new rules_config_2.RepoRootFinder().resolveRepoRoot(cwd));
145
+ if (subagentBlock) {
146
+ (0, agent_response_1.emitDeny)(event, subagentBlock.report, codex_subagent_guard_1.CODEX_SUBAGENT_RULE, subagentBlock.fault);
147
+ }
148
+ for (const file of event.files) {
149
+ handleOneFile(event, file, cwd, mode);
150
+ }
151
+ (0, agent_response_1.emitAllow)();
152
+ }
153
+ // webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design
154
+ function handleOneFile(event, file, cwd, mode) {
155
+ const input = file.input;
156
+ // Always allow edits to webpieces.config.json — it's the fix target when the config is broken.
157
+ // This returns BEFORE run(), so feature-branch-guard never sees a config edit; record that so the
158
+ // audit trail explains why a config edit on a bad branch was not blocked (see decision-log.ts).
159
+ if (path.basename(input.filePath) === rules_config_1.CONFIG_FILENAME) {
160
+ if (mode !== 'rules') {
161
+ // `.webpieces/` (the decision log + sync cache these two calls write) lives at the repo
162
+ // root, not the AI's cwd — resolve it so a config edit from a subdir doesn't create a
163
+ // stray `<subdir>/.webpieces` tree.
164
+ const root = new rules_config_2.RepoRootFinder().resolveRepoRoot(cwd);
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
+ // The guard's own refresh trigger lives inside its check(), which we skip here — so warm
167
+ // the cache directly, otherwise a session that only edits webpieces.config.json never
168
+ // refreshes the sync status. Fire-and-forget; never blocks the edit.
169
+ (0, main_sync_refresh_1.triggerMainSyncRefresh)(root, (0, main_sync_timeout_1.branchStateHangTimeoutFor)(cwd));
170
+ }
171
+ return;
172
+ }
173
+ const result = (0, runner_1.run)(file.toolKind, input, cwd, mode);
174
+ if (!result)
175
+ return;
176
+ (0, rejection_log_1.logRejection)(file.toolKind, input, result, cwd);
177
+ // File-tool deny → the event's kind is 'File', so denyJson omits systemMessage (the reason
178
+ // already renders red natively for these tools). See agent-response.ts.
179
+ (0, agent_response_1.emitDeny)(event, result.report, blockingRule(result.report, 'file-guard'), result.fault);
180
+ }
181
+ // webpieces-disable no-function-outside-class -- pure decision helper beside the adapter's other module-scope functions; exported for direct unit testing.
182
+ function shimStaleRecoveryDecision(toolName, command, filePath, aiType) {
183
+ const allowed = (0, shim_1.isAllowed)(toolName, command, filePath, aiType);
184
+ if (allowed === 'pass')
185
+ return 'pass';
186
+ if (allowed === 'allow')
187
+ return 'allow-cure';
188
+ return 'deny';
189
+ }
190
+ // MANAGED-HOOK-SURFACE self-guard, moved here from the rendered shim (2026-07-24) and widened from one
191
+ // file to three (2026-08-07). The committed
192
+ // .claude/webpieces/ai-hook.sh is webpieces-MANAGED and generated from renderShim(); if it no longer
193
+ // matches, it was reverted / hand-edited / predates this binary, so its OWN fail-closed logic can't be
194
+ // trusted. We are the CURRENT binary from node_modules — the trustworthy party — so WE decide here
195
+ // instead of the (possibly stale) shim. It used to `cmp` itself inside the shim: a double-edged trap,
196
+ // since the check lived in the very file it guarded and a fix could only ship by regenerating that
197
+ // file. Now we fail closed on all real WORK while always leaving the recovery path open (see
198
+ // shimStaleRecoveryDecision): the whole L0 allowlist, any Read, and editing webpieces.config.json. We deny +
199
+ // tell the AI; we do NOT silently rewrite the file under it. 'rules' hook skips it (guards owns the
200
+ // shim). Returns normally (pass / nothing to do) or exits via emitAllow/emitDeny.
201
+ //
202
+ // It asks the allowlist about the RAW WIRE FIELDS, not about the normalized event, and that ordering is
203
+ // deliberate: L0 has to hold on a tree too broken to trust anything above it, including the adapters.
204
+ // The raw fields are the same key names in both harnesses (measured), so one reading serves both, and
205
+ // the answer cannot change because a normalizer changed. `event` is here only to decorate the deny.
206
+ // webpieces-disable no-function-outside-class -- sibling of handleBash()/handleFileTool() in this module; the adapter is module-scope functions by design
207
+ function enforceCommittedShim(payload, event, cwd, mode) {
208
+ // ONE root for the whole decision, resolved from the RUNNING MODULE (governingShimRoot), never from
209
+ // `cwd`: the shim file we compare and the renderShim() we compare it TO must come from the same
210
+ // install, or the check straddles two trees and can never converge (see governingShimRoot's header).
211
+ // `cwd` still selects where the L0 matrix doc is dropped — that is a "where does the AI read" question,
212
+ // not part of the judgement.
213
+ const shimRoot = (0, shim_1.governingShimRoot)();
214
+ if (mode === 'rules')
215
+ return;
216
+ // WHICH of the managed things moved — ai-hook.sh, either harness's hook registration
217
+ // (.claude/settings.json, .codex/hooks.json), or the Claude settings' managed env entry (the
218
+ // Bash-cwd pin that keeps a guard's verdict independent of where an earlier `cd` left the shell;
219
+ // see managed-env.ts). Nothing validated the registration before it joined this
220
+ // fault, so a settings file left on a superseded form silently changed WHO GOVERNS, with no signal
221
+ // anywhere — which is the whole reason the registration is a drift surface and not just an install
222
+ // step.
223
+ const drifted = (0, hook_registration_1.managedSurfaceDrift)(shimRoot);
224
+ if (drifted.length === 0)
225
+ return;
226
+ // The harness comes from the RAW envelope too — `detectAiType` asks one question of one key, so it
227
+ // is as trustworthy here as the wire fields beside it, and it is the PRECISE test the shim's sh half
228
+ // can only approximate. Reading it off the normalized event instead would put a normalizer between
229
+ // L0 and its decision, which is the coupling the paragraph above exists to refuse.
230
+ const decision = shimStaleRecoveryDecision(payload.tool_name, payload.tool_input.command ?? '', payload.tool_input.file_path ?? '', (0, hook_runtime_5.detectAiType)(payload));
231
+ if (decision === 'pass')
232
+ return;
233
+ if (decision === 'allow-cure')
234
+ (0, agent_response_1.emitAllow)();
235
+ // Drop the L0 matrix doc where the AI can read it and point the deny at it — a Read is entry 1 of
236
+ // the same allowlist, so the pointer is always followable. Best-effort: no doc → no pointer.
237
+ const root = new rules_config_2.RepoRootFinder().resolveRepoRoot(cwd);
238
+ const docPath = (0, l0_matrix_1.writeGuardMatrixDoc)(root);
239
+ // WRITE THE AUDIT LINE HERE. This block happens BEFORE invocationLog.begin() — it has to, since a
240
+ // stale shim invalidates everything downstream — so emitDeny's flush finds nothing pending and an
241
+ // `S` storm left NO trace at all: the one fault most likely to block twenty consecutive tool calls
242
+ // was the one fault the trail could not show. A decision line is the fix that costs no reordering.
243
+ const target = payload.tool_input.command ?? payload.tool_input.file_path ?? '';
244
+ (0, decision_log_1.logGuardDecision)(root, new decision_log_1.GuardDecision('committed-shim-stale', payload.tool_name, target, (0, decision_log_1.branchForLog)(root), 'BLOCK_AI_CURE', 'L0 fault S (committed shim != renderShim)', '-', rules_config_4.L0_FAULT_SHIM_STALE, decision_log_1.MATRIX_L0_BLOCK));
245
+ // L0 fault S in GUARD_MATRIX.md's codebook — named as the blocking rule so the invocation line
246
+ // says WHAT stopped the call, not merely that something did, and stamped as `fault=S` so the same
247
+ // grep finds it here as in the sh half's `L0-shim/` stream.
248
+ // A subagent is discriminated by `agent_id`, which BOTH harnesses populate on stdin only off the
249
+ // main loop (main falls back to the session id / leaves it empty). Its cure differs: the hooks
250
+ // blocking it resolve through CLAUDE_PROJECT_DIR, which names the MAIN tree.
251
+ const inSubagent = event.agentId !== '';
252
+ (0, agent_response_1.emitDeny)(event, (0, shim_deny_reason_1.shimStaleDenyReason)((0, shim_1.installedShimRulesVersion)(), shimRoot ?? '', drifted, inSubagent) + (0, l0_matrix_1.guardMatrixPointer)(docPath), 'committed-shim-stale', rules_config_4.L0_FAULT_SHIM_STALE);
253
+ }
254
+ /**
255
+ * THE PIPELINE, from raw stdin bytes to the decision — the whole of `parse -> adapter -> runner ->
256
+ * emit`, as ONE function returning ONE value.
257
+ *
258
+ * `mode` selects which tool kinds to validate; payloads outside the mode's scope pass through
259
+ * (emitAllow). A block is a PreToolUse `permissionDecision:"deny"` JSON on stdout with exit 0 — see
260
+ * agent-response.ts. Fails CLOSED on any unexpected crash (returns a deny) so a broken hook never
261
+ * silently lets an edit through, and the reason surfaces in the agent's UI instead of being hidden on
262
+ * a stderr+exit-2 block.
263
+ *
264
+ * It reads NO stdin, writes NO stdout and calls NO exit: those three couplings are ports owned by
265
+ * HookApp (see hook-ports.ts), which is what makes the composed pipeline drivable from a test. This
266
+ * function is what `runMain` was; it is not a second spelling of it — `runMain` is deleted, and
267
+ * `HookApp.run()` is the only entry point.
268
+ */
269
+ // 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
270
+ function runPipeline(raw, mode) {
271
+ // Captured as soon as the ENVELOPE parses so the fail-closed catch below can tell denyJson which
272
+ // kind of call it is denying — a crash on a Bash call still gets the visible red systemMessage, a
273
+ // crash on a file tool does not. Null (before parse / malformed input) → treated as non-Bash.
274
+ let event = null;
275
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
276
+ try {
277
+ const payload = new hook_runtime_3.AgentPayloadParser().parse(raw);
278
+ if (!payload) {
279
+ (0, agent_response_1.emitAllow)();
280
+ }
281
+ // The envelope shape first: it reads only `tool_name` and the identity fields, so it cannot
282
+ // fail, and it is what the crash path needs. The full normalization below reads `tool_input`
283
+ // and CAN fail (a malformed Codex patch envelope denies rather than being half-understood).
284
+ event = ADAPTERS.envelope(payload);
285
+ // BEFORE enforceCommittedShim(), which can itself write a BLOCK line. See LogStream for why
286
+ // all three of session/agent/hook are needed to keep concurrent writers off one file.
287
+ log_stream_1.logStream.identify(new log_stream_1.StreamIdentity(event.sessionId, event.agentId, mode));
288
+ // Same moment, same reason: every JS-side stream stamps `ai=`, and the fault-S line written
289
+ // inside enforceCommittedShim() is one of them. See AiTypeContext for why the harness is a
290
+ // process-wide holder rather than a parameter on four writers.
291
+ ai_type_context_1.aiTypeContext.identify(event.aiType);
292
+ // Prefer the payload cwd (the AI's actual working dir, follows a persisted `cd`) over
293
+ // process.cwd(); they match today, but the payload is the authoritative signal and stays
294
+ // correct if the hook is ever invoked from a fixed dir (e.g. via $CLAUDE_PROJECT_DIR).
295
+ const cwd = payload.cwd ?? process.cwd();
296
+ // Committed-shim self-guard: blocks real work while the committed shim is stale, but keeps the
297
+ // recovery path open (cures, reads, config edit). See enforceCommittedShim / shimStaleRecoveryDecision.
298
+ enforceCommittedShim(payload, event, cwd, mode);
299
+ event = ADAPTERS.toEvent(payload, cwd);
300
+ // Read-only tools: their own fast path, which never returns when it applies.
301
+ handleReadFastPath(event, cwd, mode);
302
+ // Per-invocation guard log (the `calls/` stream): tool + command/file + live branch +
303
+ // main-sync-status snapshot, on EVERY guards call, for later cleanup automation. Best-effort;
304
+ // never blocks the call. (The committed shim is no longer silently healed here — a mismatch is
305
+ // reported by the self-guard above, not rewritten out from under the AI.)
306
+ if (mode !== 'rules') {
307
+ decision_log_1.invocationLog.begin(cwd, event.rawToolName, logTarget(event));
308
+ }
309
+ if (event.kind === 'Bash') {
310
+ // No code-style rule is bash-scoped, so the rules hook ignores Bash.
311
+ if (mode === 'rules') {
312
+ (0, agent_response_1.emitAllow)();
313
+ }
314
+ handleBash(event, cwd, mode);
315
+ }
316
+ // File payloads run in 'rules' (code-style), 'guards' (file-scoped guards like
317
+ // feature-branch-guard), and 'all'. The runner filters to the right category.
318
+ handleFileTool(event, cwd, mode);
319
+ }
320
+ catch (err) {
321
+ const error = (0, to_error_1.toError)(err);
322
+ // The pipeline's own terminal control flow, not a failure: emitAllow/emitDeny threw the answer
323
+ // out to here from wherever they were called. Treating it as a crash would turn every allow
324
+ // into a deny, so this branch comes FIRST and returns the carried outcome verbatim.
325
+ if (error instanceof hook_runtime_2.HookTerminated)
326
+ return error.outcome;
327
+ return denyForCrash(error, event);
328
+ }
329
+ }
330
+ // What the `calls/` audit line names as the call's target: the command for a shell call, else the first
331
+ // file it touches. A Codex `apply_patch` touching several files names the first — the rejection log and
332
+ // the decision log carry the rest, per file.
333
+ // webpieces-disable no-function-outside-class -- sibling of the module-scope hook entry points in this adapter
334
+ function logTarget(event) {
335
+ if (event.kind === 'Bash')
336
+ return event.bash === null ? '' : event.bash.command;
337
+ return event.files.length > 0 ? event.files[0].input.filePath : '';
338
+ }
339
+ /**
340
+ * The fail-closed boundary for anything that escaped the hook body. An escaped RuleFailError (a rule
341
+ * that threw past the runner's per-rule catch) or an InformAiError (bad config/stdin, or a Codex patch
342
+ * envelope this parser refuses to guess at) both carry an AI-readable message; anything else is an
343
+ * unexpected bug. All three DENY and surface their reason, because a hook that crashed established
344
+ * nothing and must never be read as an allow.
345
+ *
346
+ * It BUILDS the deny (denyOutcome) rather than throwing it (emitDeny), because it is already inside
347
+ * the catch that the throw would land in — see HookTerminated. Same bytes either way.
348
+ */
349
+ // 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
350
+ function denyForCrash(error, event) {
351
+ if (error instanceof rules_config_3.RuleFailError) {
352
+ return (0, agent_response_1.denyOutcome)(event, (0, rules_config_2.renderRuleFailForAi)(error), 'rule-crash');
353
+ }
354
+ if (error instanceof tooling_common_1.InformAiError) {
355
+ return (0, agent_response_1.denyOutcome)(event, error.message, 'bad-config-or-stdin');
356
+ }
357
+ return (0, agent_response_1.denyOutcome)(event, `[ai-hooks] hook crashed unexpectedly — failing closed: ${error.message}`, 'hook-crash');
358
+ }
359
+ //# sourceMappingURL=hook-core.js.map