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

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,108 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SyncLogEvent = void 0;
4
+ exports.logSyncEvent = logSyncEvent;
5
+ exports.refresherChildStdioPath = refresherChildStdioPath;
6
+ const tslib_1 = require("tslib");
7
+ const fs = tslib_1.__importStar(require("fs"));
8
+ const path = tslib_1.__importStar(require("path"));
9
+ const tooling_common_1 = require("@webpieces/tooling-common");
10
+ const log_streams_1 = require("./log-streams");
11
+ const to_error_1 = require("@webpieces/tooling-common/to-error");
12
+ const log_stream_1 = require("./log-stream");
13
+ // The ASYNC log — observability for the detached background refresher (sync-main.ts) that writes
14
+ // main-sync-status.json. Its companion is the SYNC log (sync-decisions.log, decision-log.ts) which
15
+ // records what the hook DECIDED using that cache. The refresher runs AFTER the spawning hook has
16
+ // exited, with stdio discarded, so when it fails to update the cache there is normally no trace.
17
+ // This log captures its lifecycle — SPAWN_ATTEMPT (parent side), then START / SKIP_INPROGRESS /
18
+ // FINISH / ERROR (child side) — so we can tell whether the detached child never launched, was killed
19
+ // mid-run (START with no FINISH), or threw. Writes to
20
+ // `.webpieces/logs/async-refresh/<writer>.log`, where <writer> is LogStream's
21
+ // `<sessionId>-<agentId|coordinator>-<hook>` key (see LOGS_STATE_DIR and ASYNC_REFRESH_STREAM).
22
+ //
23
+ // THE CHILD'S RAW STDIO GOES TO THIS SAME FILE. It used to have a `.stderr.log` sibling, which was
24
+ // 0 bytes on every measured run — it is written to ONLY when the child dies before its own logging
25
+ // (a module-load failure, say), and that is precisely the moment you want the crash output sitting
26
+ // directly beneath the SPAWN_ATTEMPT that preceded it, in time order, rather than in a second file
27
+ // you have to think to open. Same cycle, same writer, one file.
28
+ const MAX_LOG_BYTES = 512 * 1024; // 512 KB — rotate when exceeded (mirrors decision-log)
29
+ const MAX_DETAIL_LEN = 300;
30
+ // Data-only record of one refresher lifecycle event (per CLAUDE.md: classes for data).
31
+ class SyncLogEvent {
32
+ phase;
33
+ pid;
34
+ branchArg;
35
+ detail;
36
+ constructor(phase, pid, branchArg, detail) {
37
+ this.phase = phase;
38
+ this.pid = pid;
39
+ this.branchArg = branchArg;
40
+ this.detail = detail;
41
+ }
42
+ }
43
+ exports.SyncLogEvent = SyncLogEvent;
44
+ /**
45
+ * Append one tab-separated line per refresher event to
46
+ * `.webpieces/logs/async-refresh/<writer>.log` (see LogStream for the writer key). `root` is
47
+ * the workspace root holding `.webpieces`. Swallows all errors — logging must never block or fail
48
+ * the refresher (or the hook that spawns it).
49
+ */
50
+ // webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API
51
+ function logSyncEvent(root, event) {
52
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
53
+ try {
54
+ const timestamp = new Date().toISOString();
55
+ // LOCAL scope: this is the refresher's own lifecycle trace for THIS worktree. One writer per
56
+ // log, so its appends cannot interleave with another agent's.
57
+ const logsDir = tooling_common_1.dotWebpieces.logsFile(root, log_streams_1.ASYNC_REFRESH_STREAM);
58
+ fs.mkdirSync(logsDir, { recursive: true });
59
+ const logPath = path.join(logsDir, log_stream_1.logStream.writerFile('.log'));
60
+ rotateLogFile(logPath, path.join(logsDir, log_stream_1.logStream.writerFile('.1.log')));
61
+ const line = [
62
+ `[${timestamp}]`,
63
+ event.phase,
64
+ `pid=${String(event.pid)}`,
65
+ event.branchArg,
66
+ oneLine(event.detail),
67
+ ].join('\t') + '\n';
68
+ fs.appendFileSync(logPath, line);
69
+ }
70
+ catch (err) {
71
+ const error = (0, to_error_1.toError)(err);
72
+ void error;
73
+ }
74
+ }
75
+ // The path the detached child's stdout/stderr are redirected to (opened with fs.openSync(p,'a') by
76
+ // the spawner), so even a crash BEFORE our own logging runs — e.g. a module-load failure — is
77
+ // captured instead of vanishing into /dev/null. Callers must ensure the log dir exists first
78
+ // (logSyncEvent's mkdir, called for SPAWN_ATTEMPT, does that).
79
+ //
80
+ // This is THE SAME FILE logSyncEvent appends to — see the header. It is not a second stream and it
81
+ // no longer has a name of its own.
82
+ // webpieces-disable no-function-outside-class -- sibling of logSyncEvent in this module-scope writer; it must stay callable from a tree too broken to build a DI container
83
+ function refresherChildStdioPath(root) {
84
+ return tooling_common_1.dotWebpieces.logsFile(root, log_streams_1.ASYNC_REFRESH_STREAM, log_stream_1.logStream.writerFile('.log'));
85
+ }
86
+ // Collapse newlines/tabs and cap length so one event is always one log line.
87
+ // webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API
88
+ function oneLine(value) {
89
+ const flat = value.replace(/[\t\r\n]+/g, ' ').trim();
90
+ return flat.length <= MAX_DETAIL_LEN ? flat : flat.slice(0, MAX_DETAIL_LEN) + '…';
91
+ }
92
+ // webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API
93
+ function rotateLogFile(logPath, prevPath) {
94
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
95
+ try {
96
+ const stat = fs.statSync(logPath);
97
+ if (stat.size > MAX_LOG_BYTES) {
98
+ if (fs.existsSync(prevPath))
99
+ fs.unlinkSync(prevPath);
100
+ fs.renameSync(logPath, prevPath);
101
+ }
102
+ }
103
+ catch (err) {
104
+ const error = (0, to_error_1.toError)(err);
105
+ void error;
106
+ }
107
+ }
108
+ //# sourceMappingURL=main-sync-log.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"main-sync-log.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/core/main-sync-log.ts"],"names":[],"mappings":";;;AAmDA,oCAwBC;AAUD,0DAEC;;AAvFD,+CAAyB;AACzB,mDAA6B;AAE7B,8DAAyD;AACzD,+CAAqD;AAErD,iEAA6D;AAC7D,6CAAyC;AAEzC,iGAAiG;AACjG,mGAAmG;AACnG,iGAAiG;AACjG,iGAAiG;AACjG,gGAAgG;AAChG,qGAAqG;AACrG,sDAAsD;AACtD,8EAA8E;AAC9E,gGAAgG;AAChG,EAAE;AACF,mGAAmG;AACnG,mGAAmG;AACnG,mGAAmG;AACnG,mGAAmG;AACnG,gEAAgE;AAChE,MAAM,aAAa,GAAG,GAAG,GAAG,IAAI,CAAC,CAAC,uDAAuD;AACzF,MAAM,cAAc,GAAG,GAAG,CAAC;AAI3B,uFAAuF;AACvF,MAAa,YAAY;IACrB,KAAK,CAAY;IACjB,GAAG,CAAS;IACZ,SAAS,CAAS;IAClB,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esContent":["import * as fs from 'fs';\nimport * as path from 'path';\n\nimport { dotWebpieces } from '@webpieces/tooling-common';\nimport { ASYNC_REFRESH_STREAM } from './log-streams';\n\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { logStream } from './log-stream';\n\n// The ASYNC log — observability for the detached background refresher (sync-main.ts) that writes\n// main-sync-status.json. Its companion is the SYNC log (sync-decisions.log, decision-log.ts) which\n// records what the hook DECIDED using that cache. The refresher runs AFTER the spawning hook has\n// exited, with stdio discarded, so when it fails to update the cache there is normally no trace.\n// This log captures its lifecycle — SPAWN_ATTEMPT (parent side), then START / SKIP_INPROGRESS /\n// FINISH / ERROR (child side) — so we can tell whether the detached child never launched, was killed\n// mid-run (START with no FINISH), or threw. Writes to\n// `.webpieces/logs/async-refresh/<writer>.log`, where <writer> is LogStream's\n// `<sessionId>-<agentId|coordinator>-<hook>` key (see LOGS_STATE_DIR and ASYNC_REFRESH_STREAM).\n//\n// THE CHILD'S RAW STDIO GOES TO THIS SAME FILE. It used to have a `.stderr.log` sibling, which was\n// 0 bytes on every measured run — it is written to ONLY when the child dies before its own logging\n// (a module-load failure, say), and that is precisely the moment you want the crash output sitting\n// directly beneath the SPAWN_ATTEMPT that preceded it, in time order, rather than in a second file\n// you have to think to open. Same cycle, same writer, one file.\nconst MAX_LOG_BYTES = 512 * 1024; // 512 KB — rotate when exceeded (mirrors decision-log)\nconst MAX_DETAIL_LEN = 300;\n\nexport type SyncPhase = 'SPAWN_ATTEMPT' | 'START' | 'SKIP_INPROGRESS' | 'FINISH' | 'ERROR';\n\n// Data-only record of one refresher lifecycle event (per CLAUDE.md: classes for data).\nexport class SyncLogEvent {\n phase: SyncPhase;\n pid: number;\n branchArg: string;\n detail: string;\n\n constructor(phase: SyncPhase, pid: number, branchArg: string, detail: string) {\n this.phase = phase;\n this.pid = pid;\n this.branchArg = branchArg;\n this.detail = detail;\n }\n}\n\n/**\n * Append one tab-separated line per refresher event to\n * `.webpieces/logs/async-refresh/<writer>.log` (see LogStream for the writer key). `root` is\n * the workspace root holding `.webpieces`. Swallows all errors — logging must never block or fail\n * the refresher (or the hook that spawns it).\n */\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nexport function logSyncEvent(root: string, event: SyncLogEvent): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const timestamp = new Date().toISOString();\n // LOCAL scope: this is the refresher's own lifecycle trace for THIS worktree. One writer per\n // log, so its appends cannot interleave with another agent's.\n const logsDir = dotWebpieces.logsFile(root, ASYNC_REFRESH_STREAM);\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 event.phase,\n `pid=${String(event.pid)}`,\n event.branchArg,\n oneLine(event.detail),\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// The path the detached child's stdout/stderr are redirected to (opened with fs.openSync(p,'a') by\n// the spawner), so even a crash BEFORE our own logging runs — e.g. a module-load failure — is\n// captured instead of vanishing into /dev/null. Callers must ensure the log dir exists first\n// (logSyncEvent's mkdir, called for SPAWN_ATTEMPT, does that).\n//\n// This is THE SAME FILE logSyncEvent appends to — see the header. It is not a second stream and it\n// no longer has a name of its own.\n// webpieces-disable no-function-outside-class -- sibling of logSyncEvent in this module-scope writer; it must stay callable from a tree too broken to build a DI container\nexport function refresherChildStdioPath(root: string): string {\n return dotWebpieces.logsFile(root, ASYNC_REFRESH_STREAM, logStream.writerFile('.log'));\n}\n\n// Collapse newlines/tabs and cap length so one event is always one log line.\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nfunction oneLine(value: string): string {\n const flat = value.replace(/[\\t\\r\\n]+/g, ' ').trim();\n return flat.length <= MAX_DETAIL_LEN ? flat : flat.slice(0, MAX_DETAIL_LEN) + '…';\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,39 @@
1
+ import { StreamIdentity } from './log-stream';
2
+ export declare function resetMainSyncRefreshLatchForTest(): void;
3
+ /**
4
+ * The detached child's argv, spawner side. Positions here are offset by two from the child's
5
+ * `process.argv` (node + script path), so this array's 3/4/5 are the child's 4/5/6 — which is what
6
+ * `sync-main.ts:spawnerIdentity` reads. The two are pinned against each other by ONE test, because a
7
+ * silent disagreement about these positions IS the bug being fixed: the child previously received no
8
+ * identity at all and wrote every line to the shared `unknown-coordinator-hook-` stream.
9
+ */
10
+ export declare function refresherArgv(refresher: string, workspaceRoot: string, hangTimeoutMinutes: number, identity: StreamIdentity): string[];
11
+ /**
12
+ * Fire-and-forget spawn of the detached refresher (sync-main.js in this same dir — spawned by path,
13
+ * not a bin). The child outlives this hook process (`detached` + `unref`), does the slow
14
+ * merged-PR/fetch/merge-base/overlap work, and writes the cache the feature-branch-guard reads on
15
+ * the NEXT call. This is the first detached spawn in the codebase — every existing hook is synchronous.
16
+ *
17
+ * Observability: we log SPAWN_ATTEMPT here and the child logs START/FINISH/ERROR, all to
18
+ * `.webpieces/logs/async-refresh/<writer>.log` (LogStream names every writer). The child's
19
+ * stdout/stderr are redirected to a sibling file (not
20
+ * /dev/null) so a crash before the child's own logging is still captured. If the async-refresh stream shows
21
+ * SPAWN_ATTEMPT but never START, the detached child was killed before it ran.
22
+ *
23
+ * `hangTimeoutMinutes` IS REQUIRED, deliberately. It used to default to DEFAULT_HANG_TIMEOUT_MINUTES,
24
+ * and that default is the mechanism by which three of the four configured values could never reach a
25
+ * spawn: two callers ran before any guard and simply omitted the argument, and the at-most-once latch
26
+ * below then meant the guard's own call — the one carrying the configured value — was a no-op. An
27
+ * omitted argument that silently means "the default" is unreadable at the call site and impossible to
28
+ * grep. Required makes every caller say which value it is passing, and makes forgetting a compile error.
29
+ *
30
+ * THE IDENTITY GOES ON ARGV, and that is what makes the sentence above true. The child is a separate
31
+ * node process whose `logStream` starts unidentified, so it used to write every line to the shared
32
+ * `unknown-coordinator-hook.log` while this parent wrote SPAWN_ATTEMPT to its own
33
+ * prefixed stream. One cycle, two files — the SPAWN_ATTEMPT-without-START check then read as a
34
+ * failure on every cycle even when the child ran perfectly — and every agent's child appending to
35
+ * that one shared path is exactly the multi-writer tearing LogStream exists to remove. Passing
36
+ * session/agent/hook through (positional argv, alongside the root and timeout the child already
37
+ * takes) puts the whole cycle back in ONE file.
38
+ */
39
+ export declare function triggerMainSyncRefresh(workspaceRoot: string, hangTimeoutMinutes: number): void;
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resetMainSyncRefreshLatchForTest = resetMainSyncRefreshLatchForTest;
4
+ exports.refresherArgv = refresherArgv;
5
+ exports.triggerMainSyncRefresh = triggerMainSyncRefresh;
6
+ const tslib_1 = require("tslib");
7
+ const child_process_1 = require("child_process");
8
+ const fs = tslib_1.__importStar(require("fs"));
9
+ const path = tslib_1.__importStar(require("path"));
10
+ const to_error_1 = require("@webpieces/tooling-common/to-error");
11
+ const main_sync_log_1 = require("./main-sync-log");
12
+ const log_stream_1 = require("./log-stream");
13
+ // Per-process latch for the spawn below. A hook process handles exactly one tool call, so this makes
14
+ // the refresher at-most-once per tool call. Exported reset is test-only.
15
+ let alreadyTriggered = false;
16
+ // webpieces-disable no-function-outside-class -- test-only latch reset, matching this module's function shape
17
+ function resetMainSyncRefreshLatchForTest() {
18
+ alreadyTriggered = false;
19
+ }
20
+ /**
21
+ * The detached child's argv, spawner side. Positions here are offset by two from the child's
22
+ * `process.argv` (node + script path), so this array's 3/4/5 are the child's 4/5/6 — which is what
23
+ * `sync-main.ts:spawnerIdentity` reads. The two are pinned against each other by ONE test, because a
24
+ * silent disagreement about these positions IS the bug being fixed: the child previously received no
25
+ * identity at all and wrote every line to the shared `unknown-coordinator-hook-` stream.
26
+ */
27
+ // webpieces-disable no-function-outside-class -- argv builder for this module's spawn, matching its function shape
28
+ function refresherArgv(refresher, workspaceRoot, hangTimeoutMinutes, identity) {
29
+ return [refresher, workspaceRoot, String(hangTimeoutMinutes), identity.sessionId, identity.agentId, identity.hook];
30
+ }
31
+ /**
32
+ * Fire-and-forget spawn of the detached refresher (sync-main.js in this same dir — spawned by path,
33
+ * not a bin). The child outlives this hook process (`detached` + `unref`), does the slow
34
+ * merged-PR/fetch/merge-base/overlap work, and writes the cache the feature-branch-guard reads on
35
+ * the NEXT call. This is the first detached spawn in the codebase — every existing hook is synchronous.
36
+ *
37
+ * Observability: we log SPAWN_ATTEMPT here and the child logs START/FINISH/ERROR, all to
38
+ * `.webpieces/logs/async-refresh/<writer>.log` (LogStream names every writer). The child's
39
+ * stdout/stderr are redirected to a sibling file (not
40
+ * /dev/null) so a crash before the child's own logging is still captured. If the async-refresh stream shows
41
+ * SPAWN_ATTEMPT but never START, the detached child was killed before it ran.
42
+ *
43
+ * `hangTimeoutMinutes` IS REQUIRED, deliberately. It used to default to DEFAULT_HANG_TIMEOUT_MINUTES,
44
+ * and that default is the mechanism by which three of the four configured values could never reach a
45
+ * spawn: two callers ran before any guard and simply omitted the argument, and the at-most-once latch
46
+ * below then meant the guard's own call — the one carrying the configured value — was a no-op. An
47
+ * omitted argument that silently means "the default" is unreadable at the call site and impossible to
48
+ * grep. Required makes every caller say which value it is passing, and makes forgetting a compile error.
49
+ *
50
+ * THE IDENTITY GOES ON ARGV, and that is what makes the sentence above true. The child is a separate
51
+ * node process whose `logStream` starts unidentified, so it used to write every line to the shared
52
+ * `unknown-coordinator-hook.log` while this parent wrote SPAWN_ATTEMPT to its own
53
+ * prefixed stream. One cycle, two files — the SPAWN_ATTEMPT-without-START check then read as a
54
+ * failure on every cycle even when the child ran perfectly — and every agent's child appending to
55
+ * that one shared path is exactly the multi-writer tearing LogStream exists to remove. Passing
56
+ * session/agent/hook through (positional argv, alongside the root and timeout the child already
57
+ * takes) puts the whole cycle back in ONE file.
58
+ */
59
+ // webpieces-disable no-function-outside-class -- the module's one entry point, beside refresherArgv; a detached fire-and-forget spawn has no state to inject and must stay callable from a tree too broken to build a DI container
60
+ function triggerMainSyncRefresh(workspaceRoot, hangTimeoutMinutes) {
61
+ // ONE refresher per hook process. Several call sites fire this on a single tool call — the Read
62
+ // fast path in hook-core AND read-stale-guard's own check(), for one — which is why the log showed
63
+ // two SPAWN_ATTEMPTs ~20ms apart from the same pid on every cycle. The loser only ever reached the
64
+ // lock and exited, so the second child was pure waste (and one more `git fetch` racing the
65
+ // agent's). The child's lock still guards against refreshers from OTHER hook processes.
66
+ if (alreadyTriggered)
67
+ return;
68
+ alreadyTriggered = true;
69
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
70
+ try {
71
+ const refresher = path.join(__dirname, 'sync-main.js');
72
+ // SPAWN_ATTEMPT first — this also creates .webpieces/logs so the stderr fd below can open.
73
+ (0, main_sync_log_1.logSyncEvent)(workspaceRoot, new main_sync_log_1.SyncLogEvent('SPAWN_ATTEMPT', process.pid, '-', `refresher=${refresher}`));
74
+ // Redirect the detached child's stdout+stderr to a file (not /dev/null) so an uncaught crash
75
+ // before the child's own logging — e.g. a module-load failure — is still captured.
76
+ const errFd = fs.openSync((0, main_sync_log_1.refresherChildStdioPath)(workspaceRoot), 'a');
77
+ const child = (0, child_process_1.spawn)(process.execPath, refresherArgv(refresher, workspaceRoot, hangTimeoutMinutes, log_stream_1.logStream.identity()), {
78
+ detached: true,
79
+ stdio: ['ignore', errFd, errFd],
80
+ });
81
+ // spawn errors (e.g. ENOENT) arrive asynchronously; record one if it fires. The hook may exit
82
+ // before this handler runs, but on POSIX a successful exec has already happened by now.
83
+ child.once('error', (err) => {
84
+ (0, main_sync_log_1.logSyncEvent)(workspaceRoot, new main_sync_log_1.SyncLogEvent('ERROR', child.pid ?? -1, '-', `spawn failed: ${err.message}`));
85
+ });
86
+ child.unref();
87
+ // The child has its own dup'd copy of the fd after spawn; close the parent's copy.
88
+ fs.closeSync(errFd);
89
+ }
90
+ catch (err) {
91
+ const error = (0, to_error_1.toError)(err);
92
+ void error;
93
+ // Spawning the background refresh must never block or fail the tool call.
94
+ }
95
+ }
96
+ //# sourceMappingURL=main-sync-refresh.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"main-sync-refresh.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/core/main-sync-refresh.ts"],"names":[],"mappings":";;AAaA,4EAEC;AAUD,sCAEC;AA+BD,wDAmCC;;AA7FD,iDAAsC;AACtC,+CAAyB;AACzB,mDAA6B;AAE7B,iEAA6D;AAC7D,mDAAsF;AACtF,6CAAyD;AAEzD,qGAAqG;AACrG,yEAAyE;AACzE,IAAI,gBAAgB,GAAG,KAAK,CAAC;AAE7B,8GAA8G;AAC9G,SAAgB,gCAAgC;IAC5C,gBAAgB,GAAG,KAAK,CAAC;AAC7B,CAAC;AAED;;;;;;GAMG;AACH,mHAAmH;AACnH,SAAgB,aAAa,CAAC,SAAiB,EAAE,aAAqB,EAAE,kBAA0B,EAAE,QAAwB;IACxH,OAAO,CAAC,SAAS,EAAE,aAAa,EAAE,MAAM,CAAC,kBAAkB,CAAC,EAAE,QAAQ,CAAC,SAAS,EAAE,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC,IAAI,CAAC,CAAC;AACvH,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,mOAAmO;AACnO,SAAgB,sBAAsB,CAAC,aAAqB,EAAE,kBAA0B;IACpF,gGAAgG;IAChG,mGAAmG;IACnG,mGAAmG;IACnG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GAAG,CAAC,CAAC;QAC3B,KAAK,KAAK,CAAC;QACX,0EAA0E;IAC9E,CAAC;AACL,CAAC","sourcesContent":["import { spawn } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { logSyncEvent, SyncLogEvent, refresherChildStdioPath } from './main-sync-log';\nimport { logStream, StreamIdentity } from './log-stream';\n\n// Per-process latch for the spawn below. A hook process handles exactly one tool call, so this makes\n// the refresher at-most-once per tool call. Exported reset is test-only.\nlet alreadyTriggered = false;\n\n// webpieces-disable no-function-outside-class -- test-only latch reset, matching this module's function shape\nexport function resetMainSyncRefreshLatchForTest(): void {\n alreadyTriggered = false;\n}\n\n/**\n * The detached child's argv, spawner side. Positions here are offset by two from the child's\n * `process.argv` (node + script path), so this array's 3/4/5 are the child's 4/5/6 — which is what\n * `sync-main.ts:spawnerIdentity` reads. The two are pinned against each other by ONE test, because a\n * silent disagreement about these positions IS the bug being fixed: the child previously received no\n * identity at all and wrote every line to the shared `unknown-coordinator-hook-` stream.\n */\n// webpieces-disable no-function-outside-class -- argv builder for this module's spawn, matching its function shape\nexport function refresherArgv(refresher: string, workspaceRoot: string, hangTimeoutMinutes: number, identity: StreamIdentity): string[] {\n return [refresher, workspaceRoot, String(hangTimeoutMinutes), identity.sessionId, identity.agentId, identity.hook];\n}\n\n/**\n * Fire-and-forget spawn of the detached refresher (sync-main.js in this same dir — spawned by path,\n * not a bin). The child outlives this hook process (`detached` + `unref`), does the slow\n * merged-PR/fetch/merge-base/overlap work, and writes the cache the feature-branch-guard reads on\n * the NEXT call. This is the first detached spawn in the codebase — every existing hook is synchronous.\n *\n * Observability: we log SPAWN_ATTEMPT here and the child logs START/FINISH/ERROR, all to\n * `.webpieces/logs/async-refresh/<writer>.log` (LogStream names every writer). The child's\n * stdout/stderr are redirected to a sibling file (not\n * /dev/null) so a crash before the child's own logging is still captured. If the async-refresh stream shows\n * SPAWN_ATTEMPT but never START, the detached child was killed before it ran.\n *\n * `hangTimeoutMinutes` IS REQUIRED, deliberately. It used to default to DEFAULT_HANG_TIMEOUT_MINUTES,\n * and that default is the mechanism by which three of the four configured values could never reach a\n * spawn: two callers ran before any guard and simply omitted the argument, and the at-most-once latch\n * below then meant the guard's own call — the one carrying the configured value — was a no-op. An\n * omitted argument that silently means \"the default\" is unreadable at the call site and impossible to\n * grep. Required makes every caller say which value it is passing, and makes forgetting a compile error.\n *\n * THE IDENTITY GOES ON ARGV, and that is what makes the sentence above true. The child is a separate\n * node process whose `logStream` starts unidentified, so it used to write every line to the shared\n * `unknown-coordinator-hook.log` while this parent wrote SPAWN_ATTEMPT to its own\n * prefixed stream. One cycle, two files — the SPAWN_ATTEMPT-without-START check then read as a\n * failure on every cycle even when the child ran perfectly — and every agent's child appending to\n * that one shared path is exactly the multi-writer tearing LogStream exists to remove. Passing\n * session/agent/hook through (positional argv, alongside the root and timeout the child already\n * takes) puts the whole cycle back in ONE file.\n */\n// webpieces-disable no-function-outside-class -- the module's one entry point, beside refresherArgv; a detached fire-and-forget spawn has no state to inject and must stay callable from a tree too broken to build a DI container\nexport function triggerMainSyncRefresh(workspaceRoot: string, hangTimeoutMinutes: number): void {\n // ONE refresher per hook process. Several call sites fire this on a single tool call — the Read\n // fast path in hook-core AND read-stale-guard's own check(), for one — which is why the log showed\n // two SPAWN_ATTEMPTs ~20ms apart from the same pid on every cycle. The loser only ever reached the\n // lock and exited, so the second child was pure waste (and one more `git fetch` racing the\n // agent's). The child's lock still guards against refreshers from OTHER hook processes.\n if (alreadyTriggered) return;\n alreadyTriggered = true;\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const refresher = path.join(__dirname, 'sync-main.js');\n // SPAWN_ATTEMPT first — this also creates .webpieces/logs so the stderr fd below can open.\n logSyncEvent(workspaceRoot, new SyncLogEvent('SPAWN_ATTEMPT', process.pid, '-', `refresher=${refresher}`));\n\n // Redirect the detached child's stdout+stderr to a file (not /dev/null) so an uncaught crash\n // before the child's own logging — e.g. a module-load failure — is still captured.\n const errFd = fs.openSync(refresherChildStdioPath(workspaceRoot), 'a');\n const child = spawn(process.execPath, refresherArgv(refresher, workspaceRoot, hangTimeoutMinutes, logStream.identity()), {\n detached: true,\n stdio: ['ignore', errFd, errFd],\n });\n // spawn errors (e.g. ENOENT) arrive asynchronously; record one if it fires. The hook may exit\n // before this handler runs, but on POSIX a successful exec has already happened by now.\n child.once('error', (err: Error): void => {\n logSyncEvent(workspaceRoot, new SyncLogEvent('ERROR', child.pid ?? -1, '-', `spawn failed: ${err.message}`));\n });\n child.unref();\n // The child has its own dup'd copy of the fd after spawn; close the parent's copy.\n fs.closeSync(errFd);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n // Spawning the background refresh must never block or fail the tool call.\n }\n}\n"]}
@@ -0,0 +1,33 @@
1
+ import { WebpiecesRulesConfig } from '@webpieces/rules-config';
2
+ import { BranchStateGuardConfig } from "../configs/main-sync-guard-configs";
3
+ import type { Rule } from '@webpieces/hook-runtime';
4
+ /**
5
+ * The value on a branch-state ENTRY, or the default — for the four guard classes, which are handed
6
+ * their own typed config and never see the whole file.
7
+ *
8
+ * The four used to spell this inline as `this.config.hangTimeoutMinutes ?? DEFAULT_HANG_TIMEOUT_MINUTES`,
9
+ * which is a fourth copy of the resolution and exactly the shape that let the four DECLARATIONS drift
10
+ * apart in the first place. One reader, one fallback.
11
+ */
12
+ export declare function hangTimeoutOf(config: BranchStateGuardConfig): number;
13
+ /** The configured value for a caller that has ALREADY loaded the whole config. */
14
+ export declare function branchStateHangTimeout(config: WebpiecesRulesConfig): number;
15
+ /**
16
+ * The configured value for a caller that has NOT loaded the config — the hook adapter's two pre-rule
17
+ * refresh triggers (the webpieces.config.json edit bypass, and the Read fast path).
18
+ *
19
+ * Fails back to the default on an unloadable config: warming a cache must never throw on the tool path.
20
+ */
21
+ export declare function branchStateHangTimeoutFor(cwd: string): number;
22
+ /** Test-only: clears the per-process memo above. */
23
+ export declare function resetHangTimeoutCacheForTest(): void;
24
+ /**
25
+ * Fire-and-forget the detached refresher when the branch-state policy is loaded and active, so the
26
+ * cache stays fresh as the AI works. The guard rules themselves also trigger it; this covers the Bash
27
+ * path so the cache is warm on every command.
28
+ *
29
+ * Keyed on `feature-branch-guard` — the rule NAME, not the config key. Any of the four branch-state
30
+ * classes would do (they share one entry, so they are on or off together); this one is asked because it
31
+ * is the class whose cache freshness matters on the very next Write.
32
+ */
33
+ export declare function maybeRefreshMainSync(rules: readonly Rule[], workspaceRoot: string, hangTimeoutMinutes: number): void;
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.hangTimeoutOf = hangTimeoutOf;
4
+ exports.branchStateHangTimeout = branchStateHangTimeout;
5
+ exports.branchStateHangTimeoutFor = branchStateHangTimeoutFor;
6
+ exports.resetHangTimeoutCacheForTest = resetHangTimeoutCacheForTest;
7
+ exports.maybeRefreshMainSync = maybeRefreshMainSync;
8
+ const rules_config_1 = require("@webpieces/rules-config");
9
+ const policy_keys_1 = require("../policy-keys");
10
+ const repo_workflow_core_1 = require("@webpieces/repo-workflow-core");
11
+ const to_error_1 = require("@webpieces/tooling-common/to-error");
12
+ const main_sync_refresh_1 = require("./main-sync-refresh");
13
+ // ---------------------------------------------------------------------------
14
+ // THE ONE `hangTimeoutMinutes`, and every caller that has to read it.
15
+ //
16
+ // There is ONE detached refresher writing ONE cache (.webpieces/main-sync-status.json), so there is one
17
+ // knob: `hookGuards.branch-state-guard.hangTimeoutMinutes`, which tunes the stale-lock reclaim window.
18
+ //
19
+ // It used to be declared FOUR times — once per branch-state guard class — and read four times, and
20
+ // three of those four values were structurally unable to take effect. Two things conspired:
21
+ // `triggerMainSyncRefresh` latches at most one spawn per hook process, and two callers ran BEFORE any
22
+ // guard's own call while passing the hardcoded default. So on the Bash path and the Read path (the two
23
+ // hottest) the default always won the latch and the configured value never reached a spawn.
24
+ //
25
+ // Collapsing four declarations into one only fixes that if EVERY caller reads the one. This module is
26
+ // where they do, which is also why it is a module rather than three helpers in runner.ts: the callers
27
+ // live in two files (the runner and the hook adapter) and a knob honoured in one of them is the bug
28
+ // again, one release later.
29
+ // ---------------------------------------------------------------------------
30
+ /**
31
+ * The value on a branch-state ENTRY, or the default — for the four guard classes, which are handed
32
+ * their own typed config and never see the whole file.
33
+ *
34
+ * The four used to spell this inline as `this.config.hangTimeoutMinutes ?? DEFAULT_HANG_TIMEOUT_MINUTES`,
35
+ * which is a fourth copy of the resolution and exactly the shape that let the four DECLARATIONS drift
36
+ * apart in the first place. One reader, one fallback.
37
+ */
38
+ // webpieces-disable no-function-outside-class -- module-scope config accessor, matching the shape of the runner helpers it was extracted from
39
+ function hangTimeoutOf(config) {
40
+ const configured = config.hangTimeoutMinutes;
41
+ return typeof configured === 'number' ? configured : repo_workflow_core_1.DEFAULT_HANG_TIMEOUT_MINUTES;
42
+ }
43
+ /** The configured value for a caller that has ALREADY loaded the whole config. */
44
+ // webpieces-disable no-function-outside-class -- module-scope config accessor, matching the shape of the runner helpers it was extracted from
45
+ function branchStateHangTimeout(config) {
46
+ const entry = config[policy_keys_1.BRANCH_STATE_GUARD_KEY];
47
+ return entry === undefined ? repo_workflow_core_1.DEFAULT_HANG_TIMEOUT_MINUTES : hangTimeoutOf(entry);
48
+ }
49
+ // Memoized per PROCESS, and a hook process handles exactly one tool call — so the adapter's two call
50
+ // sites cost at most one extra config parse between them, never one each.
51
+ let cachedHangTimeout = null;
52
+ /**
53
+ * The configured value for a caller that has NOT loaded the config — the hook adapter's two pre-rule
54
+ * refresh triggers (the webpieces.config.json edit bypass, and the Read fast path).
55
+ *
56
+ * Fails back to the default on an unloadable config: warming a cache must never throw on the tool path.
57
+ */
58
+ // webpieces-disable no-function-outside-class -- module-scope config accessor, matching the shape of the runner helpers it was extracted from
59
+ function branchStateHangTimeoutFor(cwd) {
60
+ if (cachedHangTimeout !== null)
61
+ return cachedHangTimeout;
62
+ let value = repo_workflow_core_1.DEFAULT_HANG_TIMEOUT_MINUTES;
63
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- a cache-warming knob must never throw on the tool path
64
+ try {
65
+ value = branchStateHangTimeout((0, rules_config_1.loadAndValidate)(cwd).rulesConfig);
66
+ }
67
+ catch (err) {
68
+ const error = (0, to_error_1.toError)(err);
69
+ void error;
70
+ }
71
+ cachedHangTimeout = value;
72
+ return value;
73
+ }
74
+ /** Test-only: clears the per-process memo above. */
75
+ // webpieces-disable no-function-outside-class -- module-scope test hook beside the memo it clears
76
+ function resetHangTimeoutCacheForTest() {
77
+ cachedHangTimeout = null;
78
+ }
79
+ /**
80
+ * Fire-and-forget the detached refresher when the branch-state policy is loaded and active, so the
81
+ * cache stays fresh as the AI works. The guard rules themselves also trigger it; this covers the Bash
82
+ * path so the cache is warm on every command.
83
+ *
84
+ * Keyed on `feature-branch-guard` — the rule NAME, not the config key. Any of the four branch-state
85
+ * classes would do (they share one entry, so they are on or off together); this one is asked because it
86
+ * is the class whose cache freshness matters on the very next Write.
87
+ */
88
+ // webpieces-disable no-function-outside-class -- module-scope refresh trigger, matching the shape of the runner helpers it was extracted from
89
+ function maybeRefreshMainSync(rules, workspaceRoot, hangTimeoutMinutes) {
90
+ const guard = rules.find((r) => r.name === 'feature-branch-guard');
91
+ if (guard && guard.shouldRun()) {
92
+ (0, main_sync_refresh_1.triggerMainSyncRefresh)(workspaceRoot, hangTimeoutMinutes);
93
+ }
94
+ }
95
+ //# sourceMappingURL=main-sync-timeout.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"main-sync-timeout.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/core/main-sync-timeout.ts"],"names":[],"mappings":";;AAoCA,sCAGC;AAID,wDAGC;AAaD,8DAYC;AAID,oEAEC;AAYD,oDAKC;AA9FD,0DAAgF;AAChF,gDAAwD;AAExD,sEAA6E;AAE7E,iEAA6D;AAC7D,2DAA6D;AAG7D,8EAA8E;AAC9E,sEAAsE;AACtE,EAAE;AAC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AACpD,kGAAkG;AAClG,SAAgB,4BAA4B;IACxC,iBAAiB,GAAG,IAAI,CAAC;AAC7B,CAAC;AAED;;;;;;;;GAQG;AACH,8IAA8I;AAC9I,SAAgB,oBAAoB,CAAC,KAAsB,EAAE,aAAqB,EAAE,kBAA0B;IAC1G,MAAM,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC,CAAO,EAAW,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,sBAAsB,CAAC,CAAC;IAClF,IAAI,KAAK,IAAI,KAAK,CAAC,SAAS,EAAE,EAAE,CAAC;QAC7B,IAAA,0CAAsB,EAAC,aAAa,EAAE,kBAAkB,CAAC,CAAC;IAC9D,CAAC;AACL,CAAC","sourcesContent":["import { loadAndValidate, WebpiecesRulesConfig } from '@webpieces/rules-config';\nimport { BRANCH_STATE_GUARD_KEY } from '../policy-keys';\nimport { BranchStateGuardConfig } from \"../configs/main-sync-guard-configs\";\nimport { DEFAULT_HANG_TIMEOUT_MINUTES } from '@webpieces/repo-workflow-core';\n\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { triggerMainSyncRefresh } from './main-sync-refresh';\nimport type { Rule } from '@webpieces/hook-runtime';\n\n// ---------------------------------------------------------------------------\n// THE ONE `hangTimeoutMinutes`, and every caller that has to read it.\n//\n// There is ONE detached refresher writing ONE cache (.webpieces/main-sync-status.json), so there is one\n// knob: `hookGuards.branch-state-guard.hangTimeoutMinutes`, which tunes the stale-lock reclaim window.\n//\n// It used to be declared FOUR times — once per branch-state guard class — and read four times, and\n// three of those four values were structurally unable to take effect. Two things conspired:\n// `triggerMainSyncRefresh` latches at most one spawn per hook process, and two callers ran BEFORE any\n// guard's own call while passing the hardcoded default. So on the Bash path and the Read path (the two\n// hottest) the default always won the latch and the configured value never reached a spawn.\n//\n// Collapsing four declarations into one only fixes that if EVERY caller reads the one. This module is\n// where they do, which is also why it is a module rather than three helpers in runner.ts: the callers\n// live in two files (the runner and the hook adapter) and a knob honoured in one of them is the bug\n// again, one release later.\n// ---------------------------------------------------------------------------\n\n/**\n * The value on a branch-state ENTRY, or the default — for the four guard classes, which are handed\n * their own typed config and never see the whole file.\n *\n * The four used to spell this inline as `this.config.hangTimeoutMinutes ?? DEFAULT_HANG_TIMEOUT_MINUTES`,\n * which is a fourth copy of the resolution and exactly the shape that let the four DECLARATIONS drift\n * apart in the first place. One reader, one fallback.\n */\n// webpieces-disable no-function-outside-class -- module-scope config accessor, matching the shape of the runner helpers it was extracted from\nexport function hangTimeoutOf(config: BranchStateGuardConfig): number {\n const configured = config.hangTimeoutMinutes;\n return typeof configured === 'number' ? configured : DEFAULT_HANG_TIMEOUT_MINUTES;\n}\n\n/** The configured value for a caller that has ALREADY loaded the whole config. */\n// webpieces-disable no-function-outside-class -- module-scope config accessor, matching the shape of the runner helpers it was extracted from\nexport function branchStateHangTimeout(config: WebpiecesRulesConfig): number {\n const entry = config[BRANCH_STATE_GUARD_KEY] as BranchStateGuardConfig | undefined;\n return entry === undefined ? DEFAULT_HANG_TIMEOUT_MINUTES : hangTimeoutOf(entry);\n}\n\n// Memoized per PROCESS, and a hook process handles exactly one tool call — so the adapter's two call\n// sites cost at most one extra config parse between them, never one each.\nlet cachedHangTimeout: number | null = null;\n\n/**\n * The configured value for a caller that has NOT loaded the config — the hook adapter's two pre-rule\n * refresh triggers (the webpieces.config.json edit bypass, and the Read fast path).\n *\n * Fails back to the default on an unloadable config: warming a cache must never throw on the tool path.\n */\n// webpieces-disable no-function-outside-class -- module-scope config accessor, matching the shape of the runner helpers it was extracted from\nexport function branchStateHangTimeoutFor(cwd: string): number {\n if (cachedHangTimeout !== null) return cachedHangTimeout;\n let value = DEFAULT_HANG_TIMEOUT_MINUTES;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- a cache-warming knob must never throw on the tool path\n try {\n value = branchStateHangTimeout(loadAndValidate(cwd).rulesConfig);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n }\n cachedHangTimeout = value;\n return value;\n}\n\n/** Test-only: clears the per-process memo above. */\n// webpieces-disable no-function-outside-class -- module-scope test hook beside the memo it clears\nexport function resetHangTimeoutCacheForTest(): void {\n cachedHangTimeout = null;\n}\n\n/**\n * Fire-and-forget the detached refresher when the branch-state policy is loaded and active, so the\n * cache stays fresh as the AI works. The guard rules themselves also trigger it; this covers the Bash\n * path so the cache is warm on every command.\n *\n * Keyed on `feature-branch-guard` — the rule NAME, not the config key. Any of the four branch-state\n * classes would do (they share one entry, so they are on or off together); this one is asked because it\n * is the class whose cache freshness matters on the very next Write.\n */\n// webpieces-disable no-function-outside-class -- module-scope refresh trigger, matching the shape of the runner helpers it was extracted from\nexport function maybeRefreshMainSync(rules: readonly Rule[], workspaceRoot: string, hangTimeoutMinutes: number): void {\n const guard = rules.find((r: Rule): boolean => r.name === 'feature-branch-guard');\n if (guard && guard.shouldRun()) {\n triggerMainSyncRefresh(workspaceRoot, hangTimeoutMinutes);\n }\n}\n"]}
@@ -0,0 +1,12 @@
1
+ /** What a row with no cure — every ALLOW row, and every layer this module does not own — logs. */
2
+ export declare const NO_CURE = "-";
3
+ /**
4
+ * The literal cure for a layer+row, for the log line. `-` when the row allows, or when the layer is
5
+ * not one this module owns.
6
+ *
7
+ * Markdown backticks are stripped: the doc is read by a human in a renderer, the log is read through
8
+ * `grep`, and a cure you cannot grep for without escaping the fence characters is a cure the trail
9
+ * cannot be searched by. The words are otherwise untouched, so the log and the doc stay comparable
10
+ * literal-for-literal, which is the point of deriving one from the other.
11
+ */
12
+ export declare function cureForMatrix(layer: string, row: string): string;
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NO_CURE = void 0;
4
+ exports.cureForMatrix = cureForMatrix;
5
+ const l1_rows_1 = require("./l1-rows");
6
+ const l2_rows_1 = require("./l2-rows");
7
+ // ---------------------------------------------------------------------------
8
+ // THE CURE, as a log field — the other half of `row=`.
9
+ //
10
+ // `row=` already joined a decision-log line to a row in the generated matrix. What it could not tell
11
+ // you is what the agent was actually TOLD to do, and that is the half you need to audit the table:
12
+ // a row whose cure keeps appearing in the trail next to a session that then did something else is a
13
+ // row whose use cases need updating. Reading the doc tells you what the cure IS; reading the log used
14
+ // to tell you only that some row fired.
15
+ //
16
+ // THE ONE DESIGN DECISION HERE: the cure is LOOKED UP from the row, never passed in by the caller.
17
+ //
18
+ // A `cure` field on GuardDecision would have been the obvious move and is the wrong one. It would let
19
+ // the logged cure and the printed cure drift — two spellings of one thing, which is the shim shape
20
+ // this repo rejects — and it would have to be threaded through every construction site, so the cheap
21
+ // path would be to pass '' and the field would rot. Deriving it from `decision.matrix` means the
22
+ // logged cure is BY CONSTRUCTION the same literal the generated doc prints for that row, and no call
23
+ // site changes at all.
24
+ //
25
+ // Both layers are covered because both stamp a MatrixRef: L1 dispatches from L1_ROWS, L2 joins by
26
+ // reason. L0's cures are a different shape (L0Cure carries mention + discriminator + guidance, and
27
+ // the sh shim prints them itself), so L0 rows resolve to '-' here rather than being half-rendered.
28
+ // ---------------------------------------------------------------------------
29
+ /** What a row with no cure — every ALLOW row, and every layer this module does not own — logs. */
30
+ exports.NO_CURE = '-';
31
+ /**
32
+ * The literal cure for a layer+row, for the log line. `-` when the row allows, or when the layer is
33
+ * not one this module owns.
34
+ *
35
+ * Markdown backticks are stripped: the doc is read by a human in a renderer, the log is read through
36
+ * `grep`, and a cure you cannot grep for without escaping the fence characters is a cure the trail
37
+ * cannot be searched by. The words are otherwise untouched, so the log and the doc stay comparable
38
+ * literal-for-literal, which is the point of deriving one from the other.
39
+ */
40
+ // webpieces-disable no-function-outside-class -- the pure lookup this module exists to be, over the two row arrays it imports
41
+ function cureForMatrix(layer, row) {
42
+ if (layer === 'L2')
43
+ return cureOf(l2_rows_1.L2_ROWS.find((r) => String(r.num) === row)?.cure);
44
+ if (layer === 'L1')
45
+ return cureOf(l1_rows_1.L1_ROWS.find((r) => String(r.num) === row)?.cure?.denyMention);
46
+ return exports.NO_CURE;
47
+ }
48
+ // An allow row's cure cell is the em-dash the doc prints; in a log field that is noise, so it becomes
49
+ // the same `-` an unknown row gets. The distinction a reader needs is carried by `verdict`, not here.
50
+ // webpieces-disable no-function-outside-class -- private normalizer for cureForMatrix above, beside it in this module
51
+ function cureOf(cure) {
52
+ if (cure === undefined || cure === '' || cure === '—')
53
+ return exports.NO_CURE;
54
+ return cure.replace(/`/g, '');
55
+ }
56
+ //# sourceMappingURL=matrix-cures.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"matrix-cures.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/core/matrix-cures.ts"],"names":[],"mappings":";;;AAuCA,sCAIC;AA3CD,uCAA2C;AAC3C,uCAA2C;AAE3C,8EAA8E;AAC9E,uDAAuD;AACvD,EAAE;AACF,qGAAqG;AACrG,mGAAmG;AACnG,oGAAoG;AACpG,sGAAsG;AACtG,wCAAwC;AACxC,EAAE;AACF,mGAAmG;AACnG,EAAE;AACF,sGAAsG;AACtG,mGAAmG;AACnG,qGAAqG;AACrG,iGAAiG;AACjG,qGAAqG;AACrG,uBAAuB;AACvB,EAAE;AACF,kGAAkG;AAClG,mGAAmG;AACnG,mGAAmG;AACnG,8EAA8E;AAE9E,kGAAkG;AACrF,QAAA,OAAO,GAAG,GAAG,CAAC;AAE3B;;;;;;;;GAQG;AACH,8HAA8H;AAC9H,SAAgB,aAAa,CAAC,KAAa,EAAE,GAAW;IACpD,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,MAAM,CAAC,iBAAO,CAAC,IAAI,CAAC,CAAC,CAAQ,EAAW,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,GAAG,CAAC,EAAE,IAAI,CAAC,CAAC;IACpG,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,MAAM,CAAC,iBAAO,CAAC,IAAI,CAAC,CAAC,CAAQ,EAAW,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,GAAG,CAAC,EAAE,IAAI,EAAE,WAAW,CAAC,CAAC;IACjH,OAAO,eAAO,CAAC;AACnB,CAAC;AAED,sGAAsG;AACtG,sGAAsG;AACtG,sHAAsH;AACtH,SAAS,MAAM,CAAC,IAAwB;IACpC,IAAI,IAAI,KAAK,SAAS,IAAI,IAAI,KAAK,EAAE,IAAI,IAAI,KAAK,GAAG;QAAE,OAAO,eAAO,CAAC;IACtE,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;AAClC,CAAC","sourcesContent":["import { L1_ROWS, L1Row } from './l1-rows';\nimport { L2_ROWS, L2Row } from './l2-rows';\n\n// ---------------------------------------------------------------------------\n// THE CURE, as a log field — the other half of `row=`.\n//\n// `row=` already joined a decision-log line to a row in the generated matrix. What it could not tell\n// you is what the agent was actually TOLD to do, and that is the half you need to audit the table:\n// a row whose cure keeps appearing in the trail next to a session that then did something else is a\n// row whose use cases need updating. Reading the doc tells you what the cure IS; reading the log used\n// to tell you only that some row fired.\n//\n// THE ONE DESIGN DECISION HERE: the cure is LOOKED UP from the row, never passed in by the caller.\n//\n// A `cure` field on GuardDecision would have been the obvious move and is the wrong one. It would let\n// the logged cure and the printed cure drift — two spellings of one thing, which is the shim shape\n// this repo rejects — and it would have to be threaded through every construction site, so the cheap\n// path would be to pass '' and the field would rot. Deriving it from `decision.matrix` means the\n// logged cure is BY CONSTRUCTION the same literal the generated doc prints for that row, and no call\n// site changes at all.\n//\n// Both layers are covered because both stamp a MatrixRef: L1 dispatches from L1_ROWS, L2 joins by\n// reason. L0's cures are a different shape (L0Cure carries mention + discriminator + guidance, and\n// the sh shim prints them itself), so L0 rows resolve to '-' here rather than being half-rendered.\n// ---------------------------------------------------------------------------\n\n/** What a row with no cure — every ALLOW row, and every layer this module does not own — logs. */\nexport const NO_CURE = '-';\n\n/**\n * The literal cure for a layer+row, for the log line. `-` when the row allows, or when the layer is\n * not one this module owns.\n *\n * Markdown backticks are stripped: the doc is read by a human in a renderer, the log is read through\n * `grep`, and a cure you cannot grep for without escaping the fence characters is a cure the trail\n * cannot be searched by. The words are otherwise untouched, so the log and the doc stay comparable\n * literal-for-literal, which is the point of deriving one from the other.\n */\n// webpieces-disable no-function-outside-class -- the pure lookup this module exists to be, over the two row arrays it imports\nexport function cureForMatrix(layer: string, row: string): string {\n if (layer === 'L2') return cureOf(L2_ROWS.find((r: L2Row): boolean => String(r.num) === row)?.cure);\n if (layer === 'L1') return cureOf(L1_ROWS.find((r: L1Row): boolean => String(r.num) === row)?.cure?.denyMention);\n return NO_CURE;\n}\n\n// An allow row's cure cell is the em-dash the doc prints; in a log field that is noise, so it becomes\n// the same `-` an unknown row gets. The distinction a reader needs is carried by `verdict`, not here.\n// webpieces-disable no-function-outside-class -- private normalizer for cureForMatrix above, beside it in this module\nfunction cureOf(cure: string | undefined): string {\n if (cure === undefined || cure === '' || cure === '—') return NO_CURE;\n return cure.replace(/`/g, '');\n}\n"]}
@@ -0,0 +1,38 @@
1
+ import { EffectiveTree } from '@webpieces/hook-runtime';
2
+ import { BlockedResult } from '@webpieces/hook-runtime';
3
+ /**
4
+ * L1: the directory this command would run in DOES NOT EXIST.
5
+ *
6
+ * THE INCIDENT (reproduced from a transcript, 0.4.603). A subagent was launched with its cwd inside
7
+ * `<root>/.claude/worktrees/agent-a5931637c5bff6d6d`. Mid-session another agent's cleanup REAPED that
8
+ * worktree. The shell's cwd still named a path that was now gone.
9
+ *
10
+ * `classify()` asked git for the toplevel, got `null` — and `null` meant two completely different
11
+ * things: "this is not a git directory" and "this directory does not exist". Conflating them classified
12
+ * the dead path as the PRIMARY clone, so force-to-root fired and printed:
13
+ *
14
+ * ❌ Run git/gh commands from the repo root, not a subdirectory.
15
+ * Command runs in: <root>/.claude/worktrees/agent-a5931637c5bff6d6d
16
+ * Judged against: <root>
17
+ * cd '<root>' && cd <root>/.claude/worktrees/agent-… && git fetch …
18
+ *
19
+ * Three things wrong at once: the diagnosis (it is not a subdirectory, it is GONE), the tone (it reads
20
+ * as a scolding for a mistake nobody made), and the remedy (it ends inside the deleted directory, so it
21
+ * cannot satisfy the check — the retry re-fires with the prefix doubled, then tripled). Three rounds
22
+ * were burned before `git worktree list` made the real state visible.
23
+ *
24
+ * So the fix is a DISTINCT tree kind with its own message. Naming the state is most of the cure: an
25
+ * agent that is told the directory is gone stops trying to `cd` into it. The remedy deliberately routes
26
+ * through the governed root and drops the command's own leading `cd`, so it can never point back at the
27
+ * dead path — the same convergence property `remedyAtRoot` gives force-to-root.
28
+ *
29
+ * The lost-work line is not padding. A reaped worktree takes uncommitted changes with it, and an agent
30
+ * that silently retries at the root will otherwise report success on work that no longer exists.
31
+ */
32
+ export declare class MissingDirectoryGuard {
33
+ private readonly resolver;
34
+ /** The deny report, or null to allow. */
35
+ block(command: string, tree: EffectiveTree): string | null;
36
+ private report;
37
+ }
38
+ export declare function missingDirectoryBlock(command: string, tree: EffectiveTree): BlockedResult | null;
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MissingDirectoryGuard = void 0;
4
+ exports.missingDirectoryBlock = missingDirectoryBlock;
5
+ const hook_runtime_1 = require("@webpieces/hook-runtime");
6
+ const hook_runtime_2 = require("@webpieces/hook-runtime");
7
+ /**
8
+ * L1: the directory this command would run in DOES NOT EXIST.
9
+ *
10
+ * THE INCIDENT (reproduced from a transcript, 0.4.603). A subagent was launched with its cwd inside
11
+ * `<root>/.claude/worktrees/agent-a5931637c5bff6d6d`. Mid-session another agent's cleanup REAPED that
12
+ * worktree. The shell's cwd still named a path that was now gone.
13
+ *
14
+ * `classify()` asked git for the toplevel, got `null` — and `null` meant two completely different
15
+ * things: "this is not a git directory" and "this directory does not exist". Conflating them classified
16
+ * the dead path as the PRIMARY clone, so force-to-root fired and printed:
17
+ *
18
+ * ❌ Run git/gh commands from the repo root, not a subdirectory.
19
+ * Command runs in: <root>/.claude/worktrees/agent-a5931637c5bff6d6d
20
+ * Judged against: <root>
21
+ * cd '<root>' && cd <root>/.claude/worktrees/agent-… && git fetch …
22
+ *
23
+ * Three things wrong at once: the diagnosis (it is not a subdirectory, it is GONE), the tone (it reads
24
+ * as a scolding for a mistake nobody made), and the remedy (it ends inside the deleted directory, so it
25
+ * cannot satisfy the check — the retry re-fires with the prefix doubled, then tripled). Three rounds
26
+ * were burned before `git worktree list` made the real state visible.
27
+ *
28
+ * So the fix is a DISTINCT tree kind with its own message. Naming the state is most of the cure: an
29
+ * agent that is told the directory is gone stops trying to `cd` into it. The remedy deliberately routes
30
+ * through the governed root and drops the command's own leading `cd`, so it can never point back at the
31
+ * dead path — the same convergence property `remedyAtRoot` gives force-to-root.
32
+ *
33
+ * The lost-work line is not padding. A reaped worktree takes uncommitted changes with it, and an agent
34
+ * that silently retries at the root will otherwise report success on work that no longer exists.
35
+ */
36
+ class MissingDirectoryGuard {
37
+ resolver = new hook_runtime_1.EffectiveTreeResolver();
38
+ /** The deny report, or null to allow. */
39
+ block(command, tree) {
40
+ if (tree.kind !== 'missing')
41
+ return null;
42
+ return this.report(command, tree);
43
+ }
44
+ // Short, on the L0 message diet: name the state, say what it costs, give ONE runnable line.
45
+ report(command, tree) {
46
+ return [
47
+ `❌ The directory this command would run in no longer exists:`,
48
+ ` ${tree.effectiveCwd}`,
49
+ ' Most often it was a linked worktree that has since been reaped (`git worktree list` no',
50
+ ' longer shows it). Nothing can run there, and any UNCOMMITTED work that was in it is gone.',
51
+ '',
52
+ ` Continue from ${tree.governedRoot} — this line does NOT route back through the dead path:`,
53
+ ` ${this.resolver.remedyAtRoot(tree.governedRoot, command)}`,
54
+ ].join('\n');
55
+ }
56
+ }
57
+ exports.MissingDirectoryGuard = MissingDirectoryGuard;
58
+ // L1 row 7's dispatch entry. It lives HERE rather than beside its two siblings in runner.ts because
59
+ // the guard owns its own report and runner.ts is at its file-size cap — the runner needs only the row
60
+ // lookup and this one call.
61
+ // webpieces-disable no-function-outside-class -- the one-line runner entry point for the class above, beside it
62
+ function missingDirectoryBlock(command, tree) {
63
+ const report = new MissingDirectoryGuard().block(command, tree);
64
+ return report === null ? null : new hook_runtime_2.BlockedResult(report);
65
+ }
66
+ //# sourceMappingURL=missing-directory.js.map