@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,44 @@
1
+ /**
2
+ * HOW MANY TIMES has this session already run this exact Bash command?
3
+ *
4
+ * ─── Why a guard is allowed to ask a question about HISTORY at all ─────────────────────────────────
5
+ * Every other guard here answers from the command TEXT plus the tree's git state, and `managed-env.ts`
6
+ * states that preference out loud: same command, same verdict, every time. That rule exists so a
7
+ * verdict cannot depend on where an unrelated earlier command left the shell — an accident.
8
+ *
9
+ * A SPIN is not an accident, and it is not visible in one command. `gh pr checks 874` asked once is a
10
+ * snapshot somebody acts on; asked for the ninetieth time in four minutes it is the wait loop this
11
+ * whole feature exists to delete, and the two are byte-identical. Repetition IS the defect, so
12
+ * repetition is the only thing that can be measured. Nothing else about the call differs.
13
+ *
14
+ * ─── Where the count comes from ────────────────────────────────────────────────────────────────────
15
+ * `InvocationLog` already writes ONE tab-separated line per guards-hook call to
16
+ * `<state>/logs/calls/<sessionId>-<agentId|coordinator>-<hook>.log`, and `logStream` has already been
17
+ * identified with this session and agent by the time a rule's `check()` runs. So the file IS the
18
+ * session, for free — no new state, no new writer, and a worktree-isolated subagent gets its own
19
+ * because the path is resolved from the tree it acts on.
20
+ *
21
+ * Each tool call is its own process and flushes that line at its terminal boundary, so on call N the
22
+ * file holds calls 1..N-1. The count this returns is therefore PRIOR calls, never including the one
23
+ * being judged.
24
+ *
25
+ * ─── It fails OPEN, always ─────────────────────────────────────────────────────────────────────────
26
+ * A missing file (the first call of a session), a rotated one, an unreadable one — all of them mean
27
+ * "no evidence", which is 0, which blocks nothing. A logging failure may never become a refusal.
28
+ */
29
+ export declare class SessionCallHistory {
30
+ /**
31
+ * How many times `command` already appears as a Bash target in THIS session's call log.
32
+ *
33
+ * The comparison is against the same one-line normalization `InvocationLog` writes, so a command
34
+ * spanning two lines in the payload and the same command on one line count as the same command.
35
+ */
36
+ priorBashCalls(root: string, command: string): number;
37
+ /**
38
+ * One logged call is `[<iso>]\tBash\t<target>\tbranch=…` — so field 1 is the tool and field 2 the
39
+ * command. Split rather than `includes`, because a command that MENTIONS another command in its
40
+ * text would otherwise count as that command.
41
+ */
42
+ private isBashCallOf;
43
+ private lines;
44
+ }
@@ -0,0 +1,79 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SessionCallHistory = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const fs = tslib_1.__importStar(require("fs"));
6
+ const tooling_common_1 = require("@webpieces/tooling-common");
7
+ const log_streams_1 = require("./log-streams");
8
+ const log_stream_1 = require("./log-stream");
9
+ const log_target_1 = require("./log-target");
10
+ const to_error_1 = require("@webpieces/tooling-common/to-error");
11
+ /**
12
+ * HOW MANY TIMES has this session already run this exact Bash command?
13
+ *
14
+ * ─── Why a guard is allowed to ask a question about HISTORY at all ─────────────────────────────────
15
+ * Every other guard here answers from the command TEXT plus the tree's git state, and `managed-env.ts`
16
+ * states that preference out loud: same command, same verdict, every time. That rule exists so a
17
+ * verdict cannot depend on where an unrelated earlier command left the shell — an accident.
18
+ *
19
+ * A SPIN is not an accident, and it is not visible in one command. `gh pr checks 874` asked once is a
20
+ * snapshot somebody acts on; asked for the ninetieth time in four minutes it is the wait loop this
21
+ * whole feature exists to delete, and the two are byte-identical. Repetition IS the defect, so
22
+ * repetition is the only thing that can be measured. Nothing else about the call differs.
23
+ *
24
+ * ─── Where the count comes from ────────────────────────────────────────────────────────────────────
25
+ * `InvocationLog` already writes ONE tab-separated line per guards-hook call to
26
+ * `<state>/logs/calls/<sessionId>-<agentId|coordinator>-<hook>.log`, and `logStream` has already been
27
+ * identified with this session and agent by the time a rule's `check()` runs. So the file IS the
28
+ * session, for free — no new state, no new writer, and a worktree-isolated subagent gets its own
29
+ * because the path is resolved from the tree it acts on.
30
+ *
31
+ * Each tool call is its own process and flushes that line at its terminal boundary, so on call N the
32
+ * file holds calls 1..N-1. The count this returns is therefore PRIOR calls, never including the one
33
+ * being judged.
34
+ *
35
+ * ─── It fails OPEN, always ─────────────────────────────────────────────────────────────────────────
36
+ * A missing file (the first call of a session), a rotated one, an unreadable one — all of them mean
37
+ * "no evidence", which is 0, which blocks nothing. A logging failure may never become a refusal.
38
+ */
39
+ class SessionCallHistory {
40
+ /**
41
+ * How many times `command` already appears as a Bash target in THIS session's call log.
42
+ *
43
+ * The comparison is against the same one-line normalization `InvocationLog` writes, so a command
44
+ * spanning two lines in the payload and the same command on one line count as the same command.
45
+ */
46
+ priorBashCalls(root, command) {
47
+ const wanted = log_target_1.logTarget.oneLine(command);
48
+ if (wanted === '')
49
+ return 0;
50
+ return this.lines(root).filter((line) => this.isBashCallOf(line, wanted)).length;
51
+ }
52
+ /**
53
+ * One logged call is `[<iso>]\tBash\t<target>\tbranch=…` — so field 1 is the tool and field 2 the
54
+ * command. Split rather than `includes`, because a command that MENTIONS another command in its
55
+ * text would otherwise count as that command.
56
+ */
57
+ isBashCallOf(line, wanted) {
58
+ const fields = line.split('\t');
59
+ return fields.length > 2 && fields[1] === 'Bash' && fields[2] === wanted;
60
+ }
61
+ lines(root) {
62
+ // webpieces-disable no-unmanaged-exceptions -- a log that cannot be read is NO EVIDENCE, which
63
+ // is the fail-open answer; a logging failure must never become a refusal
64
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
65
+ try {
66
+ const file = tooling_common_1.dotWebpieces.logsFile(root, log_streams_1.CALLS_STREAM, log_stream_1.logStream.writerFile('.log'));
67
+ if (!fs.existsSync(file))
68
+ return [];
69
+ return fs.readFileSync(file, 'utf8').split('\n');
70
+ }
71
+ catch (err) {
72
+ const error = (0, to_error_1.toError)(err);
73
+ void error;
74
+ return [];
75
+ }
76
+ }
77
+ }
78
+ exports.SessionCallHistory = SessionCallHistory;
79
+ //# sourceMappingURL=session-call-history.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-call-history.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/core/session-call-history.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AAEzB,8DAAyD;AAEzD,+CAA6C;AAC7C,6CAAyC;AACzC,6CAAyC;AACzC,iEAA6D;AAE7D;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,MAAa,kBAAkB;IAC3B;;;;;OAKG;IACH,cAAc,CAAC,IAAY,EAAE,OAAe;QACxC,MAAM,MAAM,GAAG,sBAAS,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;QAC1C,IAAI,MAAM,KAAK,EAAE;YAAE,OAAO,CAAC,CAAC;QAC5B,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,IAAY,EAAW,EAAE,CAAC,IAAI,CAAC,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC;IACtG,CAAC;IAED;;;;OAIG;IACK,YAAY,CAAC,IAAY,EAAE,MAAc;QAC7C,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAChC,OAAO,MAAM,CAAC,MAAM,GAAG,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,KAAK,MAAM,IAAI,MAAM,CAAC,CAAC,CAAC,KAAK,MAAM,CAAC;IAC7E,CAAC;IAEO,KAAK,CAAC,IAAY;QACtB,+FAA+F;QAC/F,yEAAyE;QACzE,8DAA8D;QAC9D,IAAI,CAAC;YACD,MAAM,IAAI,GAAG,6BAAY,CAAC,QAAQ,CAAC,IAAI,EAAE,0BAAY,EAAE,sBAAS,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC;YACrF,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC;gBAAE,OAAO,EAAE,CAAC;YACpC,OAAO,EAAE,CAAC,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QACrD,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,KAAK,KAAK,CAAC;YACX,OAAO,EAAE,CAAC;QACd,CAAC;IACL,CAAC;CACJ;AArCD,gDAqCC","sourcesContent":["import * as fs from 'fs';\n\nimport { dotWebpieces } from '@webpieces/tooling-common';\n\nimport { CALLS_STREAM } from './log-streams';\nimport { logStream } from './log-stream';\nimport { logTarget } from './log-target';\nimport { toError } from '@webpieces/tooling-common/to-error';\n\n/**\n * HOW MANY TIMES has this session already run this exact Bash command?\n *\n * ─── Why a guard is allowed to ask a question about HISTORY at all ─────────────────────────────────\n * Every other guard here answers from the command TEXT plus the tree's git state, and `managed-env.ts`\n * states that preference out loud: same command, same verdict, every time. That rule exists so a\n * verdict cannot depend on where an unrelated earlier command left the shell — an accident.\n *\n * A SPIN is not an accident, and it is not visible in one command. `gh pr checks 874` asked once is a\n * snapshot somebody acts on; asked for the ninetieth time in four minutes it is the wait loop this\n * whole feature exists to delete, and the two are byte-identical. Repetition IS the defect, so\n * repetition is the only thing that can be measured. Nothing else about the call differs.\n *\n * ─── Where the count comes from ────────────────────────────────────────────────────────────────────\n * `InvocationLog` already writes ONE tab-separated line per guards-hook call to\n * `<state>/logs/calls/<sessionId>-<agentId|coordinator>-<hook>.log`, and `logStream` has already been\n * identified with this session and agent by the time a rule's `check()` runs. So the file IS the\n * session, for free — no new state, no new writer, and a worktree-isolated subagent gets its own\n * because the path is resolved from the tree it acts on.\n *\n * Each tool call is its own process and flushes that line at its terminal boundary, so on call N the\n * file holds calls 1..N-1. The count this returns is therefore PRIOR calls, never including the one\n * being judged.\n *\n * ─── It fails OPEN, always ─────────────────────────────────────────────────────────────────────────\n * A missing file (the first call of a session), a rotated one, an unreadable one — all of them mean\n * \"no evidence\", which is 0, which blocks nothing. A logging failure may never become a refusal.\n */\nexport class SessionCallHistory {\n /**\n * How many times `command` already appears as a Bash target in THIS session's call log.\n *\n * The comparison is against the same one-line normalization `InvocationLog` writes, so a command\n * spanning two lines in the payload and the same command on one line count as the same command.\n */\n priorBashCalls(root: string, command: string): number {\n const wanted = logTarget.oneLine(command);\n if (wanted === '') return 0;\n return this.lines(root).filter((line: string): boolean => this.isBashCallOf(line, wanted)).length;\n }\n\n /**\n * One logged call is `[<iso>]\\tBash\\t<target>\\tbranch=…` — so field 1 is the tool and field 2 the\n * command. Split rather than `includes`, because a command that MENTIONS another command in its\n * text would otherwise count as that command.\n */\n private isBashCallOf(line: string, wanted: string): boolean {\n const fields = line.split('\\t');\n return fields.length > 2 && fields[1] === 'Bash' && fields[2] === wanted;\n }\n\n private lines(root: string): readonly string[] {\n // webpieces-disable no-unmanaged-exceptions -- a log that cannot be read is NO EVIDENCE, which\n // is the fail-open answer; a logging failure must never become a refusal\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const file = dotWebpieces.logsFile(root, CALLS_STREAM, logStream.writerFile('.log'));\n if (!fs.existsSync(file)) return [];\n return fs.readFileSync(file, 'utf8').split('\\n');\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return [];\n }\n }\n}\n"]}
@@ -0,0 +1,46 @@
1
+ import { StreamIdentity } from './log-stream';
2
+ /**
3
+ * The detached, fire-and-forget refresher spawned (by file path, not a bin) from
4
+ * main-sync-refresh.ts. It does the SLOW work (merged-PR lookup + git fetch + merge-base +
5
+ * same-file-overlap) and writes `.webpieces/main-sync-status.json` so the next hook call reads it
6
+ * instantly. Nobody reads our exit code or output — we run after the spawning hook has returned.
7
+ *
8
+ * Concurrency: a lock file (`.webpieces/main-sync.lock.json`) holds `inprocess`/`finished` + a start
9
+ * epoch + the holder's pid, taken with an ATOMIC exclusive create. If another refresher already holds
10
+ * it and is alive, we exit immediately (don't pile up `git fetch`es). If the holder is finished, dead,
11
+ * or older than hangTimeoutMinutes, the lock is reclaimed and we proceed.
12
+ *
13
+ * argv: [, , repoRoot, hangTimeoutMinutes, sessionId, agentId, hook]
14
+ *
15
+ * The last three are the SPAWNER's LogStream identity, and adopting them here is the whole reason
16
+ * they are passed. This process has its own fresh module-level `logStream`; left unidentified it
17
+ * named every line `unknown-coordinator-hook.log` — one shared file that every
18
+ * agent's refresher child appended to concurrently (the PIPE_BUF tearing LogStream exists to remove),
19
+ * and which held this run's START/FINISH while the parent's SPAWN_ATTEMPT sat in a different file
20
+ * entirely. Adopting the parent's identity puts one refresh cycle back in one stream. Absent argv
21
+ * (a hand-run of this file) leaves the default, which still prefixes.
22
+ */
23
+ export declare function main(): void;
24
+ /**
25
+ * Parse the hang timeout off argv, WITHOUT `||`.
26
+ *
27
+ * `Number(argv[3]) || DEFAULT` silently rewrote a configured `0` — "never treat a lock as stale" — into
28
+ * the 5-minute default, because `0` is falsy. The knob now has exactly one reader (the branch-state
29
+ * policy entry), so a value that survives the config only to be discarded at the process boundary is
30
+ * the whole knob being a lie. Only a MISSING or non-numeric argument falls back.
31
+ */
32
+ export declare function hangTimeoutFromArgv(raw: string | undefined): number;
33
+ /**
34
+ * The spawner's LogStream identity as it arrives on this child's argv — positions 4/5/6, which is
35
+ * where `triggerMainSyncRefresh` puts them (its own array is offset by two: node + script path).
36
+ *
37
+ * Exported so ONE test can pin BOTH ends of the contract at once. The bug this closes is precisely a
38
+ * disagreement between two files about argv positions, and a test that only checks the reader would
39
+ * have stayed green through it.
40
+ */
41
+ export declare function spawnerIdentity(argv: string[]): StreamIdentity;
42
+ /**
43
+ * The refresh itself, argv-free so it can be driven by a test. `main()` is only the argv parse — a
44
+ * test importing another module's `main` is what no-process-exit-outside-main exists to prevent.
45
+ */
46
+ export declare function refreshMainSync(repoRoot: string, hangTimeoutMinutes: number, argvDetail?: string): void;
@@ -0,0 +1,176 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.main = main;
4
+ exports.hangTimeoutFromArgv = hangTimeoutFromArgv;
5
+ exports.spawnerIdentity = spawnerIdentity;
6
+ exports.refreshMainSync = refreshMainSync;
7
+ const repo_workflow_core_1 = require("@webpieces/repo-workflow-core");
8
+ const rules_config_1 = require("@webpieces/rules-config");
9
+ const to_error_1 = require("@webpieces/tooling-common/to-error");
10
+ const main_sync_log_1 = require("./main-sync-log");
11
+ const log_stream_1 = require("./log-stream");
12
+ /**
13
+ * The detached, fire-and-forget refresher spawned (by file path, not a bin) from
14
+ * main-sync-refresh.ts. It does the SLOW work (merged-PR lookup + git fetch + merge-base +
15
+ * same-file-overlap) and writes `.webpieces/main-sync-status.json` so the next hook call reads it
16
+ * instantly. Nobody reads our exit code or output — we run after the spawning hook has returned.
17
+ *
18
+ * Concurrency: a lock file (`.webpieces/main-sync.lock.json`) holds `inprocess`/`finished` + a start
19
+ * epoch + the holder's pid, taken with an ATOMIC exclusive create. If another refresher already holds
20
+ * it and is alive, we exit immediately (don't pile up `git fetch`es). If the holder is finished, dead,
21
+ * or older than hangTimeoutMinutes, the lock is reclaimed and we proceed.
22
+ *
23
+ * argv: [, , repoRoot, hangTimeoutMinutes, sessionId, agentId, hook]
24
+ *
25
+ * The last three are the SPAWNER's LogStream identity, and adopting them here is the whole reason
26
+ * they are passed. This process has its own fresh module-level `logStream`; left unidentified it
27
+ * named every line `unknown-coordinator-hook.log` — one shared file that every
28
+ * agent's refresher child appended to concurrently (the PIPE_BUF tearing LogStream exists to remove),
29
+ * and which held this run's START/FINISH while the parent's SPAWN_ATTEMPT sat in a different file
30
+ * entirely. Adopting the parent's identity puts one refresh cycle back in one stream. Absent argv
31
+ * (a hand-run of this file) leaves the default, which still prefixes.
32
+ */
33
+ // webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API
34
+ function main() {
35
+ log_stream_1.logStream.identify(spawnerIdentity(process.argv));
36
+ refreshMainSync(process.argv[2] ?? process.cwd(), hangTimeoutFromArgv(process.argv[3]), process.argv.slice(2).join(' '));
37
+ }
38
+ /**
39
+ * Parse the hang timeout off argv, WITHOUT `||`.
40
+ *
41
+ * `Number(argv[3]) || DEFAULT` silently rewrote a configured `0` — "never treat a lock as stale" — into
42
+ * the 5-minute default, because `0` is falsy. The knob now has exactly one reader (the branch-state
43
+ * policy entry), so a value that survives the config only to be discarded at the process boundary is
44
+ * the whole knob being a lie. Only a MISSING or non-numeric argument falls back.
45
+ */
46
+ // webpieces-disable no-function-outside-class -- argv parse for this detached main(), matching the file's existing shape
47
+ function hangTimeoutFromArgv(raw) {
48
+ if (raw === undefined || raw.trim() === '')
49
+ return repo_workflow_core_1.DEFAULT_HANG_TIMEOUT_MINUTES;
50
+ const parsed = Number(raw);
51
+ return Number.isFinite(parsed) ? parsed : repo_workflow_core_1.DEFAULT_HANG_TIMEOUT_MINUTES;
52
+ }
53
+ /**
54
+ * The spawner's LogStream identity as it arrives on this child's argv — positions 4/5/6, which is
55
+ * where `triggerMainSyncRefresh` puts them (its own array is offset by two: node + script path).
56
+ *
57
+ * Exported so ONE test can pin BOTH ends of the contract at once. The bug this closes is precisely a
58
+ * disagreement between two files about argv positions, and a test that only checks the reader would
59
+ * have stayed green through it.
60
+ */
61
+ // webpieces-disable no-function-outside-class -- argv parse for this detached main(), matching the file's existing shape
62
+ function spawnerIdentity(argv) {
63
+ return new log_stream_1.StreamIdentity(argv[4] ?? '', argv[5] ?? '', argv[6] ?? 'hook');
64
+ }
65
+ /**
66
+ * The refresh itself, argv-free so it can be driven by a test. `main()` is only the argv parse — a
67
+ * test importing another module's `main` is what no-process-exit-outside-main exists to prevent.
68
+ */
69
+ // webpieces-disable no-function-outside-class -- module-level entry point of this detached refresher, matching the file's existing shape
70
+ function refreshMainSync(repoRoot, hangTimeoutMinutes, argvDetail = '') {
71
+ const startedMs = Date.now();
72
+ // First action: prove the detached child actually started. If the async-refresh stream has no START line
73
+ // for a spawn, the child never launched (or died before this point).
74
+ (0, main_sync_log_1.logSyncEvent)(repoRoot, new main_sync_log_1.SyncLogEvent('START', process.pid, '-', `argv=${argvDetail}`));
75
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
76
+ try {
77
+ // ONE atomic acquire — not a check followed by a write. The old check-then-write pair had a
78
+ // gap in which two detached children could both pass the check and then both run `git fetch`.
79
+ const lock = (0, repo_workflow_core_1.tryAcquireMainSyncLock)(repoRoot, hangTimeoutMinutes);
80
+ if (!lock) {
81
+ (0, main_sync_log_1.logSyncEvent)(repoRoot, new main_sync_log_1.SyncLogEvent('SKIP_INPROGRESS', process.pid, '-', 'another refresh is in progress'));
82
+ return;
83
+ }
84
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
85
+ try {
86
+ // EVERY worktree's branch, not just ours. The cache is shared by the whole repo but used
87
+ // to describe only the branch of whichever tree won this lock, so every other worktree's
88
+ // guards read a cross-branch cache and abstained. One fetch + one `gh` call now arms all
89
+ // of them; the map is rebuilt from the live worktree set, so dead branches drop out.
90
+ const file = (0, repo_workflow_core_1.computeAllMainSyncStatuses)(repoRoot);
91
+ (0, repo_workflow_core_1.writeMainSyncStatusFile)(repoRoot, file);
92
+ // Second slow signal, same lock, same detached run: which local branches are dead. One bulk
93
+ // `gh pr list --state merged` call. The branch-creation-guard reads the result to enforce its
94
+ // cap without ever touching the network itself. Deliberately allowed to go stale.
95
+ const mergedBranches = new repo_workflow_core_1.MergedBranchesService();
96
+ // `false`: the background refresher NEVER ignores a standing agent lock. That flag is
97
+ // wp-cleanup's, and it means "a human asked for this run" — nothing an unattended
98
+ // refresher can claim on somebody's behalf.
99
+ const cache = mergedBranches.computeMergedBranches(repoRoot, false);
100
+ mergedBranches.writeMergedBranches(repoRoot, cache);
101
+ // Third step, same detached run: actually DELETE the dead branches. Reporting them was
102
+ // never enough — the reap was only ever a `git branch -D` string in a fix hint, which an
103
+ // agent reads as destructive and stalls on, so nothing was ever cleaned. Here nobody has
104
+ // to be asked. Reuses the verdicts we JUST computed (no second `gh` call).
105
+ const reaped = autoReap(repoRoot, cache);
106
+ // FINISH after a successful write — START-without-FINISH means we were killed mid-run.
107
+ const names = Object.keys(file.branches);
108
+ (0, main_sync_log_1.logSyncEvent)(repoRoot, new main_sync_log_1.SyncLogEvent('FINISH', process.pid, names.join(','), `branches=${String(names.length)} ${names.map(summarize(file)).join(' ')} deletableBranches=${String(cache.deletable.length)} reaped=${String(reaped)} ms=${String(Date.now() - startedMs)}`));
109
+ }
110
+ finally {
111
+ // Always flip the lock off so a compute failure can't wedge the guard until the
112
+ // staleness reclaim kicks in.
113
+ (0, repo_workflow_core_1.writeMainSyncLock)(repoRoot, (0, repo_workflow_core_1.finishedLock)(lock.started));
114
+ }
115
+ }
116
+ catch (err) {
117
+ const error = (0, to_error_1.toError)(err);
118
+ // Detached: swallow so a transient git/fs error never leaves poison state (the next hook call
119
+ // spawns a fresh refresher) — but record WHY it died so the failure isn't invisible.
120
+ (0, main_sync_log_1.logSyncEvent)(repoRoot, new main_sync_log_1.SyncLogEvent('ERROR', process.pid, '-', `${error.message} | ${error.stack ?? ''}`));
121
+ }
122
+ }
123
+ /**
124
+ * One `branch(merged/forkPoint/conflict)` token per recorded branch, for the FINISH log line. The log
125
+ * is the only evidence that a given worktree's branch was actually armed by a refresh, so it has to
126
+ * name every branch written, not just the tree the refresher happened to run in.
127
+ */
128
+ // webpieces-disable no-function-outside-class -- module-level log formatter of this detached main(), matching the file's existing shape
129
+ function summarize(file) {
130
+ return (branch) => {
131
+ const status = file.branches[branch];
132
+ if (status === undefined)
133
+ return `${branch}(?)`;
134
+ return `${branch}(merged=${String(status.branchAlreadyMerged)}:${status.mergedPr} fork=${String(status.hasForkPoint)} conflict=${String(status.conflict)})`;
135
+ };
136
+ }
137
+ /**
138
+ * Delete the branches the verdicts just declared dead. Returns how many actually went.
139
+ *
140
+ * WHY it is safe to do this unattended: every candidate is provably dead (merged PR / squash backup
141
+ * of a merged branch / zero commits of its own), `main` and any worktree-held branch are excluded
142
+ * upstream, and each delete is logged with the branch's pre-delete SHA plus the exact command that
143
+ * restores it. WHY it is safe to do it HERE: this refresher already recomputed those verdicts on
144
+ * this very run, so it is acting on evidence seconds old, not on the deliberately-stale cache file.
145
+ *
146
+ * Swallows everything. We are detached and fire-and-forget: cleanup failing must never damage the
147
+ * main-sync status this process exists to produce — but every failure is logged, because a silent
148
+ * background deletion is exactly what nobody should have to trust.
149
+ */
150
+ // webpieces-disable no-function-outside-class -- module-level helper of this detached main(), matching the file's existing shape
151
+ function autoReap(repoRoot, cache) {
152
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
153
+ try {
154
+ const config = (0, rules_config_1.loadAndValidate)(repoRoot).rulesConfig['branch-creation-guard'];
155
+ // Strictly opt-IN: only an explicit `true` reaps. `autoReapMergedBranches` is schema-required,
156
+ // so every validated config states an answer — which means "absent" here is not a consumer
157
+ // who wants the default, it is a config that never passed validation. Deleting branches on
158
+ // that basis would be deleting on a preference nobody expressed.
159
+ if (config?.mode === 'OFF' || config?.autoReapMergedBranches !== true)
160
+ return 0;
161
+ const result = new repo_workflow_core_1.BranchReaper().reap(repoRoot, 'auto-reap', cache);
162
+ for (const failure of result.failed) {
163
+ (0, main_sync_log_1.logSyncEvent)(repoRoot, new main_sync_log_1.SyncLogEvent('ERROR', process.pid, failure.branch, `reap failed: ${failure.error}`));
164
+ }
165
+ return result.reaped.length;
166
+ }
167
+ catch (err) {
168
+ const error = (0, to_error_1.toError)(err);
169
+ (0, main_sync_log_1.logSyncEvent)(repoRoot, new main_sync_log_1.SyncLogEvent('ERROR', process.pid, '-', `autoReap: ${error.message}`));
170
+ return 0;
171
+ }
172
+ }
173
+ if (require.main === module) {
174
+ main();
175
+ }
176
+ //# sourceMappingURL=sync-main.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sync-main.js","sourceRoot":"","sources":["../../../../../../packages/tooling/agent-workflow-rules/src/core/sync-main.ts"],"names":[],"mappings":"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","sourcesContent":["import { BranchCreationGuardConfig } from '../configs/rule-configs';\nimport { BranchReaper, DEFAULT_HANG_TIMEOUT_MINUTES, MainSyncStatusFile, MergedBranchesCache, MergedBranchesService, ReapResult, computeAllMainSyncStatuses, writeMainSyncStatusFile, writeMainSyncLock, tryAcquireMainSyncLock, finishedLock } from '@webpieces/repo-workflow-core';\nimport { loadAndValidate } from '@webpieces/rules-config';\n\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { logSyncEvent, SyncLogEvent } from './main-sync-log';\nimport { logStream, StreamIdentity } from './log-stream';\n\n/**\n * The detached, fire-and-forget refresher spawned (by file path, not a bin) from\n * main-sync-refresh.ts. It does the SLOW work (merged-PR lookup + git fetch + merge-base +\n * same-file-overlap) and writes `.webpieces/main-sync-status.json` so the next hook call reads it\n * instantly. Nobody reads our exit code or output — we run after the spawning hook has returned.\n *\n * Concurrency: a lock file (`.webpieces/main-sync.lock.json`) holds `inprocess`/`finished` + a start\n * epoch + the holder's pid, taken with an ATOMIC exclusive create. If another refresher already holds\n * it and is alive, we exit immediately (don't pile up `git fetch`es). If the holder is finished, dead,\n * or older than hangTimeoutMinutes, the lock is reclaimed and we proceed.\n *\n * argv: [, , repoRoot, hangTimeoutMinutes, sessionId, agentId, hook]\n *\n * The last three are the SPAWNER's LogStream identity, and adopting them here is the whole reason\n * they are passed. This process has its own fresh module-level `logStream`; left unidentified it\n * named every line `unknown-coordinator-hook.log` — one shared file that every\n * agent's refresher child appended to concurrently (the PIPE_BUF tearing LogStream exists to remove),\n * and which held this run's START/FINISH while the parent's SPAWN_ATTEMPT sat in a different file\n * entirely. Adopting the parent's identity puts one refresh cycle back in one stream. Absent argv\n * (a hand-run of this file) leaves the default, which still prefixes.\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 main(): void {\n logStream.identify(spawnerIdentity(process.argv));\n refreshMainSync(\n process.argv[2] ?? process.cwd(),\n hangTimeoutFromArgv(process.argv[3]),\n process.argv.slice(2).join(' '),\n );\n}\n\n/**\n * Parse the hang timeout off argv, WITHOUT `||`.\n *\n * `Number(argv[3]) || DEFAULT` silently rewrote a configured `0` — \"never treat a lock as stale\" — into\n * the 5-minute default, because `0` is falsy. The knob now has exactly one reader (the branch-state\n * policy entry), so a value that survives the config only to be discarded at the process boundary is\n * the whole knob being a lie. Only a MISSING or non-numeric argument falls back.\n */\n// webpieces-disable no-function-outside-class -- argv parse for this detached main(), matching the file's existing shape\nexport function hangTimeoutFromArgv(raw: string | undefined): number {\n if (raw === undefined || raw.trim() === '') return DEFAULT_HANG_TIMEOUT_MINUTES;\n const parsed = Number(raw);\n return Number.isFinite(parsed) ? parsed : DEFAULT_HANG_TIMEOUT_MINUTES;\n}\n\n/**\n * The spawner's LogStream identity as it arrives on this child's argv — positions 4/5/6, which is\n * where `triggerMainSyncRefresh` puts them (its own array is offset by two: node + script path).\n *\n * Exported so ONE test can pin BOTH ends of the contract at once. The bug this closes is precisely a\n * disagreement between two files about argv positions, and a test that only checks the reader would\n * have stayed green through it.\n */\n// webpieces-disable no-function-outside-class -- argv parse for this detached main(), matching the file's existing shape\nexport function spawnerIdentity(argv: string[]): StreamIdentity {\n return new StreamIdentity(argv[4] ?? '', argv[5] ?? '', argv[6] ?? 'hook');\n}\n\n/**\n * The refresh itself, argv-free so it can be driven by a test. `main()` is only the argv parse — a\n * test importing another module's `main` is what no-process-exit-outside-main exists to prevent.\n */\n// webpieces-disable no-function-outside-class -- module-level entry point of this detached refresher, matching the file's existing shape\nexport function refreshMainSync(repoRoot: string, hangTimeoutMinutes: number, argvDetail: string = ''): void {\n const startedMs = Date.now();\n\n // First action: prove the detached child actually started. If the async-refresh stream has no START line\n // for a spawn, the child never launched (or died before this point).\n logSyncEvent(repoRoot, new SyncLogEvent('START', process.pid, '-', `argv=${argvDetail}`));\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // ONE atomic acquire — not a check followed by a write. The old check-then-write pair had a\n // gap in which two detached children could both pass the check and then both run `git fetch`.\n const lock = tryAcquireMainSyncLock(repoRoot, hangTimeoutMinutes);\n if (!lock) {\n logSyncEvent(repoRoot, new SyncLogEvent('SKIP_INPROGRESS', process.pid, '-', 'another refresh is in progress'));\n return;\n }\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // EVERY worktree's branch, not just ours. The cache is shared by the whole repo but used\n // to describe only the branch of whichever tree won this lock, so every other worktree's\n // guards read a cross-branch cache and abstained. One fetch + one `gh` call now arms all\n // of them; the map is rebuilt from the live worktree set, so dead branches drop out.\n const file = computeAllMainSyncStatuses(repoRoot);\n writeMainSyncStatusFile(repoRoot, file);\n\n // Second slow signal, same lock, same detached run: which local branches are dead. One bulk\n // `gh pr list --state merged` call. The branch-creation-guard reads the result to enforce its\n // cap without ever touching the network itself. Deliberately allowed to go stale.\n const mergedBranches = new MergedBranchesService();\n // `false`: the background refresher NEVER ignores a standing agent lock. That flag is\n // wp-cleanup's, and it means \"a human asked for this run\" — nothing an unattended\n // refresher can claim on somebody's behalf.\n const cache = mergedBranches.computeMergedBranches(repoRoot, false);\n mergedBranches.writeMergedBranches(repoRoot, cache);\n\n // Third step, same detached run: actually DELETE the dead branches. Reporting them was\n // never enough — the reap was only ever a `git branch -D` string in a fix hint, which an\n // agent reads as destructive and stalls on, so nothing was ever cleaned. Here nobody has\n // to be asked. Reuses the verdicts we JUST computed (no second `gh` call).\n const reaped = autoReap(repoRoot, cache);\n\n // FINISH after a successful write — START-without-FINISH means we were killed mid-run.\n const names = Object.keys(file.branches);\n logSyncEvent(repoRoot, new SyncLogEvent(\n 'FINISH', process.pid, names.join(','),\n `branches=${String(names.length)} ${names.map(summarize(file)).join(' ')} deletableBranches=${String(cache.deletable.length)} reaped=${String(reaped)} ms=${String(Date.now() - startedMs)}`,\n ));\n } finally {\n // Always flip the lock off so a compute failure can't wedge the guard until the\n // staleness reclaim kicks in.\n writeMainSyncLock(repoRoot, finishedLock(lock.started));\n }\n } catch (err: unknown) {\n const error = toError(err);\n // Detached: swallow so a transient git/fs error never leaves poison state (the next hook call\n // spawns a fresh refresher) — but record WHY it died so the failure isn't invisible.\n logSyncEvent(repoRoot, new SyncLogEvent('ERROR', process.pid, '-', `${error.message} | ${error.stack ?? ''}`));\n }\n}\n\n/**\n * One `branch(merged/forkPoint/conflict)` token per recorded branch, for the FINISH log line. The log\n * is the only evidence that a given worktree's branch was actually armed by a refresh, so it has to\n * name every branch written, not just the tree the refresher happened to run in.\n */\n// webpieces-disable no-function-outside-class -- module-level log formatter of this detached main(), matching the file's existing shape\nfunction summarize(file: MainSyncStatusFile): (branch: string) => string {\n return (branch: string): string => {\n const status = file.branches[branch];\n if (status === undefined) return `${branch}(?)`;\n return `${branch}(merged=${String(status.branchAlreadyMerged)}:${status.mergedPr} fork=${String(status.hasForkPoint)} conflict=${String(status.conflict)})`;\n };\n}\n\n/**\n * Delete the branches the verdicts just declared dead. Returns how many actually went.\n *\n * WHY it is safe to do this unattended: every candidate is provably dead (merged PR / squash backup\n * of a merged branch / zero commits of its own), `main` and any worktree-held branch are excluded\n * upstream, and each delete is logged with the branch's pre-delete SHA plus the exact command that\n * restores it. WHY it is safe to do it HERE: this refresher already recomputed those verdicts on\n * this very run, so it is acting on evidence seconds old, not on the deliberately-stale cache file.\n *\n * Swallows everything. We are detached and fire-and-forget: cleanup failing must never damage the\n * main-sync status this process exists to produce — but every failure is logged, because a silent\n * background deletion is exactly what nobody should have to trust.\n */\n// webpieces-disable no-function-outside-class -- module-level helper of this detached main(), matching the file's existing shape\nfunction autoReap(repoRoot: string, cache: MergedBranchesCache): number {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const config = loadAndValidate(repoRoot).rulesConfig['branch-creation-guard'] as BranchCreationGuardConfig | undefined;\n // Strictly opt-IN: only an explicit `true` reaps. `autoReapMergedBranches` is schema-required,\n // so every validated config states an answer — which means \"absent\" here is not a consumer\n // who wants the default, it is a config that never passed validation. Deleting branches on\n // that basis would be deleting on a preference nobody expressed.\n if (config?.mode === 'OFF' || config?.autoReapMergedBranches !== true) return 0;\n\n const result: ReapResult = new BranchReaper().reap(repoRoot, 'auto-reap', cache);\n for (const failure of result.failed) {\n logSyncEvent(repoRoot, new SyncLogEvent(\n 'ERROR', process.pid, failure.branch, `reap failed: ${failure.error}`));\n }\n return result.reaped.length;\n } catch (err: unknown) {\n const error = toError(err);\n logSyncEvent(repoRoot, new SyncLogEvent('ERROR', process.pid, '-', `autoReap: ${error.message}`));\n return 0;\n }\n}\n\nif (require.main === module) {\n main();\n}\n"]}
@@ -0,0 +1,219 @@
1
+ import { AiType } from '@webpieces/hook-runtime';
2
+ import { EffectiveTree } from '@webpieces/hook-runtime';
3
+ import { VersionQuartet } from './webpieces-versions';
4
+ export declare class VersionSyncGuard {
5
+ private readonly inspection;
6
+ private readonly versions;
7
+ /**
8
+ * True when this tree is a linked worktree whose webpieces version disagrees with the main tree's.
9
+ * This is the `V` dimension of the L1 matrix; the runner asks it for EVERY Bash call so the answer
10
+ * lands in the audit log even when nothing blocks.
11
+ */
12
+ skewed(tree: EffectiveTree): boolean;
13
+ /** The deny report, or null to allow. */
14
+ block(command: string, tree: EffectiveTree, aiType: AiType): string | null;
15
+ /**
16
+ * Commands that must pass EVEN WHILE THIS GUARD IS BLOCKING, because they are how you get unblocked
17
+ * — or how you look at the tree first.
18
+ *
19
+ * `ReadOnlyInspectionScan` deliberately excludes git and gh OUTRIGHT ("the guards exist to police
20
+ * git, and read-only git is not a line worth drawing while flying blind"), which is right for the
21
+ * guards that police git but WRONG here: this guard's own prescribed cure is `git pull` in both
22
+ * trees. Without this carve-out the guard would deny the exact command it tells the reader to run —
23
+ * the single failure shape this repo has been burned by most often, and the reason the deny text is
24
+ * allowed to promise "STILL ALLOWED HERE: ... pnpm install, git pull/fetch".
25
+ *
26
+ * Deliberately NARROW: fetching, pulling and installing cannot make a skew worse, and every one of
27
+ * them moves the tree toward agreement. Anything that BUILDS, TESTS or COMMITS is still blocked,
28
+ * because those are the operations that would be judged by the wrong release.
29
+ */
30
+ private isCureOrLook;
31
+ /**
32
+ * Is there a cross-tree comparison to make at all? TWO cheap conditions, no file read behind either:
33
+ *
34
+ * • K is `worktree` — git's `--git-dir ≠ --git-common-dir`, so a repo with no linked worktrees can
35
+ * never reach the manifests. (In the primary clone this is also structural escape #1: "do the
36
+ * work in the main tree" needs no allowlist entry to keep working.)
37
+ * • the two roots are DIFFERENT directories — a tree compared with itself is not a skew, it is the
38
+ * single-tree pin-vs-install question the L0 drift guard already owns.
39
+ */
40
+ private applies;
41
+ /** Public so the runner can log all four versions on ALLOW as well as on BLOCK (audit, not just deny). */
42
+ quartetFor(tree: EffectiveTree): VersionQuartet;
43
+ private report;
44
+ /**
45
+ * WHICH of the five states this is — asked ONCE, so the FIX block and the escalation block can never
46
+ * describe two different diagnoses of the same skew.
47
+ *
48
+ * Order is not arbitrary. `main-inconsistent` is asked FIRST because it is a fault in the governing
49
+ * tree itself: comparing this worktree against a tree that disagrees with itself picks a direction
50
+ * out of two numbers that are not yet one answer. `bump` next, because a deliberate raise is the one
51
+ * shape where the direction is real but every ordinary cure is harmful.
52
+ */
53
+ private classify;
54
+ /**
55
+ * SEMVER ORDER of two versions: 1 when `a` is newer, -1 when older, 0 when equal OR undecidable.
56
+ *
57
+ * 0 is the FAIL-SAFE answer and every caller must read it as "no opinion": an unreadable leg, a
58
+ * dist-tag, two different pre-releases, or build metadata (which carries no precedence) all land
59
+ * there, and `classify` then falls to `main-behind`, the branch that ASKS rather than acts. Guessing
60
+ * a direction is how a downgrade gets prescribed, and this repo has already paid for that once.
61
+ *
62
+ * The same rules the shim's awk compare uses, so L0 and L1 cannot order one pair two ways: build
63
+ * metadata stripped, numeric cores compared component-wise, and a pre-release sorting BELOW its
64
+ * release.
65
+ */
66
+ private compare;
67
+ /** One version split into its numeric core and its pre-release suffix, or null if it is not numeric. */
68
+ private parts;
69
+ /**
70
+ * The cure list, which is NOT the same list in both directions — but which, in BOTH directions, is a
71
+ * list of things the reader ASKS FOR rather than runs.
72
+ *
73
+ * The ordinary skew is two trees sitting on different commits of main. The pin is tracked, so putting
74
+ * both trees on the same commit and installing genuinely converges them. That cure is WRONG, and worse
75
+ * than useless, when the branch bumped the pin ON PURPOSE: pulling would revert the deliverable, and
76
+ * an install cannot move a pin in either tree. Printing the git cure first in that case is what sent a
77
+ * real upgrade agent round the loop below.
78
+ *
79
+ * WHAT THIS BLOCK IS NOT ALLOWED TO SAY, in either branch: `git -C <the main tree> pull`. Two defects
80
+ * rode on that one line, and it was printed ABOVE the escalation block, so it was the first thing read.
81
+ * (a) A worktree-isolated SUBAGENT — the overwhelmingly common reader of this deny — CANNOT run
82
+ * cross-tree git at all; the harness refuses it (shim-deny-reason.ts records the same
83
+ * measurement). The one printed cure was the one thing the reader could not perform.
84
+ * (b) A bare `git pull` acts on whatever branch that tree currently has checked out, and the primary
85
+ * clone is normally sitting on a feature branch. It pulls the feature branch, the manifest never
86
+ * moves, the pin never converges, and this guard fires again. The cure has to NAME main:
87
+ * `cd <main> && git checkout main && git pull`.
88
+ * So every step is prefixed `Tell main agent:` — INDIVIDUALLY, not under one shared header. That
89
+ * repetition is deliberate and is the deliverable: a reader who skims exactly one of these lines must
90
+ * still see it is not their own action. Do not factor it out.
91
+ *
92
+ * The FIX block still prints ABOVE the escalation block, on purpose. Moving it below would split the
93
+ * numbered steps from the versions they refer to, and the do-not-retry beat has to stay last and stay
94
+ * unique — a second shouted beat competing with it is exactly the wall-of-text regression the L0
95
+ * message diet exists to prevent.
96
+ * Labelling carries the "not yours to run" fact instead, which is what the caps header does.
97
+ */
98
+ private fixLines;
99
+ /**
100
+ * CASE A — the MAIN tree disagrees with ITSELF: its `node_modules` is on one version while its own
101
+ * `pnpm-workspace.yaml` pins another. Nothing in this worktree is wrong, and nothing this worktree
102
+ * does can help.
103
+ *
104
+ * The cure is deliberately the SMALL one. The generic branch prints `git checkout main && git pull`
105
+ * first, and that is over-prescribed here: both halves of the disagreement are already in that tree,
106
+ * so an install materializes the pin it already has and the skew is gone. Printing the pull as well
107
+ * invites a main agent to move main's commit for a fault that is not about main's commit at all.
108
+ */
109
+ private mainInconsistentFix;
110
+ /**
111
+ * CASE B — the MAIN tree already RUNS a newer release than this tree's pin asks for. This is the
112
+ * common case, and it is the one the old message got exactly backwards.
113
+ *
114
+ * It is the ONLY case a worktree fixes ITSELF. Nothing needs to move in the main tree — the version
115
+ * the guards will judge this tree by is already installed there — so the entire fix is to raise this
116
+ * tree's own pin to match, which is a one-line edit to a TRACKED file this tree owns. Printing an
117
+ * escalation here (as every earlier revision did) tells an agent to stop and wait for a main agent
118
+ * who has nothing to do, which is how a five-minute edit became a stalled turn.
119
+ *
120
+ * The edit is typable from inside the block because pnpm-workspace.yaml is on the L0 allowlist and
121
+ * carved out in the runner's edit path. That carve-out and this text ship together on purpose: a
122
+ * message prescribing a blocked call is the failure shape this repo has been burned by most often.
123
+ *
124
+ * ON A DETACHED HEAD the edit has no branch to belong to, so it is not offered — an edit that
125
+ * survives nothing is worse than no edit. Get onto a branch, then read this message again.
126
+ */
127
+ private mainAheadFix;
128
+ /**
129
+ * Is HEAD DETACHED in this tree — i.e. is there no branch for a pin edit to belong to?
130
+ *
131
+ * `branch --show-current`, NOT `rev-parse --abbrev-ref HEAD`: it answers on an UNBORN branch (which
132
+ * every freshly-created worktree is until its first commit, and where `rev-parse` fatals) and prints
133
+ * EMPTY on a detached HEAD, which is exactly the distinction case B needs.
134
+ *
135
+ * A git FAILURE is NOT detached, and the difference is load-bearing: `--show-current` prints nothing
136
+ * in both situations, so keying off the output alone would tell anyone whose tree git cannot read
137
+ * (no repo, a broken index, git absent) that their HEAD is detached — a confident diagnosis of a
138
+ * state nobody measured. Only an exit-0-with-empty-output is detached; anything else falls back to
139
+ * the ordinary branch wording, whose worst case is prescribing an edit that turns out to be moot.
140
+ */
141
+ private isDetachedHead;
142
+ /**
143
+ * THE SUBAGENT CANNOT REACH THE MAIN TREE, so the message it is handed has to be the message it
144
+ * FORWARDS. This used to be one sentence — "report to your coordinator that one of you must move to
145
+ * the other's version" — with no command, no direction and nothing pasteable, and the result was a
146
+ * subagent that correctly diagnosed the block, correctly escalated, and handed its coordinator a
147
+ * request too vague to act on. Worse, the obvious guess ("ask the coordinator to run `pnpm install`
148
+ * in main") is a NO-OP on a bump: it reinstalls main's own pin and nothing moves.
149
+ *
150
+ * So the escalation is rendered as literal text to forward, with the versions and the direction
151
+ * already filled in. A human cannot sit with every agent; the deny has to carry the whole ask.
152
+ *
153
+ * The ask is ROUTED THROUGH THE MAIN AGENT rather than phrased as a command, and that distinction is
154
+ * the whole point of this block. `git -C <mainRoot> pull` reads like something you run from wherever
155
+ * you are standing — so a subagent reads it, tries it, and only then discovers that CROSS-TREE GIT IS
156
+ * REFUSED to a worktree-isolated agent (same measurement shim-deny-reason.ts records: the harness
157
+ * blocks `git -C <other tree>`, and it is git specifically). This skew needs a git pull in main, so
158
+ * the one printed cure was the one thing this session cannot perform. Be precise about that and do
159
+ * NOT overstate it into "you cannot reach that tree at all" — a local `cd <main> && pnpm install`
160
+ * measurably DOES run, it simply cannot move main onto a different commit, which is what a skew
161
+ * requires. The actor who can is the MAIN AGENT running in the MAIN git worktree, so the forwarded
162
+ * text asks for exactly that — and asks to be TOLD WHEN IT IS DONE, because "the work happened" is
163
+ * the event that unblocks this subagent and it has no way to observe it otherwise.
164
+ *
165
+ * And it has to refuse the RETRY, because forwarding is only half of what the subagent must do. One
166
+ * measured subagent transcript re-fired this identical deny 13 TIMES (25 across the whole session,
167
+ * counting two sibling subagents and two parent sessions): the subagent read it, escalated exactly
168
+ * as asked — and then re-ran the blocked call. Every retry cost a round trip and pushed the one
169
+ * message that mattered further up the scrollback. The block is not transient and no command from
170
+ * this tree slips past it, so retrying is never a strategy; it is the bug.
171
+ *
172
+ * What it must NOT do is decide the agent's control flow. #679 first wrote this beat as "STOP WORKING
173
+ * NOW. Forwarding that message IS the end of your turn: make NO further tool calls" — a turn-level
174
+ * prescription, which `.claude/rules/never-tell-an-ai-to-end-its-turn.md` forbids (#902 deleted every
175
+ * other one; this one survived because no spec rendered it — issue #1000). Refusing one futile
176
+ * command is legitimate; ruling on when the turn ends is a judgement the agent is better placed to
177
+ * make. So the beat names the retry, says why it is futile, and stops talking.
178
+ */
179
+ private escalationLines;
180
+ /**
181
+ * What the coordinator does ONCE main is synced — and here the two harnesses need opposite answers.
182
+ *
183
+ * Codex runs every subagent in the coordinator's own checkout, so "tell me when it is done so I can
184
+ * continue" is literally true: the same agent picks up where it stopped.
185
+ *
186
+ * Claude Code does NOT keep that tree for it. A worktree-isolated subagent that hands back with an
187
+ * unchanged worktree has that worktree REAPED, and a subagent resumed afterwards (SendMessage) comes
188
+ * back with its cwd on the PRIMARY clone — which happened to the first agent on issue #863 itself. So
189
+ * asking to be resumed routes the work into the one tree it must never land in. The ask is therefore a
190
+ * FRESH `isolation: "worktree"` subagent, and "resume me" / "continue working" must not appear.
191
+ */
192
+ private afterwardLines;
193
+ private waitLines;
194
+ /**
195
+ * The forwardable ASK, one per case that needs one. `main-ahead` never reaches here — it has nothing
196
+ * to ask for — so the three shapes below cover every escalating case. What happens AFTER the ask is
197
+ * harness-specific and lives in {@link afterwardLines}, so none of these says "tell me when".
198
+ *
199
+ * The bump ask carries the upgrade sentence VERBATIM as Dean wrote it, because it answers the one
200
+ * question an upgrade agent gets wrong: "webpieces cannot be upgraded from a worktree" is not a
201
+ * missing permission it can route around, it is a property of who governs whom.
202
+ */
203
+ private askLines;
204
+ /**
205
+ * Did THIS BRANCH change the pin, as opposed to the two trees having drifted onto different commits?
206
+ *
207
+ * Only answerable now that both pin legs actually resolve — before the catalog reader followed YAML
208
+ * anchors they both read null on the repos that pin via an anchor, so every skew looked alike and the
209
+ * report could only ever print the one generic cure.
210
+ *
211
+ * Two git spawns worst case, on the BLOCK path only (this is never reached on an allow), and
212
+ * best-effort: a git failure answers "not a deliberate bump", which falls back to the generic cure
213
+ * that was the only text this report had before.
214
+ */
215
+ private isDeliberateBump;
216
+ private touchesWorkspaceFile;
217
+ private versionLines;
218
+ private show;
219
+ }