@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,409 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.invocationLog = exports.InvocationLog = exports.GuardInvocation = exports.GuardDecision = exports.MATRIX_L2_UNROWED = exports.MATRIX_L0_BLOCK = exports.MATRIX_L0_ALLOW = exports.MatrixRef = void 0;
4
+ exports.matrixL2Row = matrixL2Row;
5
+ exports.logGuardDecision = logGuardDecision;
6
+ exports.logL1Decision = logL1Decision;
7
+ exports.branchForLog = branchForLog;
8
+ const tslib_1 = require("tslib");
9
+ const child_process_1 = require("child_process");
10
+ const fs = tslib_1.__importStar(require("fs"));
11
+ const path = tslib_1.__importStar(require("path"));
12
+ const tooling_common_1 = require("@webpieces/tooling-common");
13
+ const repo_workflow_core_1 = require("@webpieces/repo-workflow-core");
14
+ const rules_config_1 = require("@webpieces/rules-config");
15
+ const log_streams_1 = require("./log-streams");
16
+ const rules_config_2 = require("@webpieces/rules-config");
17
+ const to_error_1 = require("@webpieces/tooling-common/to-error");
18
+ const log_stream_1 = require("./log-stream");
19
+ const log_target_1 = require("./log-target");
20
+ const ai_type_context_1 = require("./ai-type-context");
21
+ const l2_rows_1 = require("./l2-rows");
22
+ const matrix_cures_1 = require("./matrix-cures");
23
+ // The SYNC decision log — what the synchronous hook DID on each invocation and WHY. Its companion is
24
+ // the ASYNC log (the `async-refresh/` stream, written by the detached refresher in main-sync-log.ts). This
25
+ // one records EVERY guard decision — allow, block, config-bypass, and the fail-open cases — and CITES
26
+ // the async-written cache snapshot (`cache` field) that drove the decision, so a wrong allow/block is
27
+ // traceable to a stale or missing async write. Writes to `.webpieces/logs/L2-decisions/<writer>.log` —
28
+ // the LAYER is the directory, the WRITER is the file (see log-streams.ts and LogStream).
29
+ const MAX_LOG_BYTES = 512 * 1024; // 512 KB — rotate when exceeded (mirrors rotation in rejection-log)
30
+ /**
31
+ * WHICH ROW of WHICH layer's decision table produced this line. Data-only → a class, per CLAUDE.md.
32
+ *
33
+ * `row` is the row NUMBER from the layer's row array (`L1_ROWS[i].num`, `L2_ROWS[i].num`) — the
34
+ * same number the generated doc prints, because the doc is rendered from that same array. So a log
35
+ * line joins to its matrix row BY NUMBER, and checking observed behaviour against the documented use
36
+ * cases becomes a lookup rather than an investigation.
37
+ */
38
+ class MatrixRef {
39
+ layer;
40
+ row;
41
+ constructor(layer, row) {
42
+ this.layer = layer;
43
+ this.row = row;
44
+ }
45
+ }
46
+ exports.MatrixRef = MatrixRef;
47
+ /**
48
+ * The layer tokens. EVERY layer now cites a row: L0 through its two decision-matrix rows, L1 through
49
+ * L1_ROWS, and L2 through L2_ROWS (see `matrixL2Row`). This used to say `'-'` was for "a layer with no
50
+ * row array YET (L2 is the un-converted one)" — L2 is converted, and a comment describing a state the
51
+ * code left behind is exactly the kind of doc a reader trusts and should not.
52
+ *
53
+ * `'-'` survives for ONE case, and it is a real one: an L2 reason that no row claims. See matrixL2Row.
54
+ *
55
+ * These are REQUIRED at the constructor, not defaulted: a defaulted `MatrixRef` would make the
56
+ * uncited case reachable by doing nothing and impossible to grep — the same defect this file's own
57
+ * docblock argues against for `'BLOCK'`, where silence was the one wrong answer available.
58
+ *
59
+ * L0 NOW CITES ITS ROW TOO. It used to be `'-'` on the grounds that "L0's faults are a table of letters
60
+ * rather than numbered rows" — but L0 has BOTH: the letter says WHICH fault, and the numbered decision
61
+ * matrix (`renderGuardMatrixDoc`) says which of its three rows was taken. There is one ALLOW row and one
62
+ * BLOCK row, so the pair `row=` + `fault=` pins the decision exactly, and the deny an agent reads now
63
+ * carries the identical pair. That is the join: one grep spans the deny, the log line and the doc.
64
+ * Two constants, not one `MATRIX_L0`, because the two call sites are a cure-bypass ALLOW and an L0
65
+ * BLOCK — one token covering both is what made the row unciteable in the first place.
66
+ */
67
+ exports.MATRIX_L0_ALLOW = new MatrixRef('L0', rules_config_2.L0_ROW_ALLOWLISTED);
68
+ exports.MATRIX_L0_BLOCK = new MatrixRef('L0', rules_config_2.L0_ROW_BLOCKED);
69
+ /**
70
+ * The L2 reference for one decision, with the row DERIVED FROM THE REASON.
71
+ *
72
+ * There is no `MATRIX_L2` constant any more, and its absence is the point: a single shared instance
73
+ * meant every L2 line in the repo carried `row=-`, which reads as "L2 has no rows" rather than "this
74
+ * decision was not classified". Deleting it makes every construction site name a reason, and the reason
75
+ * is the only thing a call site has that identifies which row it is an instance of.
76
+ *
77
+ * `l2RowForReason` returns null for a reason no row claims, and that renders as `'-'` — visible in the
78
+ * log, not silently absorbed into a default row. l2-matrix.spec.ts reads the four guard sources and
79
+ * fails the build if any reason literal in them is unmapped, so `-` should never appear in practice;
80
+ * when it does, it is a genuine hole in the table and the log says so.
81
+ */
82
+ // webpieces-disable no-function-outside-class -- a named constructor for MatrixRef beside it, in this module of module-scope writers
83
+ function matrixL2Row(reason) {
84
+ const row = (0, l2_rows_1.l2RowForReason)(reason);
85
+ return new MatrixRef('L2', row === null ? '-' : String(row));
86
+ }
87
+ /**
88
+ * The L2 stream, with NO row — for the two kinds of line that genuinely are not an instance of a row.
89
+ *
90
+ * 1. The runner's AGGREGATE bash lines ("no bash-guard block" / "bash-guard block"). They summarise
91
+ * the whole guard set's answer for one command, not one row's verdict; the per-guard lines that
92
+ * DO cite rows are written alongside them by the guards themselves.
93
+ * 2. `whole-repo-build-guard`, which is not a branch-state policy at all — it is the experimental
94
+ * home-config guard, has no webpieces.config.json entry, and shares this stream only because the
95
+ * stream is "bash decisions", not "L2 rows".
96
+ *
97
+ * A NAMED constant rather than an inline `new MatrixRef('L2', '-')`, so `grep MATRIX_L2_UNROWED` lists
98
+ * every uncited line and the list stays short and arguable. It is deliberately NOT called `MATRIX_L2`:
99
+ * the old name was used by everything and made "L2 has no rows" indistinguishable from "this line is
100
+ * not a row".
101
+ */
102
+ exports.MATRIX_L2_UNROWED = new MatrixRef('L2', '-');
103
+ // Data-only record of one guard decision (per CLAUDE.md: classes for data, not object literals).
104
+ // `cache` summarizes the async-written main-sync-status.json that drove a feature-branch-guard
105
+ // decision (branch/merged/conflict/fork + the cache timestamp), or '-' when no cache was consulted
106
+ // (bash guards, on-main, config-bypass).
107
+ class GuardDecision {
108
+ rule;
109
+ tool;
110
+ target; // file path (file guards) or the bash command (bash guards)
111
+ branch;
112
+ verdict;
113
+ reason;
114
+ cache;
115
+ /**
116
+ * The L0 fault this decision IS, in the codebook's letter (core/l0-fault-codes.ts), or `-` for an
117
+ * ordinary rule decision. The `sh` shim has always stamped `fault=` on its own stream; the three
118
+ * JS-side faults (S/C/Y) reached this one with no label at all, so `grep fault=S` found nothing
119
+ * even while an S storm was blocking every call.
120
+ */
121
+ fault;
122
+ /** Which layer + row decided this. See MatrixRef — it is what joins a log line to the doc. */
123
+ matrix;
124
+ // eslint-disable-next-line @typescript-eslint/max-params
125
+ constructor(rule, tool, target, branch, verdict, reason, cache = '-', fault, matrix) {
126
+ this.rule = rule;
127
+ this.tool = tool;
128
+ this.target = target;
129
+ this.branch = branch;
130
+ this.verdict = verdict;
131
+ this.reason = reason;
132
+ this.cache = cache;
133
+ this.fault = fault;
134
+ this.matrix = matrix;
135
+ }
136
+ }
137
+ exports.GuardDecision = GuardDecision;
138
+ /**
139
+ * Append one tab-separated line per L2 decision to `.webpieces/logs/L2-decisions/<writer>.log`, where
140
+ * <writer> is LogStream's `<sessionId>-<agentId|coordinator>-<hook>` key (a caller that never
141
+ * identified renders as `unknown-coordinator-hook` — there is no un-keyed name).
142
+ * `root` is
143
+ * the repo/workspace root that holds `.webpieces` (callers pass workspaceRoot, or a
144
+ * RepoRootFinder-resolved root at the pre-load config-bypass site — never a raw cwd, so a bypass
145
+ * logged from a subdir never scatters a stray `.webpieces`). Swallows all errors — logging must never
146
+ * block or fail a hook.
147
+ */
148
+ // webpieces-disable no-function-outside-class -- the module-scope writer this log has always been, beside branchForLog/oneLine/rotateLogFile; it must stay callable from a tree too broken to build a DI container
149
+ function logGuardDecision(root, decision) {
150
+ appendDecision(root, log_streams_1.L2_DECISIONS_STREAM, decision);
151
+ }
152
+ /**
153
+ * The L1 stream — `.webpieces/logs/L1-location/<writer>.log`.
154
+ *
155
+ * L1 had NO stream. Its three blocking paths wrote into L2's file under an implementation name
156
+ * (`force-to-root`, `trinary-version-skew`, `cd-must-be-first`), and its NON-blocking outcomes —
157
+ * the exempt row and the three hand-down rows — wrote nothing at all. So "L1 had no objection" was
158
+ * unobservable, and "show me every L1 decision" had no answer: L1 existed in the trail only as the
159
+ * `root=` / `projectDir=` / `tree=` columns stapled onto somebody else's line.
160
+ *
161
+ * A SIBLING rather than a `base` parameter on logGuardDecision, deliberately: that signature is what
162
+ * the process-wide `logStream` singleton exists to keep unchanged (see LogStream's docblock), and
163
+ * `INVOCATION_LOG_FILE` already establishes the pattern of a second stream owning its own name in
164
+ * this same module.
165
+ */
166
+ // webpieces-disable no-function-outside-class -- sibling of logGuardDecision, same module-scope writer shape and same reason
167
+ function logL1Decision(root, decision) {
168
+ appendDecision(root, log_streams_1.L1_LOCATION_STREAM, decision);
169
+ }
170
+ // The one appender both streams share. `streamDir` is the LAYER; the writer key inside it is
171
+ // logStream's session/agent/hook, which is what keeps one writer per file.
172
+ // webpieces-disable no-function-outside-class -- the shared body of the two module-scope writers above
173
+ function appendDecision(root, streamDir, decision) {
174
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
175
+ try {
176
+ const timestamp = new Date().toISOString();
177
+ // LOCAL scope: a guard decision belongs to the tree it judged. WHO made the call is answered
178
+ // by the filename, which logStream names with session/agent/hook.
179
+ const logsDir = tooling_common_1.dotWebpieces.logsFile(root, streamDir);
180
+ fs.mkdirSync(logsDir, { recursive: true });
181
+ const logPath = path.join(logsDir, log_stream_1.logStream.writerFile('.log'));
182
+ rotateLogFile(logPath, path.join(logsDir, log_stream_1.logStream.writerFile('.1.log')));
183
+ const line = [
184
+ `[${timestamp}]`,
185
+ decision.verdict,
186
+ decision.tool,
187
+ oneLine(decision.target),
188
+ decision.branch,
189
+ decision.rule,
190
+ oneLine(decision.reason),
191
+ oneLine(decision.cache),
192
+ // WHICH ROW of WHICH table decided this. The directory already carries the layer, but a
193
+ // line quoted out of its file must still say what judged it — and `row=` is the join key
194
+ // to the generated doc, which is the point of the whole exercise.
195
+ `layer=${decision.matrix.layer}`,
196
+ `row=${decision.matrix.row}`,
197
+ // The tree this decision was actually made against, and what Claude Code told the hook the
198
+ // project was. Appended (never reordered) for the same reason as on the invocation line —
199
+ // see ClaudeEnv: when these two disagree, that disagreement is the bug.
200
+ `root=${root}`,
201
+ `projectDir=${rules_config_1.claudeEnv.projectDirForLog()}`,
202
+ // git's name for that tree — `primary`, else the worktree name. Same literal and same
203
+ // derivation as the L0 shim log's `tree=` (shim-audit-log.ts), so one grep spans both
204
+ // streams: L0 carries tree without projectDir, L1 now carries both.
205
+ `tree=${tooling_common_1.dotWebpieces.worktreeName(root) || 'primary'}`,
206
+ // APPEND-ONLY, same spelling as the invocation line and the L0 shim log: which L0 fault
207
+ // this was, or `-`.
208
+ `fault=${decision.fault}`,
209
+ // WHAT THE AGENT WAS TOLD TO DO — looked up from the row above, never passed in, so it is
210
+ // by construction the same literal the generated matrix prints for that row (see
211
+ // matrix-cures.ts). `row=` says which row judged the call; this says what that row
212
+ // prescribed, which is what makes the trail auditable against the doc without opening it.
213
+ // APPEND-ONLY, like every field before it.
214
+ `cure=${oneLine((0, matrix_cures_1.cureForMatrix)(decision.matrix.layer, decision.matrix.row))}`,
215
+ // WHICH HARNESS made the call, spelled exactly as the L0 sh shim spells it on its own
216
+ // stream — so ONE grep (`ai=codex`) spans all five streams and "is Codex actually being
217
+ // guarded?" is a question the trail can answer. APPEND-ONLY, like every field before it; a
218
+ // row from a release that predates this carries no `ai=` and reads as `unknown`.
219
+ `ai=${ai_type_context_1.aiTypeContext.forLog()}`,
220
+ ].join('\t') + '\n';
221
+ fs.appendFileSync(logPath, line);
222
+ }
223
+ catch (err) {
224
+ const error = (0, to_error_1.toError)(err);
225
+ void error;
226
+ }
227
+ }
228
+ /**
229
+ * What the guard SAW on one invocation, captured up front and held until the outcome is known.
230
+ * Data-only (per CLAUDE.md: classes for data, explicit construction).
231
+ */
232
+ class GuardInvocation {
233
+ root;
234
+ timestamp;
235
+ tool;
236
+ target;
237
+ branch;
238
+ sync;
239
+ projectDir;
240
+ // eslint-disable-next-line @typescript-eslint/max-params
241
+ constructor(root, timestamp, tool, target, branch, sync, projectDir) {
242
+ this.root = root;
243
+ this.timestamp = timestamp;
244
+ this.tool = tool;
245
+ this.target = target;
246
+ this.branch = branch;
247
+ this.sync = sync;
248
+ this.projectDir = projectDir;
249
+ }
250
+ }
251
+ exports.GuardInvocation = GuardInvocation;
252
+ /**
253
+ * The per-INVOCATION stream — `.webpieces/logs/calls/<writer>.log` (see LogStream for the writer
254
+ * key), one line for EVERY guards-hook
255
+ * call (allow or block, bash or file), unlike `L2-decisions/` which records only the calls a
256
+ * rule actually judged. It captures the tool, the command/file, the live git branch, the async-written
257
+ * main-sync-status.json snapshot (branch / merged / fork-point / conflict), and — since this class
258
+ * replaced a bare log-and-forget function — HOW THE CALL ENDED.
259
+ *
260
+ * WHY IT IS TWO CALLS. The line used to be written the moment the hook started, so it could not carry
261
+ * a verdict: the decision had not been made yet. Answering "what happened to this call?" therefore
262
+ * meant joining this file against the L2 decision stream BY TIMESTAMP, which is exactly the kind of
263
+ * reconstruction a log exists to make unnecessary. So {@link begin} now only CAPTURES (including the
264
+ * git/cache reads, which must still happen while the hook is running), and {@link finish} — called
265
+ * from the hook's single terminal boundary, emitAllow/emitDeny — writes the whole line once the
266
+ * outcome is known. The two streams stay distinct in purpose: this one is "every call and how it
267
+ * ended", the decision log remains "every judgement and why".
268
+ *
269
+ * Every error is swallowed: logging must never block or fail a hook.
270
+ */
271
+ class InvocationLog {
272
+ pending = null;
273
+ /**
274
+ * Capture the context of one invocation. `cwd` is the AI's working dir; the repo root that owns
275
+ * `.webpieces` is resolved from it. Writes NOTHING — {@link finish} does that.
276
+ */
277
+ begin(cwd, tool, target) {
278
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
279
+ try {
280
+ const root = new rules_config_1.RepoRootFinder().resolveRepoRoot(cwd);
281
+ const branch = branchForLog(root);
282
+ // The cache is branch-keyed, so the entry to log is the one for the branch we are standing
283
+ // on. 'unknown' (branchForLog's failure value) simply misses and logs 'sync=none'.
284
+ const sync = summarizeSyncStatus((0, repo_workflow_core_1.readMainSyncStatus)(root, branch));
285
+ this.pending = new GuardInvocation(root, new Date().toISOString(), tool, oneLine(target), branch, sync, rules_config_1.claudeEnv.projectDirForLog());
286
+ }
287
+ catch (err) {
288
+ const error = (0, to_error_1.toError)(err);
289
+ void error;
290
+ }
291
+ }
292
+ /**
293
+ * Write the captured line, now stamped with the outcome. A no-op when nothing was captured (the
294
+ * 'rules' hook, or a terminal boundary reached before begin()), and it clears the pending entry so
295
+ * a second emit cannot double-log.
296
+ *
297
+ * `rule` is the rule that blocked, or '-' when there is none; `fault` is the L0 fault code when this
298
+ * call ended on one (S/C/Y — the JS-side faults), else '-'. FIELD ORDER IS APPEND-ONLY: the five
299
+ * original fields keep their positions (cleanup automation mines this file), and `guards=` /
300
+ * `rule=` / … / `fault=` are added at the end.
301
+ */
302
+ finish(verdict, rule, fault = rules_config_2.L0_FAULT_NONE) {
303
+ const invocation = this.pending;
304
+ this.pending = null;
305
+ if (invocation === null)
306
+ return;
307
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
308
+ try {
309
+ const logsDir = tooling_common_1.dotWebpieces.logsFile(invocation.root, log_streams_1.CALLS_STREAM);
310
+ fs.mkdirSync(logsDir, { recursive: true });
311
+ const logPath = path.join(logsDir, log_stream_1.logStream.writerFile('.log'));
312
+ rotateLogFile(logPath, path.join(logsDir, log_stream_1.logStream.writerFile('.1.log')));
313
+ const line = [
314
+ `[${invocation.timestamp}]`,
315
+ invocation.tool,
316
+ invocation.target,
317
+ `branch=${invocation.branch}`,
318
+ invocation.sync,
319
+ // `guards=`, NOT `verdict=`. This hook can only report on ITSELF. Claude Code runs all
320
+ // its PreToolUse hooks IN PARALLEL, so another hook process may deny a call this one
321
+ // had no objection to, and neither can see the other's answer. Measured under the
322
+ // RETIRED three-hook form: `cd <repo>/packages && ls` was DENIED by L-1 and recorded
323
+ // here three times as `verdict=ALLOW`. The old field name promised an outcome it
324
+ // structurally cannot know, so the name stayed even though L-1 is gone: the two
325
+ // surviving hooks still run in parallel and still cannot see each other.
326
+ `guards=${verdict}`,
327
+ `rule=${oneLine(rule) || '-'}`,
328
+ // The tree the guard ACTED in, next to what Claude Code said the project was. Both, on
329
+ // every line, because the diagnostic value is entirely in comparing them — see
330
+ // ClaudeEnv for the open question this field exists to settle empirically.
331
+ `root=${invocation.root}`,
332
+ `projectDir=${invocation.projectDir}`,
333
+ // See logGuardDecision: the short tree label, so `tree=primary` with a matching
334
+ // projectDir reads as healthy at a glance and `tree=<worktree>` beside a projectDir
335
+ // pointing at the primary is the straddle, without diffing two absolute paths.
336
+ `tree=${tooling_common_1.dotWebpieces.worktreeName(invocation.root) || 'primary'}`,
337
+ // WHICH L0 fault ended this call, in the same letters and the same field name the L0 sh
338
+ // shim uses (the `L0-shim/` stream) — so ONE grep spans the whole trail.
339
+ `fault=${fault}`,
340
+ // WHICH HARNESS made the call — same field name and same vocabulary as the L0 sh shim's
341
+ // `ai=` and the decision stream's, so one grep spans the whole trail. APPEND-ONLY.
342
+ `ai=${ai_type_context_1.aiTypeContext.forLog()}`,
343
+ ].join('\t') + '\n';
344
+ fs.appendFileSync(logPath, line);
345
+ }
346
+ catch (err) {
347
+ const error = (0, to_error_1.toError)(err);
348
+ void error;
349
+ }
350
+ }
351
+ }
352
+ exports.InvocationLog = InvocationLog;
353
+ // Process-wide instance: one hook process handles exactly one tool call, so a single pending entry is
354
+ // the whole state there is. Module-scope (rather than DI) because the terminal boundary that flushes
355
+ // it — emitAllow/emitDeny — is itself module-scope protocol code with no container in reach.
356
+ exports.invocationLog = new InvocationLog();
357
+ // One-field summary of main-sync-status.json for the invocation log: the branch the cache is FOR,
358
+ // whether it is already merged (and its PR), fork-point presence, and conflict state — the signals a
359
+ // cleanup step keys off. 'sync=none' when the cache has not been written yet (first call of a session).
360
+ // webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API
361
+ function summarizeSyncStatus(status) {
362
+ if (status === null)
363
+ return 'sync=none';
364
+ const merged = status.branchAlreadyMerged ? `PR#${status.mergedPr !== '' ? status.mergedPr : '?'}` : 'no';
365
+ return `sync=${status.branch} merged=${merged} fork=${String(status.hasForkPoint)} conflict=${String(status.conflict)} ts=${status.timestamp}`;
366
+ }
367
+ // Best-effort current branch for the log line. Returns 'unknown' on any failure (e.g. not a git
368
+ // repo) — this is for display only, never for a control decision.
369
+ // webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API
370
+ function branchForLog(root) {
371
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
372
+ try {
373
+ return (0, child_process_1.execSync)('git rev-parse --abbrev-ref HEAD', {
374
+ cwd: root,
375
+ encoding: 'utf8',
376
+ stdio: ['pipe', 'pipe', 'pipe'],
377
+ }).trim() || 'unknown';
378
+ }
379
+ catch (err) {
380
+ const error = (0, to_error_1.toError)(err);
381
+ void error;
382
+ return 'unknown';
383
+ }
384
+ }
385
+ // Collapse newlines/tabs and cap length so one decision is always one log line. The collapse itself
386
+ // lives in LogTarget, because SessionCallHistory READS this format back and the two must agree byte
387
+ // for byte — a second private copy of the cap is a silent way for a long command to stop matching
388
+ // itself.
389
+ // webpieces-disable no-function-outside-class -- the module's own leaf helper, beside branchForLog/rotateLogFile
390
+ function oneLine(value) {
391
+ return log_target_1.logTarget.oneLine(value);
392
+ }
393
+ // webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API
394
+ function rotateLogFile(logPath, prevPath) {
395
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
396
+ try {
397
+ const stat = fs.statSync(logPath);
398
+ if (stat.size > MAX_LOG_BYTES) {
399
+ if (fs.existsSync(prevPath))
400
+ fs.unlinkSync(prevPath);
401
+ fs.renameSync(logPath, prevPath);
402
+ }
403
+ }
404
+ catch (err) {
405
+ const error = (0, to_error_1.toError)(err);
406
+ void error;
407
+ }
408
+ }
409
+ //# sourceMappingURL=decision-log.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"decision-log.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/core/decision-log.ts"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,EAAE,CAAC;YAC5B,IAAI,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC;gBAAE,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;YACrD,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;QACrC,CAAC;IACL,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,KAAK,KAAK,CAAC;IACf,CAAC;AACL,CAAC","sourcesContent":["import { execSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nimport { dotWebpieces } from '@webpieces/tooling-common';\nimport { readMainSyncStatus, MainSyncStatus } from '@webpieces/repo-workflow-core';\nimport { RepoRootFinder, claudeEnv } from '@webpieces/rules-config';\nimport { L1_LOCATION_STREAM, L2_DECISIONS_STREAM, CALLS_STREAM } from './log-streams';\n\nimport { L0_FAULT_NONE, L0_ROW_ALLOWLISTED, L0_ROW_BLOCKED } from '@webpieces/rules-config';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { logStream } from './log-stream';\nimport { logTarget } from './log-target';\nimport { aiTypeContext } from './ai-type-context';\nimport { l2RowForReason } from './l2-rows';\nimport { cureForMatrix } from './matrix-cures';\n\n// The SYNC decision log — what the synchronous hook DID on each invocation and WHY. Its companion is\n// the ASYNC log (the `async-refresh/` stream, written by the detached refresher in main-sync-log.ts). This\n// one records EVERY guard decision — allow, block, config-bypass, and the fail-open cases — and CITES\n// the async-written cache snapshot (`cache` field) that drove the decision, so a wrong allow/block is\n// traceable to a stale or missing async write. Writes to `.webpieces/logs/L2-decisions/<writer>.log` —\n// the LAYER is the directory, the WRITER is the file (see log-streams.ts and LogStream).\nconst MAX_LOG_BYTES = 512 * 1024; // 512 KB — rotate when exceeded (mirrors rotation in rejection-log)\n\n/**\n * THE ACTION CODEBOOK, as a type. These are the five actions GUARD_MATRIX.md numbers 1-5, and they\n * are the vocabulary EVERY layer reports in — so one grep spans L-1, L0, L1 and L2.\n *\n * The three distinctions this exists to make, none of which `'ALLOW' | 'BLOCK'` could:\n *\n * ALLOW no objection — the call was HANDED DOWN to the next layer. A layer saying ALLOW\n * is NOT saying the call ran: the layer below it, or the OTHER parallel hook, may\n * still deny. This is L1's `ACT_DOWN`.\n * ALLOW_EXEMPT out of scope by construction — allowed, and evaluation STOPS here. L1's\n * `ACT_EXEMPT`.\n * ALLOW_FAIL_OPEN state could not be established, so nothing was judged. Keeping this distinct\n * from ALLOW is the entire point of the type: a fail-open allow and a real allow\n * that look identical make it impossible to tell whether the guards are protecting\n * anything or quietly abstaining. It used to be a `' (fail-open)'` SUBSTRING on the\n * reason field, which is exactly why the abstentions were never countable.\n * BLOCK_AI_CURE blocked, and the printed cure is a command the AI can run itself.\n * BLOCK_HUMAN blocked, and it needs a human decision — or a delegation (spawn a subagent) that\n * the blocked agent cannot perform for itself.\n *\n * Hard cut, per `.claude/rules/no-backwards-compat.md`: `'BLOCK'` is GONE rather than aliased, so every\n * construction site fails to\n * compile and has to say which kind of block it is. Before, that question had exactly one wrong\n * answer available — silence.\n */\nexport type Verdict = 'ALLOW' | 'ALLOW_EXEMPT' | 'ALLOW_FAIL_OPEN' | 'BLOCK_AI_CURE' | 'BLOCK_HUMAN';\n\n/**\n * WHICH ROW of WHICH layer's decision table produced this line. Data-only → a class, per CLAUDE.md.\n *\n * `row` is the row NUMBER from the layer's row array (`L1_ROWS[i].num`, `L2_ROWS[i].num`) — the\n * same number the generated doc prints, because the doc is rendered from that same array. So a log\n * line joins to its matrix row BY NUMBER, and checking observed behaviour against the documented use\n * cases becomes a lookup rather than an investigation.\n */\nexport class MatrixRef {\n constructor(readonly layer: string, readonly row: string) {}\n}\n\n/**\n * The layer tokens. EVERY layer now cites a row: L0 through its two decision-matrix rows, L1 through\n * L1_ROWS, and L2 through L2_ROWS (see `matrixL2Row`). This used to say `'-'` was for \"a layer with no\n * row array YET (L2 is the un-converted one)\" — L2 is converted, and a comment describing a state the\n * code left behind is exactly the kind of doc a reader trusts and should not.\n *\n * `'-'` survives for ONE case, and it is a real one: an L2 reason that no row claims. See matrixL2Row.\n *\n * These are REQUIRED at the constructor, not defaulted: a defaulted `MatrixRef` would make the\n * uncited case reachable by doing nothing and impossible to grep — the same defect this file's own\n * docblock argues against for `'BLOCK'`, where silence was the one wrong answer available.\n *\n * L0 NOW CITES ITS ROW TOO. It used to be `'-'` on the grounds that \"L0's faults are a table of letters\n * rather than numbered rows\" — but L0 has BOTH: the letter says WHICH fault, and the numbered decision\n * matrix (`renderGuardMatrixDoc`) says which of its three rows was taken. There is one ALLOW row and one\n * BLOCK row, so the pair `row=` + `fault=` pins the decision exactly, and the deny an agent reads now\n * carries the identical pair. That is the join: one grep spans the deny, the log line and the doc.\n * Two constants, not one `MATRIX_L0`, because the two call sites are a cure-bypass ALLOW and an L0\n * BLOCK — one token covering both is what made the row unciteable in the first place.\n */\nexport const MATRIX_L0_ALLOW = new MatrixRef('L0', L0_ROW_ALLOWLISTED);\nexport const MATRIX_L0_BLOCK = new MatrixRef('L0', L0_ROW_BLOCKED);\n\n/**\n * The L2 reference for one decision, with the row DERIVED FROM THE REASON.\n *\n * There is no `MATRIX_L2` constant any more, and its absence is the point: a single shared instance\n * meant every L2 line in the repo carried `row=-`, which reads as \"L2 has no rows\" rather than \"this\n * decision was not classified\". Deleting it makes every construction site name a reason, and the reason\n * is the only thing a call site has that identifies which row it is an instance of.\n *\n * `l2RowForReason` returns null for a reason no row claims, and that renders as `'-'` — visible in the\n * log, not silently absorbed into a default row. l2-matrix.spec.ts reads the four guard sources and\n * fails the build if any reason literal in them is unmapped, so `-` should never appear in practice;\n * when it does, it is a genuine hole in the table and the log says so.\n */\n// webpieces-disable no-function-outside-class -- a named constructor for MatrixRef beside it, in this module of module-scope writers\nexport function matrixL2Row(reason: string): MatrixRef {\n const row = l2RowForReason(reason);\n return new MatrixRef('L2', row === null ? '-' : String(row));\n}\n\n/**\n * The L2 stream, with NO row — for the two kinds of line that genuinely are not an instance of a row.\n *\n * 1. The runner's AGGREGATE bash lines (\"no bash-guard block\" / \"bash-guard block\"). They summarise\n * the whole guard set's answer for one command, not one row's verdict; the per-guard lines that\n * DO cite rows are written alongside them by the guards themselves.\n * 2. `whole-repo-build-guard`, which is not a branch-state policy at all — it is the experimental\n * home-config guard, has no webpieces.config.json entry, and shares this stream only because the\n * stream is \"bash decisions\", not \"L2 rows\".\n *\n * A NAMED constant rather than an inline `new MatrixRef('L2', '-')`, so `grep MATRIX_L2_UNROWED` lists\n * every uncited line and the list stays short and arguable. It is deliberately NOT called `MATRIX_L2`:\n * the old name was used by everything and made \"L2 has no rows\" indistinguishable from \"this line is\n * not a row\".\n */\nexport const MATRIX_L2_UNROWED = new MatrixRef('L2', '-');\n\n// Data-only record of one guard decision (per CLAUDE.md: classes for data, not object literals).\n// `cache` summarizes the async-written main-sync-status.json that drove a feature-branch-guard\n// decision (branch/merged/conflict/fork + the cache timestamp), or '-' when no cache was consulted\n// (bash guards, on-main, config-bypass).\nexport class GuardDecision {\n rule: string;\n tool: string;\n target: string; // file path (file guards) or the bash command (bash guards)\n branch: string;\n verdict: Verdict;\n reason: string;\n cache: string;\n /**\n * The L0 fault this decision IS, in the codebook's letter (core/l0-fault-codes.ts), or `-` for an\n * ordinary rule decision. The `sh` shim has always stamped `fault=` on its own stream; the three\n * JS-side faults (S/C/Y) reached this one with no label at all, so `grep fault=S` found nothing\n * even while an S storm was blocking every call.\n */\n fault: string;\n /** Which layer + row decided this. See MatrixRef — it is what joins a log line to the doc. */\n matrix: MatrixRef;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(rule: string, tool: string, target: string, branch: string, verdict: Verdict, reason: string, cache: string = '-', fault: string, matrix: MatrixRef) {\n this.rule = rule;\n this.tool = tool;\n this.target = target;\n this.branch = branch;\n this.verdict = verdict;\n this.reason = reason;\n this.cache = cache;\n this.fault = fault;\n this.matrix = matrix;\n }\n}\n\n/**\n * Append one tab-separated line per L2 decision to `.webpieces/logs/L2-decisions/<writer>.log`, where\n * <writer> is LogStream's `<sessionId>-<agentId|coordinator>-<hook>` key (a caller that never\n * identified renders as `unknown-coordinator-hook` — there is no un-keyed name).\n * `root` is\n * the repo/workspace root that holds `.webpieces` (callers pass workspaceRoot, or a\n * RepoRootFinder-resolved root at the pre-load config-bypass site — never a raw cwd, so a bypass\n * logged from a subdir never scatters a stray `.webpieces`). Swallows all errors — logging must never\n * block or fail a hook.\n */\n// webpieces-disable no-function-outside-class -- the module-scope writer this log has always been, beside branchForLog/oneLine/rotateLogFile; it must stay callable from a tree too broken to build a DI container\nexport function logGuardDecision(root: string, decision: GuardDecision): void {\n appendDecision(root, L2_DECISIONS_STREAM, decision);\n}\n\n/**\n * The L1 stream — `.webpieces/logs/L1-location/<writer>.log`.\n *\n * L1 had NO stream. Its three blocking paths wrote into L2's file under an implementation name\n * (`force-to-root`, `trinary-version-skew`, `cd-must-be-first`), and its NON-blocking outcomes —\n * the exempt row and the three hand-down rows — wrote nothing at all. So \"L1 had no objection\" was\n * unobservable, and \"show me every L1 decision\" had no answer: L1 existed in the trail only as the\n * `root=` / `projectDir=` / `tree=` columns stapled onto somebody else's line.\n *\n * A SIBLING rather than a `base` parameter on logGuardDecision, deliberately: that signature is what\n * the process-wide `logStream` singleton exists to keep unchanged (see LogStream's docblock), and\n * `INVOCATION_LOG_FILE` already establishes the pattern of a second stream owning its own name in\n * this same module.\n */\n// webpieces-disable no-function-outside-class -- sibling of logGuardDecision, same module-scope writer shape and same reason\nexport function logL1Decision(root: string, decision: GuardDecision): void {\n appendDecision(root, L1_LOCATION_STREAM, decision);\n}\n\n// The one appender both streams share. `streamDir` is the LAYER; the writer key inside it is\n// logStream's session/agent/hook, which is what keeps one writer per file.\n// webpieces-disable no-function-outside-class -- the shared body of the two module-scope writers above\nfunction appendDecision(root: string, streamDir: string, decision: GuardDecision): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const timestamp = new Date().toISOString();\n // LOCAL scope: a guard decision belongs to the tree it judged. WHO made the call is answered\n // by the filename, which logStream names with session/agent/hook.\n const logsDir = dotWebpieces.logsFile(root, streamDir);\n fs.mkdirSync(logsDir, { recursive: true });\n\n const logPath = path.join(logsDir, logStream.writerFile('.log'));\n rotateLogFile(logPath, path.join(logsDir, logStream.writerFile('.1.log')));\n\n const line = [\n `[${timestamp}]`,\n decision.verdict,\n decision.tool,\n oneLine(decision.target),\n decision.branch,\n decision.rule,\n oneLine(decision.reason),\n oneLine(decision.cache),\n // WHICH ROW of WHICH table decided this. The directory already carries the layer, but a\n // line quoted out of its file must still say what judged it — and `row=` is the join key\n // to the generated doc, which is the point of the whole exercise.\n `layer=${decision.matrix.layer}`,\n `row=${decision.matrix.row}`,\n // The tree this decision was actually made against, and what Claude Code told the hook the\n // project was. Appended (never reordered) for the same reason as on the invocation line —\n // see ClaudeEnv: when these two disagree, that disagreement is the bug.\n `root=${root}`,\n `projectDir=${claudeEnv.projectDirForLog()}`,\n // git's name for that tree — `primary`, else the worktree name. Same literal and same\n // derivation as the L0 shim log's `tree=` (shim-audit-log.ts), so one grep spans both\n // streams: L0 carries tree without projectDir, L1 now carries both.\n `tree=${dotWebpieces.worktreeName(root) || 'primary'}`,\n // APPEND-ONLY, same spelling as the invocation line and the L0 shim log: which L0 fault\n // this was, or `-`.\n `fault=${decision.fault}`,\n // WHAT THE AGENT WAS TOLD TO DO — looked up from the row above, never passed in, so it is\n // by construction the same literal the generated matrix prints for that row (see\n // matrix-cures.ts). `row=` says which row judged the call; this says what that row\n // prescribed, which is what makes the trail auditable against the doc without opening it.\n // APPEND-ONLY, like every field before it.\n `cure=${oneLine(cureForMatrix(decision.matrix.layer, decision.matrix.row))}`,\n // WHICH HARNESS made the call, spelled exactly as the L0 sh shim spells it on its own\n // stream — so ONE grep (`ai=codex`) spans all five streams and \"is Codex actually being\n // guarded?\" is a question the trail can answer. APPEND-ONLY, like every field before it; a\n // row from a release that predates this carries no `ai=` and reads as `unknown`.\n `ai=${aiTypeContext.forLog()}`,\n ].join('\\t') + '\\n';\n fs.appendFileSync(logPath, line);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n}\n\n/**\n * What the guard SAW on one invocation, captured up front and held until the outcome is known.\n * Data-only (per CLAUDE.md: classes for data, explicit construction).\n */\nexport class GuardInvocation {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n public readonly root: string,\n public readonly timestamp: string,\n public readonly tool: string,\n public readonly target: string,\n public readonly branch: string,\n public readonly sync: string,\n public readonly projectDir: string,\n ) {}\n}\n\n/**\n * The per-INVOCATION stream — `.webpieces/logs/calls/<writer>.log` (see LogStream for the writer\n * key), one line for EVERY guards-hook\n * call (allow or block, bash or file), unlike `L2-decisions/` which records only the calls a\n * rule actually judged. It captures the tool, the command/file, the live git branch, the async-written\n * main-sync-status.json snapshot (branch / merged / fork-point / conflict), and — since this class\n * replaced a bare log-and-forget function — HOW THE CALL ENDED.\n *\n * WHY IT IS TWO CALLS. The line used to be written the moment the hook started, so it could not carry\n * a verdict: the decision had not been made yet. Answering \"what happened to this call?\" therefore\n * meant joining this file against the L2 decision stream BY TIMESTAMP, which is exactly the kind of\n * reconstruction a log exists to make unnecessary. So {@link begin} now only CAPTURES (including the\n * git/cache reads, which must still happen while the hook is running), and {@link finish} — called\n * from the hook's single terminal boundary, emitAllow/emitDeny — writes the whole line once the\n * outcome is known. The two streams stay distinct in purpose: this one is \"every call and how it\n * ended\", the decision log remains \"every judgement and why\".\n *\n * Every error is swallowed: logging must never block or fail a hook.\n */\nexport class InvocationLog {\n private pending: GuardInvocation | null = null;\n\n /**\n * Capture the context of one invocation. `cwd` is the AI's working dir; the repo root that owns\n * `.webpieces` is resolved from it. Writes NOTHING — {@link finish} does that.\n */\n begin(cwd: string, tool: string, target: string): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const root = new RepoRootFinder().resolveRepoRoot(cwd);\n const branch = branchForLog(root);\n // The cache is branch-keyed, so the entry to log is the one for the branch we are standing\n // on. 'unknown' (branchForLog's failure value) simply misses and logs 'sync=none'.\n const sync = summarizeSyncStatus(readMainSyncStatus(root, branch));\n this.pending = new GuardInvocation(root, new Date().toISOString(), tool, oneLine(target), branch, sync, claudeEnv.projectDirForLog());\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n }\n\n /**\n * Write the captured line, now stamped with the outcome. A no-op when nothing was captured (the\n * 'rules' hook, or a terminal boundary reached before begin()), and it clears the pending entry so\n * a second emit cannot double-log.\n *\n * `rule` is the rule that blocked, or '-' when there is none; `fault` is the L0 fault code when this\n * call ended on one (S/C/Y — the JS-side faults), else '-'. FIELD ORDER IS APPEND-ONLY: the five\n * original fields keep their positions (cleanup automation mines this file), and `guards=` /\n * `rule=` / … / `fault=` are added at the end.\n */\n finish(verdict: Verdict, rule: string, fault: string = L0_FAULT_NONE): void {\n const invocation = this.pending;\n this.pending = null;\n if (invocation === null) return;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const logsDir = dotWebpieces.logsFile(invocation.root, CALLS_STREAM);\n fs.mkdirSync(logsDir, { recursive: true });\n const logPath = path.join(logsDir, logStream.writerFile('.log'));\n rotateLogFile(logPath, path.join(logsDir, logStream.writerFile('.1.log')));\n\n const line = [\n `[${invocation.timestamp}]`,\n invocation.tool,\n invocation.target,\n `branch=${invocation.branch}`,\n invocation.sync,\n // `guards=`, NOT `verdict=`. This hook can only report on ITSELF. Claude Code runs all\n // its PreToolUse hooks IN PARALLEL, so another hook process may deny a call this one\n // had no objection to, and neither can see the other's answer. Measured under the\n // RETIRED three-hook form: `cd <repo>/packages && ls` was DENIED by L-1 and recorded\n // here three times as `verdict=ALLOW`. The old field name promised an outcome it\n // structurally cannot know, so the name stayed even though L-1 is gone: the two\n // surviving hooks still run in parallel and still cannot see each other.\n `guards=${verdict}`,\n `rule=${oneLine(rule) || '-'}`,\n // The tree the guard ACTED in, next to what Claude Code said the project was. Both, on\n // every line, because the diagnostic value is entirely in comparing them — see\n // ClaudeEnv for the open question this field exists to settle empirically.\n `root=${invocation.root}`,\n `projectDir=${invocation.projectDir}`,\n // See logGuardDecision: the short tree label, so `tree=primary` with a matching\n // projectDir reads as healthy at a glance and `tree=<worktree>` beside a projectDir\n // pointing at the primary is the straddle, without diffing two absolute paths.\n `tree=${dotWebpieces.worktreeName(invocation.root) || 'primary'}`,\n // WHICH L0 fault ended this call, in the same letters and the same field name the L0 sh\n // shim uses (the `L0-shim/` stream) — so ONE grep spans the whole trail.\n `fault=${fault}`,\n // WHICH HARNESS made the call — same field name and same vocabulary as the L0 sh shim's\n // `ai=` and the decision stream's, so one grep spans the whole trail. APPEND-ONLY.\n `ai=${aiTypeContext.forLog()}`,\n ].join('\\t') + '\\n';\n fs.appendFileSync(logPath, line);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n }\n}\n\n// Process-wide instance: one hook process handles exactly one tool call, so a single pending entry is\n// the whole state there is. Module-scope (rather than DI) because the terminal boundary that flushes\n// it — emitAllow/emitDeny — is itself module-scope protocol code with no container in reach.\nexport const invocationLog = new InvocationLog();\n\n// One-field summary of main-sync-status.json for the invocation log: the branch the cache is FOR,\n// whether it is already merged (and its PR), fork-point presence, and conflict state — the signals a\n// cleanup step keys off. 'sync=none' when the cache has not been written yet (first call of a session).\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nfunction summarizeSyncStatus(status: MainSyncStatus | null): string {\n if (status === null) return 'sync=none';\n const merged = status.branchAlreadyMerged ? `PR#${status.mergedPr !== '' ? status.mergedPr : '?'}` : 'no';\n return `sync=${status.branch} merged=${merged} fork=${String(status.hasForkPoint)} conflict=${String(status.conflict)} ts=${status.timestamp}`;\n}\n\n// Best-effort current branch for the log line. Returns 'unknown' on any failure (e.g. not a git\n// repo) — this is for display only, never for a control decision.\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nexport function branchForLog(root: string): string {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return execSync('git rev-parse --abbrev-ref HEAD', {\n cwd: root,\n encoding: 'utf8',\n stdio: ['pipe', 'pipe', 'pipe'],\n }).trim() || 'unknown';\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return 'unknown';\n }\n}\n\n// Collapse newlines/tabs and cap length so one decision is always one log line. The collapse itself\n// lives in LogTarget, because SessionCallHistory READS this format back and the two must agree byte\n// for byte — a second private copy of the cap is a silent way for a long command to stop matching\n// itself.\n// webpieces-disable no-function-outside-class -- the module's own leaf helper, beside branchForLog/rotateLogFile\nfunction oneLine(value: string): string {\n return logTarget.oneLine(value);\n}\n\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nfunction rotateLogFile(logPath: string, prevPath: string): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const stat = fs.statSync(logPath);\n if (stat.size > MAX_LOG_BYTES) {\n if (fs.existsSync(prevPath)) fs.unlinkSync(prevPath);\n fs.renameSync(logPath, prevPath);\n }\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n}\n"]}
@@ -0,0 +1,101 @@
1
+ import { ExcludePaths } from '@webpieces/rules-config';
2
+ import { CommandScanner } from '@webpieces/hook-runtime';
3
+ /**
4
+ * One path the denied command NAMED that `excludePaths` already exempts, plus how to reach it.
5
+ *
6
+ * Data-only, so a class (per CLAUDE.md).
7
+ *
8
+ * `cdDirectory` is the whole point of the class rather than a bare string: it is a directory that
9
+ * ITSELF satisfies `globMatches` against one of the configured globs, or null when no such directory
10
+ * exists for this reference. Callers must never invent one — see ExcludedPathEscapeScan for why a
11
+ * naive `dirname` is wrong exactly when it looks most obviously right.
12
+ */
13
+ export declare class ExcludedPathReference {
14
+ /** The referenced path, workspace-relative, as it was matched. */
15
+ readonly referencedPath: string;
16
+ /** The `excludePaths` glob that matched it — quoted back so the agent need not re-derive it. */
17
+ readonly matchedGlob: string;
18
+ /** A directory a `cd` may legally land in (matches a glob on its own), or null when none does. */
19
+ readonly cdDirectory: string | null;
20
+ /** `referencedPath` re-expressed relative to `cdDirectory`; '' when there is no `cdDirectory`. */
21
+ readonly pathFromCdDirectory: string;
22
+ constructor(referencedPath: string, matchedGlob: string, cdDirectory: string | null, pathFromCdDirectory: string);
23
+ }
24
+ /**
25
+ * Finds the paths a BASH command names that the top-level `excludePaths` already exempts.
26
+ *
27
+ * WHY this exists: the bash guards judge the shell's effective CWD, not the paths in the command, so
28
+ * `cat .webpieces/tasks.md` at the repo root is DENIED even though that exact file is exempt from
29
+ * every guard and was reachable, that instant, through Read/Write. Every remedy the deny body printed
30
+ * was a git state change — strictly more destructive than the one it omitted. This class supplies the
31
+ * missing sentence; it changes no verdict.
32
+ *
33
+ * A token is treated as a candidate path with no filesystem check: whether it exists says nothing
34
+ * about whether it is exempt, and a stat per token on the blocking hook path is exactly the cost these
35
+ * guards avoid. Non-path tokens (a `grep` pattern, a `sed` script) simply match no glob.
36
+ */
37
+ export declare class ExcludedPathEscapeScan {
38
+ private readonly scanner;
39
+ private readonly workspaceRoot;
40
+ private readonly effectiveCwd;
41
+ /**
42
+ * `effectiveCwd` is the directory the command really runs in, after its own leading `cd` — the
43
+ * same base ContentReadScan resolves relative operands against. RELATIVE tokens are resolved
44
+ * there and ABSOLUTE ones normalised straight to workspace-relative, which is how
45
+ * `cat /abs/path/to/repo/.webpieces/tasks.md` reaches the same verdict as `cat .webpieces/tasks.md`.
46
+ */
47
+ constructor(scanner: CommandScanner, workspaceRoot: string, effectiveCwd: string);
48
+ /**
49
+ * Every excluded path this command references, in command order, de-duplicated.
50
+ *
51
+ * Scans EVERY segment, not just a leading `cd`: `cat x`, `grep -n foo x`, `sed -n '1,5p' x` and a
52
+ * path inside an `&&` compound all count, because the agent's next move depends on the file it
53
+ * wanted, wherever in the line it named it.
54
+ */
55
+ references(command: string, ex: ExcludePaths): readonly ExcludedPathReference[];
56
+ private reference;
57
+ /**
58
+ * A directory the agent may `cd` into and have the guards actually stand down, or null.
59
+ *
60
+ * THE TRAP: the bash path matches the relative cwd with `globMatches`, which compiles
61
+ * `.webpieces/**` to the anchored `/^\.webpieces\/.*$/` — the `/` is a LITERAL, so the bare
62
+ * directory `.webpieces` does NOT match its own glob. `cd .webpieces && cat tasks.md` is still
63
+ * denied. Emitting that would be worse than emitting nothing: it looks authoritative and costs a
64
+ * turn to disprove. So the directory is only offered when it passes the very same matcher the
65
+ * runner will use, and the renderer says so plainly when nothing does.
66
+ */
67
+ private cdDirectory;
68
+ private matchingGlob;
69
+ /**
70
+ * Workspace-relative form of a token, or null when it is not a path inside this workspace.
71
+ *
72
+ * `~`-rooted and out-of-tree paths are nothing to do with this repo's exclusions, and the
73
+ * workspace root itself ('') matches no glob by construction.
74
+ */
75
+ private workspaceRelative;
76
+ /**
77
+ * Every token that could name a file: each segment's words minus the command word itself and
78
+ * minus flags. Deliberately generous — a token that is not a path matches no glob, while a token
79
+ * dropped by a cleverer filter is a file the agent is never told it can read.
80
+ */
81
+ private candidateTokens;
82
+ }
83
+ /**
84
+ * Renders the leading stanza of a bash deny body: the Read/Write escape the agent already has, and —
85
+ * when one genuinely exists — the `cd` that makes bash itself work.
86
+ *
87
+ * It goes at the TOP of the report, above the git remedies, because the agent acts on the first
88
+ * actionable thing it reads. The live incident this fixes had the agent create a branch in a human's
89
+ * working tree to record a row in a gitignored scratch file; the cheap, side-effect-free path was one
90
+ * sentence away and never printed. Returns '' when the command names no excluded path, so a repo
91
+ * without exemptions — and every command that names nothing exempt — sees no extra noise.
92
+ */
93
+ export declare class ExcludedPathEscapeHint {
94
+ private readonly scan;
95
+ /** `effectiveCwd` is the directory the command really runs in — see ExcludedPathEscapeScan. */
96
+ constructor(workspaceRoot: string, effectiveCwd: string);
97
+ render(command: string, ex: ExcludePaths): string;
98
+ private bashLines;
99
+ private cdLines;
100
+ private noCdLines;
101
+ }