@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 @@
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;AACn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C,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC;IAChF,OAAO,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC;AACvE,CAAC;AAED;;;;;;;;;GASG;AACH,oLAAoL;AACpL,SAAS,YAAY,CAAC,KAAY,EAAE,KAA4B;IAC5D,IAAI,KAAK,YAAY,4BAAa,EAAE,CAAC;QACjC,OAAO,IAAA,4BAAW,EAAC,KAAK,EAAE,IAAA,kCAAmB,EAAC,KAAK,CAAC,EAAE,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"]}
@@ -0,0 +1,5 @@
1
+ import { HookArgs, HookEvaluator, HookOutcome } from '@webpieces/hook-runtime';
2
+ /** agent-workflow-rules' rule/guard provider, injected into the protocol-only HookApp. */
3
+ export declare class HookPipelineEvaluator extends HookEvaluator {
4
+ evaluate(raw: string, args: HookArgs): HookOutcome;
5
+ }
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HookPipelineEvaluator = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const hook_runtime_1 = require("@webpieces/hook-runtime");
6
+ const inversify_1 = require("inversify");
7
+ const hook_core_1 = require("./hook-core");
8
+ /** agent-workflow-rules' rule/guard provider, injected into the protocol-only HookApp. */
9
+ let HookPipelineEvaluator = class HookPipelineEvaluator extends hook_runtime_1.HookEvaluator {
10
+ evaluate(raw, args) {
11
+ return (0, hook_core_1.runPipeline)(raw, args.mode);
12
+ }
13
+ };
14
+ exports.HookPipelineEvaluator = HookPipelineEvaluator;
15
+ exports.HookPipelineEvaluator = HookPipelineEvaluator = tslib_1.__decorate([
16
+ (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton)
17
+ ], HookPipelineEvaluator);
18
+ //# sourceMappingURL=hook-pipeline-evaluator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hook-pipeline-evaluator.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/adapters/hook-pipeline-evaluator.ts"],"names":[],"mappings":";;;;AAAA,0DAA+E;AAC/E,yCAA2D;AAE3D,2CAA0C;AAE1C,0FAA0F;AAEnF,IAAM,qBAAqB,GAA3B,MAAM,qBAAsB,SAAQ,4BAAa;IAC3C,QAAQ,CAAC,GAAW,EAAE,IAAc;QACzC,OAAO,IAAA,uBAAW,EAAC,GAAG,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;IACvC,CAAC;CACJ,CAAA;AAJY,sDAAqB;gCAArB,qBAAqB;IADjC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;GAC5B,qBAAqB,CAIjC","sourcesContent":["import { HookArgs, HookEvaluator, HookOutcome } from '@webpieces/hook-runtime';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { runPipeline } from './hook-core';\n\n/** agent-workflow-rules' rule/guard provider, injected into the protocol-only HookApp. */\n@injectable(bindingScopeValues.Singleton)\nexport class HookPipelineEvaluator extends HookEvaluator {\n override evaluate(raw: string, args: HookArgs): HookOutcome {\n return runPipeline(raw, args.mode);\n }\n}\n"]}
@@ -0,0 +1,20 @@
1
+ import { ReviewIdentityStampService } from '@webpieces/repo-workflow-core';
2
+ import { AgentHookEvent } from '@webpieces/hook-runtime';
3
+ /**
4
+ * Tells `pnpm wp-write-review` WHO invoked it (issue #863).
5
+ *
6
+ * The bin runs inside the Bash call, and a Bash child sees only its environment — which in neither harness
7
+ * distinguishes a reviewer subagent from its coordinator (see ReviewIdentityStamp for the detail). This
8
+ * hook, by contrast, is handed the harness's own `agent_id` for the very call that is about to run the bin.
9
+ * So for every checklist a command submits, it writes one stamp the bin consumes a moment later. The bin
10
+ * then REFUSES a stamp that names the coordinating agent — closing the forgery path a Codex coordinator
11
+ * took on two merged PRs — and records the subagent's identity in the verdict's provenance.
12
+ *
13
+ * Called ONLY for a Bash call the guards have already ALLOWED: a denied command never runs the bin, and a
14
+ * stamp it left behind would be an identity waiting to be borrowed.
15
+ */
16
+ export declare class ReviewIdentityStamper {
17
+ private readonly stamps;
18
+ constructor(stamps?: ReviewIdentityStampService);
19
+ stamp(event: AgentHookEvent, command: string, cwd: string): void;
20
+ }
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ReviewIdentityStamper = void 0;
4
+ const repo_workflow_core_1 = require("@webpieces/repo-workflow-core");
5
+ /**
6
+ * Tells `pnpm wp-write-review` WHO invoked it (issue #863).
7
+ *
8
+ * The bin runs inside the Bash call, and a Bash child sees only its environment — which in neither harness
9
+ * distinguishes a reviewer subagent from its coordinator (see ReviewIdentityStamp for the detail). This
10
+ * hook, by contrast, is handed the harness's own `agent_id` for the very call that is about to run the bin.
11
+ * So for every checklist a command submits, it writes one stamp the bin consumes a moment later. The bin
12
+ * then REFUSES a stamp that names the coordinating agent — closing the forgery path a Codex coordinator
13
+ * took on two merged PRs — and records the subagent's identity in the verdict's provenance.
14
+ *
15
+ * Called ONLY for a Bash call the guards have already ALLOWED: a denied command never runs the bin, and a
16
+ * stamp it left behind would be an identity waiting to be borrowed.
17
+ */
18
+ class ReviewIdentityStamper {
19
+ stamps;
20
+ constructor(stamps = repo_workflow_core_1.reviewIdentityStamps) {
21
+ this.stamps = stamps;
22
+ }
23
+ stamp(event, command, cwd) {
24
+ const checklists = this.stamps.invokedChecklists(command);
25
+ if (checklists.length === 0)
26
+ return;
27
+ const now = new Date().toISOString();
28
+ for (const checklistId of checklists) {
29
+ this.stamps.write(cwd, new repo_workflow_core_1.ReviewIdentityStamp(checklistId, event.aiType, event.sessionId, event.agentId, event.agentType, cwd, now));
30
+ }
31
+ }
32
+ }
33
+ exports.ReviewIdentityStamper = ReviewIdentityStamper;
34
+ //# sourceMappingURL=review-identity-stamper.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"review-identity-stamper.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/adapters/review-identity-stamper.ts"],"names":[],"mappings":";;;AAAA,sEAAsH;AAItH;;;;;;;;;;;;GAYG;AACH,MAAa,qBAAqB;IACD;IAA7B,YAA6B,SAAqC,yCAAoB;QAAzD,WAAM,GAAN,MAAM,CAAmD;IAAG,CAAC;IAE1F,KAAK,CAAC,KAAqB,EAAE,OAAe,EAAE,GAAW;QACrD,MAAM,UAAU,GAAG,IAAI,CAAC,MAAM,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC;QAC1D,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO;QACpC,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;QACrC,KAAK,MAAM,WAAW,IAAI,UAAU,EAAE,CAAC;YACnC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,IAAI,wCAAmB,CAC1C,WAAW,EAAE,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,SAAS,EAAE,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,SAAS,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC;QAC/F,CAAC;IACL,CAAC;CACJ;AAZD,sDAYC","sourcesContent":["import { ReviewIdentityStamp, ReviewIdentityStampService, reviewIdentityStamps } from '@webpieces/repo-workflow-core';\n\nimport { AgentHookEvent } from '@webpieces/hook-runtime';\n\n/**\n * Tells `pnpm wp-write-review` WHO invoked it (issue #863).\n *\n * The bin runs inside the Bash call, and a Bash child sees only its environment — which in neither harness\n * distinguishes a reviewer subagent from its coordinator (see ReviewIdentityStamp for the detail). This\n * hook, by contrast, is handed the harness's own `agent_id` for the very call that is about to run the bin.\n * So for every checklist a command submits, it writes one stamp the bin consumes a moment later. The bin\n * then REFUSES a stamp that names the coordinating agent — closing the forgery path a Codex coordinator\n * took on two merged PRs — and records the subagent's identity in the verdict's provenance.\n *\n * Called ONLY for a Bash call the guards have already ALLOWED: a denied command never runs the bin, and a\n * stamp it left behind would be an identity waiting to be borrowed.\n */\nexport class ReviewIdentityStamper {\n constructor(private readonly stamps: ReviewIdentityStampService = reviewIdentityStamps) {}\n\n stamp(event: AgentHookEvent, command: string, cwd: string): void {\n const checklists = this.stamps.invokedChecklists(command);\n if (checklists.length === 0) return;\n const now = new Date().toISOString();\n for (const checklistId of checklists) {\n this.stamps.write(cwd, new ReviewIdentityStamp(\n checklistId, event.aiType, event.sessionId, event.agentId, event.agentType, cwd, now));\n }\n }\n}\n"]}
@@ -0,0 +1,105 @@
1
+ /**
2
+ * CODEX HOOK TRUST — read it, report it, NEVER write it.
3
+ *
4
+ * ─── What Codex actually does ─────────────────────────────────────────────────────────────────────
5
+ * Codex trusts a hook entry TOFU. On first sight of a new or changed entry it PROMPTS
6
+ * (`Hooks need review / 1 hook is new or changed`) and, if the human accepts, records a hash in
7
+ * `~/.codex/config.toml`:
8
+ *
9
+ * [hooks.state."<abs path to .codex/hooks.json>:pre_tool_use:<group>:<index>"]
10
+ * trusted_hash = "sha256:…"
11
+ *
12
+ * ─── Why this only ever REPORTS ───────────────────────────────────────────────────────────────────
13
+ * The hash is NOT reproducible from outside Codex. Sixteen encodings were tried against a hooks.json we
14
+ * wrote ourselves and none of them produced the recorded value. So an installer that tried to write one
15
+ * would be guessing at a security decision on a human's behalf, and would either be ignored or — worse —
16
+ * appear to succeed. Forging it is not on the table even if the encoding were known: the prompt IS the
17
+ * mechanism, and the whole point of TOFU is that a person saw the command once.
18
+ *
19
+ * The consequence the installer must therefore SAY OUT LOUD: the prompt's third option is
20
+ * `Continue without trusting (hooks won't run)`. That is one keystroke to a fully unguarded session,
21
+ * with no later warning of any kind. Install-time verification cannot see that choice — it happens
22
+ * afterwards, in another process — so this check reports the trust state it CAN read, names the file it
23
+ * read it from, and stops there.
24
+ *
25
+ * Declining the prompt is a HUMAN's decision about their own machine, and it is deliberately left
26
+ * standing. Tooling that tried to detect and refuse it afterwards would be voiding a setting a person
27
+ * chose on purpose, and it has nothing to catch besides: the guards constrain the AGENT, while the
28
+ * prompt is answered by the HUMAN, who the agent cannot impersonate. So there is no second mechanism
29
+ * downstream of this one — this report is the whole of what webpieces knows about Codex trust.
30
+ */
31
+ /** What one repo's Codex trust looks like right now. Data-only → a class, per CLAUDE.md. */
32
+ export declare class CodexTrustStatus {
33
+ /** `~/.codex/config.toml`, named even when it does not exist so the report can point at it. */
34
+ readonly configPath: string;
35
+ readonly configExists: boolean;
36
+ /** `[projects."<root>"] trust_level = "trusted"`. */
37
+ readonly projectTrusted: boolean;
38
+ /** The repo's `.codex/hooks.json`, absolute — the key every `hooks.state` entry is prefixed by. */
39
+ readonly hooksPath: string;
40
+ /** How many webpieces-managed PreToolUse entries that file registers. 0 ⇒ Codex is not armed. */
41
+ readonly registeredEntries: number;
42
+ /** How many of them `~/.codex/config.toml` records a `trusted_hash` for. */
43
+ readonly trustedEntries: number;
44
+ constructor(
45
+ /** `~/.codex/config.toml`, named even when it does not exist so the report can point at it. */
46
+ configPath: string, configExists: boolean,
47
+ /** `[projects."<root>"] trust_level = "trusted"`. */
48
+ projectTrusted: boolean,
49
+ /** The repo's `.codex/hooks.json`, absolute — the key every `hooks.state` entry is prefixed by. */
50
+ hooksPath: string,
51
+ /** How many webpieces-managed PreToolUse entries that file registers. 0 ⇒ Codex is not armed. */
52
+ registeredEntries: number,
53
+ /** How many of them `~/.codex/config.toml` records a `trusted_hash` for. */
54
+ trustedEntries: number);
55
+ /** True when Codex is armed here AND every entry it would run is trusted. */
56
+ fullyTrusted(): boolean;
57
+ /** True when there is nothing to say — this repo has not armed Codex at all. */
58
+ notArmed(): boolean;
59
+ /**
60
+ * The report, as lines. It states what IS, then the one action that changes it — and the action is
61
+ * always the human's, because nothing here can be repaired by a tool.
62
+ */
63
+ lines(): readonly string[];
64
+ }
65
+ /**
66
+ * Reads Codex's trust state. Never writes, never throws — an unreadable or absent config reports as
67
+ * "not trusted", which is the true and safe answer.
68
+ */
69
+ export declare class CodexTrustProbe {
70
+ /** `~/.codex/config.toml`. `homeDir` is injectable so a unit test never reads the real one. */
71
+ configPath(homeDir?: string): string;
72
+ read(projectRoot: string, homeDir?: string): CodexTrustStatus;
73
+ /**
74
+ * How many webpieces-managed PreToolUse commands `.codex/hooks.json` registers.
75
+ *
76
+ * It counts what WE own, not every hook in the file: a consumer's own unrelated hook is none of this
77
+ * check's business, and counting it would make the report say "1 of 3 trusted" about hooks webpieces
78
+ * neither wrote nor can advise on.
79
+ */
80
+ private registeredEntryCount;
81
+ private readOrEmpty;
82
+ /**
83
+ * `[projects."<root>"]` carrying `trust_level = "trusted"`.
84
+ *
85
+ * A LINE SCAN, not a TOML parser, and deliberately: this package must load on a tree too broken to
86
+ * build a DI container, so it takes no dependency it does not need, and the two shapes it reads are
87
+ * both written by Codex itself in one fixed form. It over-reports "not trusted" for anything it
88
+ * cannot recognise, which is the safe direction — the consequence is one advisory line too many,
89
+ * never a session reported as guarded when it is not.
90
+ */
91
+ private projectTrusted;
92
+ /**
93
+ * How many `hooks.state."<hooksPath>:pre_tool_use:<group>:<index>"` sections carry a `trusted_hash`.
94
+ *
95
+ * The count is compared against the number of entries the file registers rather than matched
96
+ * one-for-one to a specific group/index: the group and index are Codex's own numbering of a file it
97
+ * re-reads on every launch, and an installer that assumed a numbering would report a false alarm the
98
+ * first time Codex renumbered.
99
+ */
100
+ private trustedEntryCount;
101
+ /** The body lines of one TOML section, or [] when the file carries no such header. */
102
+ private sectionBody;
103
+ /** The `<name>` of a `[<name>]` header line, or null for anything else. */
104
+ private headerOf;
105
+ }
@@ -0,0 +1,205 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CodexTrustProbe = exports.CodexTrustStatus = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const fs = tslib_1.__importStar(require("fs"));
6
+ const path = tslib_1.__importStar(require("path"));
7
+ const os_1 = require("os");
8
+ const to_error_1 = require("@webpieces/tooling-common/to-error");
9
+ const hook_registration_1 = require("./hook-registration");
10
+ /**
11
+ * CODEX HOOK TRUST — read it, report it, NEVER write it.
12
+ *
13
+ * ─── What Codex actually does ─────────────────────────────────────────────────────────────────────
14
+ * Codex trusts a hook entry TOFU. On first sight of a new or changed entry it PROMPTS
15
+ * (`Hooks need review / 1 hook is new or changed`) and, if the human accepts, records a hash in
16
+ * `~/.codex/config.toml`:
17
+ *
18
+ * [hooks.state."<abs path to .codex/hooks.json>:pre_tool_use:<group>:<index>"]
19
+ * trusted_hash = "sha256:…"
20
+ *
21
+ * ─── Why this only ever REPORTS ───────────────────────────────────────────────────────────────────
22
+ * The hash is NOT reproducible from outside Codex. Sixteen encodings were tried against a hooks.json we
23
+ * wrote ourselves and none of them produced the recorded value. So an installer that tried to write one
24
+ * would be guessing at a security decision on a human's behalf, and would either be ignored or — worse —
25
+ * appear to succeed. Forging it is not on the table even if the encoding were known: the prompt IS the
26
+ * mechanism, and the whole point of TOFU is that a person saw the command once.
27
+ *
28
+ * The consequence the installer must therefore SAY OUT LOUD: the prompt's third option is
29
+ * `Continue without trusting (hooks won't run)`. That is one keystroke to a fully unguarded session,
30
+ * with no later warning of any kind. Install-time verification cannot see that choice — it happens
31
+ * afterwards, in another process — so this check reports the trust state it CAN read, names the file it
32
+ * read it from, and stops there.
33
+ *
34
+ * Declining the prompt is a HUMAN's decision about their own machine, and it is deliberately left
35
+ * standing. Tooling that tried to detect and refuse it afterwards would be voiding a setting a person
36
+ * chose on purpose, and it has nothing to catch besides: the guards constrain the AGENT, while the
37
+ * prompt is answered by the HUMAN, who the agent cannot impersonate. So there is no second mechanism
38
+ * downstream of this one — this report is the whole of what webpieces knows about Codex trust.
39
+ */
40
+ /** What one repo's Codex trust looks like right now. Data-only → a class, per CLAUDE.md. */
41
+ class CodexTrustStatus {
42
+ configPath;
43
+ configExists;
44
+ projectTrusted;
45
+ hooksPath;
46
+ registeredEntries;
47
+ trustedEntries;
48
+ // eslint-disable-next-line @typescript-eslint/max-params
49
+ constructor(
50
+ /** `~/.codex/config.toml`, named even when it does not exist so the report can point at it. */
51
+ configPath, configExists,
52
+ /** `[projects."<root>"] trust_level = "trusted"`. */
53
+ projectTrusted,
54
+ /** The repo's `.codex/hooks.json`, absolute — the key every `hooks.state` entry is prefixed by. */
55
+ hooksPath,
56
+ /** How many webpieces-managed PreToolUse entries that file registers. 0 ⇒ Codex is not armed. */
57
+ registeredEntries,
58
+ /** How many of them `~/.codex/config.toml` records a `trusted_hash` for. */
59
+ trustedEntries) {
60
+ this.configPath = configPath;
61
+ this.configExists = configExists;
62
+ this.projectTrusted = projectTrusted;
63
+ this.hooksPath = hooksPath;
64
+ this.registeredEntries = registeredEntries;
65
+ this.trustedEntries = trustedEntries;
66
+ }
67
+ /** True when Codex is armed here AND every entry it would run is trusted. */
68
+ fullyTrusted() {
69
+ return this.registeredEntries > 0 && this.trustedEntries >= this.registeredEntries && this.projectTrusted;
70
+ }
71
+ /** True when there is nothing to say — this repo has not armed Codex at all. */
72
+ notArmed() {
73
+ return this.registeredEntries === 0;
74
+ }
75
+ /**
76
+ * The report, as lines. It states what IS, then the one action that changes it — and the action is
77
+ * always the human's, because nothing here can be repaired by a tool.
78
+ */
79
+ lines() {
80
+ if (this.notArmed())
81
+ return [];
82
+ if (this.fullyTrusted()) {
83
+ return [` ✅ Codex trusts all ${String(this.registeredEntries)} webpieces hook(s) in ${this.hooksPath}`];
84
+ }
85
+ const out = [];
86
+ out.push(` ⚠️ Codex has NOT yet trusted the webpieces hooks in ${this.hooksPath}`);
87
+ if (!this.configExists) {
88
+ out.push(` ${this.configPath} does not exist yet — Codex has never run for this user.`);
89
+ }
90
+ else if (!this.projectTrusted) {
91
+ out.push(' this project is not marked trusted in ~/.codex/config.toml.');
92
+ }
93
+ if (this.trustedEntries < this.registeredEntries) {
94
+ out.push(` ${String(this.trustedEntries)} of ${String(this.registeredEntries)} hook entries carry a trusted_hash.`);
95
+ }
96
+ out.push(' Fix: run `codex` in this repo and choose "Trust all" when it asks about hooks.');
97
+ out.push(' Its third option ("Continue without trusting") leaves the session UNGUARDED for its');
98
+ out.push(' whole life, and nothing later in the run reports that — this message is the only notice.');
99
+ return out;
100
+ }
101
+ }
102
+ exports.CodexTrustStatus = CodexTrustStatus;
103
+ /**
104
+ * Reads Codex's trust state. Never writes, never throws — an unreadable or absent config reports as
105
+ * "not trusted", which is the true and safe answer.
106
+ */
107
+ class CodexTrustProbe {
108
+ /** `~/.codex/config.toml`. `homeDir` is injectable so a unit test never reads the real one. */
109
+ configPath(homeDir = (0, os_1.homedir)()) {
110
+ return path.join(homeDir, '.codex', 'config.toml');
111
+ }
112
+ read(projectRoot, homeDir = (0, os_1.homedir)()) {
113
+ const configPath = this.configPath(homeDir);
114
+ const hooksPath = path.join(projectRoot, ...hook_registration_1.CODEX_REGISTRATION.settingsFiles[0].split('/'));
115
+ const registered = this.registeredEntryCount(hooksPath);
116
+ const raw = this.readOrEmpty(configPath);
117
+ return new CodexTrustStatus(configPath, raw !== null, this.projectTrusted(raw ?? '', projectRoot), hooksPath, registered, this.trustedEntryCount(raw ?? '', hooksPath));
118
+ }
119
+ /**
120
+ * How many webpieces-managed PreToolUse commands `.codex/hooks.json` registers.
121
+ *
122
+ * It counts what WE own, not every hook in the file: a consumer's own unrelated hook is none of this
123
+ * check's business, and counting it would make the report say "1 of 3 trusted" about hooks webpieces
124
+ * neither wrote nor can advise on.
125
+ */
126
+ registeredEntryCount(hooksPath) {
127
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
128
+ try {
129
+ if (!fs.existsSync(hooksPath))
130
+ return 0;
131
+ const entries = (0, hook_registration_1.readSettings)(hooksPath).hooks?.PreToolUse ?? [];
132
+ return entries.reduce((total, entry) => total + entry.hooks.filter((h) => (0, hook_registration_1.isManagedCommand)(h.command)).length, 0);
133
+ }
134
+ catch (err) {
135
+ const error = (0, to_error_1.toError)(err);
136
+ void error; // an unreadable/invalid hooks.json is "not armed"; the drift check is what reports that
137
+ return 0;
138
+ }
139
+ }
140
+ readOrEmpty(configPath) {
141
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
142
+ try {
143
+ return fs.existsSync(configPath) ? fs.readFileSync(configPath, 'utf8') : null;
144
+ }
145
+ catch (err) {
146
+ const error = (0, to_error_1.toError)(err);
147
+ void error; // unreadable → treated as absent, which reports as "not trusted"
148
+ return null;
149
+ }
150
+ }
151
+ /**
152
+ * `[projects."<root>"]` carrying `trust_level = "trusted"`.
153
+ *
154
+ * A LINE SCAN, not a TOML parser, and deliberately: this package must load on a tree too broken to
155
+ * build a DI container, so it takes no dependency it does not need, and the two shapes it reads are
156
+ * both written by Codex itself in one fixed form. It over-reports "not trusted" for anything it
157
+ * cannot recognise, which is the safe direction — the consequence is one advisory line too many,
158
+ * never a session reported as guarded when it is not.
159
+ */
160
+ projectTrusted(raw, projectRoot) {
161
+ return this.sectionBody(raw, `projects."${projectRoot}"`)
162
+ .some((line) => /^\s*trust_level\s*=\s*"trusted"\s*$/.test(line));
163
+ }
164
+ /**
165
+ * How many `hooks.state."<hooksPath>:pre_tool_use:<group>:<index>"` sections carry a `trusted_hash`.
166
+ *
167
+ * The count is compared against the number of entries the file registers rather than matched
168
+ * one-for-one to a specific group/index: the group and index are Codex's own numbering of a file it
169
+ * re-reads on every launch, and an installer that assumed a numbering would report a false alarm the
170
+ * first time Codex renumbered.
171
+ */
172
+ trustedEntryCount(raw, hooksPath) {
173
+ const prefix = `hooks.state."${hooksPath}:pre_tool_use:`;
174
+ let trusted = 0;
175
+ let inEntry = false;
176
+ for (const line of raw.split('\n')) {
177
+ const header = this.headerOf(line);
178
+ if (header !== null)
179
+ inEntry = header.startsWith(prefix);
180
+ else if (inEntry && /^\s*trusted_hash\s*=\s*"/.test(line))
181
+ trusted += 1;
182
+ }
183
+ return trusted;
184
+ }
185
+ /** The body lines of one TOML section, or [] when the file carries no such header. */
186
+ sectionBody(raw, wanted) {
187
+ const body = [];
188
+ let inside = false;
189
+ for (const line of raw.split('\n')) {
190
+ const header = this.headerOf(line);
191
+ if (header !== null)
192
+ inside = header === wanted;
193
+ else if (inside)
194
+ body.push(line);
195
+ }
196
+ return body;
197
+ }
198
+ /** The `<name>` of a `[<name>]` header line, or null for anything else. */
199
+ headerOf(line) {
200
+ const match = /^\s*\[([^\]]+)\]\s*$/.exec(line);
201
+ return match === null ? null : match[1];
202
+ }
203
+ }
204
+ exports.CodexTrustProbe = CodexTrustProbe;
205
+ //# sourceMappingURL=codex-trust.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codex-trust.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/bin/codex-trust.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,2BAA6B;AAE7B,iEAA6D;AAC7D,2DAAyF;AAGzF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,4FAA4F;AAC5F,MAAa,gBAAgB;IAIZ;IACA;IAEA;IAEA;IAEA;I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BAAsB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAChD,OAAO,KAAK,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAC5C,CAAC;CACJ;AAvGD,0CAuGC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { homedir } from 'os';\n\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { CODEX_REGISTRATION, isManagedCommand, readSettings } from './hook-registration';\nimport type { HookCommand, HookEntry } from './settings-shape';\n\n/**\n * CODEX HOOK TRUST — read it, report it, NEVER write it.\n *\n * ─── What Codex actually does ─────────────────────────────────────────────────────────────────────\n * Codex trusts a hook entry TOFU. On first sight of a new or changed entry it PROMPTS\n * (`Hooks need review / 1 hook is new or changed`) and, if the human accepts, records a hash in\n * `~/.codex/config.toml`:\n *\n * [hooks.state.\"<abs path to .codex/hooks.json>:pre_tool_use:<group>:<index>\"]\n * trusted_hash = \"sha256:…\"\n *\n * ─── Why this only ever REPORTS ───────────────────────────────────────────────────────────────────\n * The hash is NOT reproducible from outside Codex. Sixteen encodings were tried against a hooks.json we\n * wrote ourselves and none of them produced the recorded value. So an installer that tried to write one\n * would be guessing at a security decision on a human's behalf, and would either be ignored or — worse —\n * appear to succeed. Forging it is not on the table even if the encoding were known: the prompt IS the\n * mechanism, and the whole point of TOFU is that a person saw the command once.\n *\n * The consequence the installer must therefore SAY OUT LOUD: the prompt's third option is\n * `Continue without trusting (hooks won't run)`. That is one keystroke to a fully unguarded session,\n * with no later warning of any kind. Install-time verification cannot see that choice — it happens\n * afterwards, in another process — so this check reports the trust state it CAN read, names the file it\n * read it from, and stops there.\n *\n * Declining the prompt is a HUMAN's decision about their own machine, and it is deliberately left\n * standing. Tooling that tried to detect and refuse it afterwards would be voiding a setting a person\n * chose on purpose, and it has nothing to catch besides: the guards constrain the AGENT, while the\n * prompt is answered by the HUMAN, who the agent cannot impersonate. So there is no second mechanism\n * downstream of this one — this report is the whole of what webpieces knows about Codex trust.\n */\n\n/** What one repo's Codex trust looks like right now. Data-only → a class, per CLAUDE.md. */\nexport class CodexTrustStatus {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n /** `~/.codex/config.toml`, named even when it does not exist so the report can point at it. */\n readonly configPath: string,\n readonly configExists: boolean,\n /** `[projects.\"<root>\"] trust_level = \"trusted\"`. */\n readonly projectTrusted: boolean,\n /** The repo's `.codex/hooks.json`, absolute — the key every `hooks.state` entry is prefixed by. */\n readonly hooksPath: string,\n /** How many webpieces-managed PreToolUse entries that file registers. 0 ⇒ Codex is not armed. */\n readonly registeredEntries: number,\n /** How many of them `~/.codex/config.toml` records a `trusted_hash` for. */\n readonly trustedEntries: number,\n ) {}\n\n /** True when Codex is armed here AND every entry it would run is trusted. */\n fullyTrusted(): boolean {\n return this.registeredEntries > 0 && this.trustedEntries >= this.registeredEntries && this.projectTrusted;\n }\n\n /** True when there is nothing to say — this repo has not armed Codex at all. */\n notArmed(): boolean {\n return this.registeredEntries === 0;\n }\n\n /**\n * The report, as lines. It states what IS, then the one action that changes it — and the action is\n * always the human's, because nothing here can be repaired by a tool.\n */\n lines(): readonly string[] {\n if (this.notArmed()) return [];\n if (this.fullyTrusted()) {\n return [` ✅ Codex trusts all ${String(this.registeredEntries)} webpieces hook(s) in ${this.hooksPath}`];\n }\n const out: string[] = [];\n out.push(` ⚠️ Codex has NOT yet trusted the webpieces hooks in ${this.hooksPath}`);\n if (!this.configExists) {\n out.push(` ${this.configPath} does not exist yet — Codex has never run for this user.`);\n } else if (!this.projectTrusted) {\n out.push(' this project is not marked trusted in ~/.codex/config.toml.');\n }\n if (this.trustedEntries < this.registeredEntries) {\n out.push(` ${String(this.trustedEntries)} of ${String(this.registeredEntries)} hook entries carry a trusted_hash.`);\n }\n out.push(' Fix: run `codex` in this repo and choose \"Trust all\" when it asks about hooks.');\n out.push(' Its third option (\"Continue without trusting\") leaves the session UNGUARDED for its');\n out.push(' whole life, and nothing later in the run reports that — this message is the only notice.');\n return out;\n }\n}\n\n/**\n * Reads Codex's trust state. Never writes, never throws — an unreadable or absent config reports as\n * \"not trusted\", which is the true and safe answer.\n */\nexport class CodexTrustProbe {\n /** `~/.codex/config.toml`. `homeDir` is injectable so a unit test never reads the real one. */\n configPath(homeDir: string = homedir()): string {\n return path.join(homeDir, '.codex', 'config.toml');\n }\n\n read(projectRoot: string, homeDir: string = homedir()): CodexTrustStatus {\n const configPath = this.configPath(homeDir);\n const hooksPath = path.join(projectRoot, ...CODEX_REGISTRATION.settingsFiles[0].split('/'));\n const registered = this.registeredEntryCount(hooksPath);\n const raw = this.readOrEmpty(configPath);\n return new CodexTrustStatus(\n configPath, raw !== null, this.projectTrusted(raw ?? '', projectRoot),\n hooksPath, registered, this.trustedEntryCount(raw ?? '', hooksPath),\n );\n }\n\n /**\n * How many webpieces-managed PreToolUse commands `.codex/hooks.json` registers.\n *\n * It counts what WE own, not every hook in the file: a consumer's own unrelated hook is none of this\n * check's business, and counting it would make the report say \"1 of 3 trusted\" about hooks webpieces\n * neither wrote nor can advise on.\n */\n private registeredEntryCount(hooksPath: string): number {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n if (!fs.existsSync(hooksPath)) return 0;\n const entries: readonly HookEntry[] = readSettings(hooksPath).hooks?.PreToolUse ?? [];\n return entries.reduce(\n (total: number, entry: HookEntry): number =>\n total + entry.hooks.filter((h: HookCommand): boolean => isManagedCommand(h.command)).length,\n 0,\n );\n } catch (err: unknown) {\n const error = toError(err);\n void error; // an unreadable/invalid hooks.json is \"not armed\"; the drift check is what reports that\n return 0;\n }\n }\n\n private readOrEmpty(configPath: string): string | null {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return fs.existsSync(configPath) ? fs.readFileSync(configPath, 'utf8') : null;\n } catch (err: unknown) {\n const error = toError(err);\n void error; // unreadable → treated as absent, which reports as \"not trusted\"\n return null;\n }\n }\n\n /**\n * `[projects.\"<root>\"]` carrying `trust_level = \"trusted\"`.\n *\n * A LINE SCAN, not a TOML parser, and deliberately: this package must load on a tree too broken to\n * build a DI container, so it takes no dependency it does not need, and the two shapes it reads are\n * both written by Codex itself in one fixed form. It over-reports \"not trusted\" for anything it\n * cannot recognise, which is the safe direction — the consequence is one advisory line too many,\n * never a session reported as guarded when it is not.\n */\n private projectTrusted(raw: string, projectRoot: string): boolean {\n return this.sectionBody(raw, `projects.\"${projectRoot}\"`)\n .some((line: string): boolean => /^\\s*trust_level\\s*=\\s*\"trusted\"\\s*$/.test(line));\n }\n\n /**\n * How many `hooks.state.\"<hooksPath>:pre_tool_use:<group>:<index>\"` sections carry a `trusted_hash`.\n *\n * The count is compared against the number of entries the file registers rather than matched\n * one-for-one to a specific group/index: the group and index are Codex's own numbering of a file it\n * re-reads on every launch, and an installer that assumed a numbering would report a false alarm the\n * first time Codex renumbered.\n */\n private trustedEntryCount(raw: string, hooksPath: string): number {\n const prefix = `hooks.state.\"${hooksPath}:pre_tool_use:`;\n let trusted = 0;\n let inEntry = false;\n for (const line of raw.split('\\n')) {\n const header = this.headerOf(line);\n if (header !== null) inEntry = header.startsWith(prefix);\n else if (inEntry && /^\\s*trusted_hash\\s*=\\s*\"/.test(line)) trusted += 1;\n }\n return trusted;\n }\n\n /** The body lines of one TOML section, or [] when the file carries no such header. */\n private sectionBody(raw: string, wanted: string): readonly string[] {\n const body: string[] = [];\n let inside = false;\n for (const line of raw.split('\\n')) {\n const header = this.headerOf(line);\n if (header !== null) inside = header === wanted;\n else if (inside) body.push(line);\n }\n return body;\n }\n\n /** The `<name>` of a `[<name>]` header line, or null for anything else. */\n private headerOf(line: string): string | null {\n const match = /^\\s*\\[([^\\]]+)\\]\\s*$/.exec(line);\n return match === null ? null : match[1];\n }\n}\n"]}
@@ -0,0 +1 @@
1
+ export declare function runDevHookInstall(): Promise<void>;
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runDevHookInstall = runDevHookInstall;
4
+ const fs_1 = require("fs");
5
+ const os_1 = require("os");
6
+ const path_1 = require("path");
7
+ const rules_config_1 = require("@webpieces/rules-config");
8
+ // webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container
9
+ function wireLocalRulesConfig(cwd, distRulesConfigPath) {
10
+ // Place the symlink in dist/packages/tooling/node_modules/ — one level above
11
+ // the agent-workflow-rules package output but still below the workspace root node_modules.
12
+ // Node's require() resolution walks up from the requiring file and finds this
13
+ // node_modules entry before reaching the workspace root's stale published package.
14
+ // This directory is NOT wiped by any individual package build (each build only
15
+ // cleans its own output subfolder), so it survives a full workspace build too.
16
+ const overrideDir = (0, path_1.join)(cwd, 'dist', 'packages', 'tooling', 'node_modules', '@webpieces');
17
+ const overrideLink = (0, path_1.join)(overrideDir, 'rules-config');
18
+ (0, fs_1.mkdirSync)(overrideDir, { recursive: true });
19
+ if ((0, fs_1.existsSync)(overrideLink)) {
20
+ (0, fs_1.rmSync)(overrideLink, { recursive: true });
21
+ }
22
+ (0, fs_1.symlinkSync)(distRulesConfigPath, overrideLink);
23
+ }
24
+ // NOTE: this is a dev-only tool, no longer a `wp-*` bin. Run it directly with node against the local
25
+ // build: `node dist/packages/tooling/agent-workflow-rules/src/bin/dev-hook-install.js`.
26
+ // webpieces-disable no-function-outside-class -- existing CLI/shim bootstrap function moved intact; it must remain callable without constructing a DI container
27
+ async function runDevHookInstall() {
28
+ const cwd = process.cwd();
29
+ // Mirror production .claude/settings.json: two independent PreToolUse hooks, one per category.
30
+ const rulesHookPath = (0, path_1.join)(cwd, 'dist', 'packages', 'tooling', 'ai-hook-rules', 'src', 'adapters', 'rules-hook.js');
31
+ const guardsHookPath = (0, path_1.join)(cwd, 'dist', 'packages', 'tooling', 'agent-workflow-rules', 'src', 'adapters', 'guards-hook.js');
32
+ if (!(0, fs_1.existsSync)(rulesHookPath)) {
33
+ throw new rules_config_1.CliExitError(1, `[dev-hook-install] Local build not found at: ${rulesHookPath}\n Run \`pnpm nx run ai-hook-rules:build\` first.`);
34
+ }
35
+ if (!(0, fs_1.existsSync)(guardsHookPath)) {
36
+ throw new rules_config_1.CliExitError(1, `[dev-hook-install] Local build not found at: ${guardsHookPath}\n Run \`pnpm nx run agent-workflow-rules:build\` first.`);
37
+ }
38
+ const distRulesConfigPath = (0, path_1.join)(cwd, 'dist', 'packages', 'tooling', 'rules-config');
39
+ if (!(0, fs_1.existsSync)(distRulesConfigPath)) {
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
+ }
42
+ const homeDir = (0, os_1.homedir)();
43
+ const webpiecesDir = (0, path_1.join)(homeDir, '.webpieces');
44
+ const backupPath = (0, path_1.join)(webpiecesDir, 'dev-hook-backup.json');
45
+ const claudeSettingsPath = (0, path_1.join)(homeDir, '.claude', 'settings.json');
46
+ if ((0, fs_1.existsSync)(backupPath)) {
47
+ throw new rules_config_1.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.');
48
+ }
49
+ wireLocalRulesConfig(cwd, distRulesConfigPath);
50
+ let settings = {};
51
+ if ((0, fs_1.existsSync)(claudeSettingsPath)) {
52
+ settings = JSON.parse((0, fs_1.readFileSync)(claudeSettingsPath, 'utf8'));
53
+ }
54
+ // Save whatever hooks exist now (may be undefined/null) so uninstall can restore them
55
+ const backup = { previousHooks: settings.hooks ?? null };
56
+ if (!(0, fs_1.existsSync)(webpiecesDir)) {
57
+ (0, fs_1.mkdirSync)(webpiecesDir, { recursive: true });
58
+ }
59
+ (0, fs_1.writeFileSync)(backupPath, JSON.stringify(backup, null, 4) + '\n');
60
+ // Mirror production wiring: rules hook on file tools, guards hook on file + Bash tools.
61
+ settings.hooks = {
62
+ PreToolUse: [
63
+ {
64
+ matcher: 'Write|Edit|MultiEdit',
65
+ hooks: [{ type: 'command', command: `node ${rulesHookPath}` }],
66
+ },
67
+ {
68
+ matcher: 'Write|Edit|MultiEdit|Bash|Read',
69
+ hooks: [{ type: 'command', command: `node ${guardsHookPath}` }],
70
+ },
71
+ ],
72
+ };
73
+ (0, fs_1.mkdirSync)((0, path_1.dirname)(claudeSettingsPath), { recursive: true });
74
+ (0, fs_1.writeFileSync)(claudeSettingsPath, JSON.stringify(settings, null, 4) + '\n');
75
+ console.log(` Dev hooks installed → node ${rulesHookPath} (rules), node ${guardsHookPath} (guards)`);
76
+ console.log(' Run `node dist/packages/tooling/agent-workflow-rules/src/bin/dev-hook-uninstall.js` when done testing.');
77
+ }
78
+ if (require.main === module)
79
+ (0, rules_config_1.runMain)(runDevHookInstall);
80
+ //# sourceMappingURL=dev-hook-install.js.map