@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,198 @@
1
+ import { BranchStateGuardConfig } from "../../configs/main-sync-guard-configs";
2
+ import type { BashContext, Violation } from '@webpieces/hook-runtime';
3
+ import { BashRuleBase } from '@webpieces/hook-runtime';
4
+ import { FixHint } from '@webpieces/hook-runtime';
5
+ /**
6
+ * The BASH half of the STALE-MAIN protection (read-stale-guard's State A), in two halves of its own:
7
+ * a PREVENTIVE check that stops a session landing on a stale `main`, and the REACTIVE check that
8
+ * contains the damage once it is already there.
9
+ *
10
+ * ── PREVENTIVE: a bare `git checkout main` is blocked; the pull must ride along ──────────────────
11
+ *
12
+ * Everything below this paragraph fires only once the session is ALREADY sitting on a stale `main`.
13
+ * Nothing stopped it ARRIVING there, and arriving is one keystroke. In the incident that added this
14
+ * half, an agent ran `git checkout main` after a merge, in a clone whose local `main` was **157
15
+ * commits behind** origin. That checkout did not merely produce stale files — it reverted:
16
+ *
17
+ * 1. `package.json`'s `@webpieces` pin, to a version OLDER than the installed `node_modules`;
18
+ * 2. `.claude/webpieces/ai-hook.sh` — the version-drift guard ITSELF — to a 157-commit-old copy
19
+ * whose message stated the drift BACKWARDS ("your installed webpieces is older than required")
20
+ * and named a single cure, `pnpm install`;
21
+ * 3. and so the agent's judgment: it ran that `pnpm install`, DOWNGRADING `node_modules` to match
22
+ * the stale pin, and had to undo it with the `git pull` that should have come first.
23
+ *
24
+ * The shim on current main already diagnoses drift correctly — it distinguishes "the pin is newer"
25
+ * from "the pin is stale, and `pnpm install` would downgrade you". None of that helped, because the
26
+ * checkout had replaced the shim with the version that could not say it. **A guard a stale checkout
27
+ * can revert cannot be relied on to catch a stale checkout**, which is why this check is preventive
28
+ * and why it lives here rather than in a second rule: same failure, one step earlier, one switch.
29
+ *
30
+ * It matches on command TEXT alone and asks git nothing. That is not laziness — this runs BEFORE the
31
+ * checkout, so the only `main` it could measure is the one it is about to leave. The interesting
32
+ * `main` does not exist yet, and consulting HEAD-at-hook-time is the exact trap
33
+ * `redirect-how-to-merge-main` documents at length. Pairing is unconditionally correct instead: when
34
+ * `main` is already current the chained pull is a sub-second no-op, so no exception is worth carving.
35
+ *
36
+ * BLOCKED `git checkout main`, `git switch main` — with or without flags — when no `git pull`
37
+ * appears anywhere in the SAME command.
38
+ * ALLOWED `git checkout main && git pull origin main`, the pairing this forces — and
39
+ * `pnpm wp-sync-main`, which IS that pairing with the cleanup and the
40
+ * orphan-directory sweep welded on. The message prescribes the one command; the raw pair
41
+ * stays legal because it is plain git and because it is the L0 recovery cure, where
42
+ * `node_modules` is the thing in doubt and no `pnpm` bin can be relied on.
43
+ * ALLOWED `git checkout -b <x> origin/main` (current by construction), `git checkout <sha>`,
44
+ * `git checkout -- <file>`, and any other branch.
45
+ *
46
+ * ── ROWS 6/7: the block fires only beyond the configured stale threshold ────────────────────
47
+ *
48
+ * The finding is not "you are on `main`" — it is **"what you would read here is out of date"**. So the
49
+ * ladder below asks the main-sync cache, exactly as read-stale-guard's State A does, and BLOCKS only
50
+ * when cached `commitsBehind` is greater than `maxCommitsBehind`. Unknown → allow. At or below
51
+ * the threshold → allow. The detached refresher computes the count; this hot path never does.
52
+ *
53
+ * WHY, when this guard spent a release judging the branch alone: because the branch alone denies
54
+ * everything off a narrow allowlist on a PERFECTLY CURRENT `main`, and a current `main` is exactly
55
+ * where the prescribed cure leaves you. An agent lands a PR, runs `pnpm wp-sync-main` — the
56
+ * command this repo tells it to run — and the next `curl`, `gh pr close` or test run is refused by a
57
+ * guard whose own name says STALE. The tool that got it there could not be the cure for being there,
58
+ * and the refusal had nothing to do with staleness, which is the confusion reported from the field.
59
+ *
60
+ * THE ASYMMETRY WITH `E` IS DELIBERATE, and the docblocks that argued `B` should track `E` were right
61
+ * about the mechanism and wrong about the policy. A WRITE on `main` creates work in the wrong place
62
+ * whatever `main`'s freshness — unreviewable, and unrevertable as a unit — so feature-branch-guard
63
+ * stays unconditional and keeps its one `git rev-parse`. A READ or a BUILD on a CURRENT `main` harms
64
+ * nothing, and blocking it strands the agent at the exact moment the prescribed cure put it there.
65
+ * Same tree, different hazard, so one precondition was never right for both.
66
+ *
67
+ * THE ANCESTRY TEST, NOT HASH EQUALITY. `MainFreshness.containsOriginMain` asks "does local `main`
68
+ * already contain the cached `origin/main`?", so the block lifts the instant a pull lands rather than
69
+ * waiting for the detached refresher to catch up. It is the SAME object read-stale-guard uses — one
70
+ * implementation, so the Read and Bash halves of one state can never disagree about whether the pull
71
+ * took.
72
+ *
73
+ * FAIL-OPEN ON EVERYTHING NOT ESTABLISHED, logged as `ALLOW_FAIL_OPEN` so abstentions stay countable:
74
+ * no cache (the first call of every session), a cache for another branch, an empty `originMain`
75
+ * (offline), no local `main` at all (fresh clone / worktree), branch undeterminable. The refresher is
76
+ * fired detached on every call to keep the cache warm for the NEXT one; it is never waited on, and no
77
+ * synchronous `git fetch` is ever run on the blocking path.
78
+ *
79
+ * THE POLARITY INSIDE THE BLOCKED STATE IS UNCHANGED: default-DENY plus row 4's skip list, the shape
80
+ * merged-branch-bash-guard uses for state B, via the same shared RecoveryAllowlist. A content-read
81
+ * BLOCKLIST could not replace it — enumerating readers catches `cat` and `grep`, and structurally
82
+ * cannot catch `pnpm install`, `npx expo install`, a formatter, codegen or a `>` redirect: commands
83
+ * whose stated purpose is something else and whose effect is to modify tracked files. What changed is
84
+ * WHEN that polarity applies, not the polarity.
85
+ *
86
+ * BLOCKED on a `main` known beyond the configured threshold: anything not on the skip list — builds, tests,
87
+ * installers, formatters, codegen, `cat`/`grep`/`ls` of the tree, git writes.
88
+ * ALLOWED every command on a `main` that is current or whose freshness is unknown — and, in the
89
+ * blocked state, everything that gets you OUT or tells you where you are:
90
+ * `git checkout -b <new> origin/main`, `git switch`, `git pull`/`fetch`,
91
+ * `git status|log|diff|show|branch`, `git stash`, `gh` (it talks to GitHub, not to this
92
+ * tree), `curl`/`wget`, every `wp-*` bin, installs.
93
+ *
94
+ * ── ROWS 12/13: the cure may be COMPOSED with the work, but only with `&&` ───────────────────────
95
+ *
96
+ * `pnpm wp-sync-main && cat src/app.ts` is allowed and `pnpm wp-sync-main ; cat
97
+ * src/app.ts` is not, and the difference is the shell's rather than this guard's: `&&` short-circuits,
98
+ * so the work cannot run when the cure failed — the exact property the block is here to guarantee. `;`
99
+ * discards the exit code and runs the work anyway. See cure-prefix-scan.ts for the measured shapes.
100
+ *
101
+ * There is no dirty-tree valve here and none in read-stale-guard either: the cure is
102
+ * `git checkout -b`, which CARRIES uncommitted work onto the new branch, so a dirty tree traps nobody
103
+ * in any L2 state. (`git stash` covers the residual where origin/main touched the same files.)
104
+ */
105
+ export declare class StaleMainBashGuardRule extends BashRuleBase<BranchStateGuardConfig> {
106
+ constructor(config: BranchStateGuardConfig);
107
+ private readonly scanner;
108
+ private readonly recovery;
109
+ private readonly switches;
110
+ private readonly recoveryList;
111
+ private readonly freshness;
112
+ private readonly curePrefix;
113
+ readonly description: string;
114
+ readonly defaultOptions: {
115
+ hangTimeoutMinutes: number;
116
+ };
117
+ readonly fixHint: FixHint;
118
+ check(ctx: BashContext): readonly Violation[];
119
+ /**
120
+ * ROWS 6/7 — block ONLY when cached `commitsBehind` exceeds `maxCommitsBehind`.
121
+ *
122
+ * Read this beside read-stale-guard.checkStaleMain: it is the same ladder over the same cache, and
123
+ * that is on purpose — the Read and the Bash halves of one state must not disagree about whether
124
+ * `main` is stale. What differs is the VERDICT SHAPE once it is stale, because a Read names one
125
+ * file and a Bash command is opaque: the Read is judged per file, Bash is default-deny plus the
126
+ * row 4 skip list already applied above.
127
+ *
128
+ * Every exit that is not "established BEHIND" is an ALLOW, and the not-established ones are
129
+ * `ALLOW_FAIL_OPEN` so they stay countable. A guard that cannot see the state judges nothing.
130
+ */
131
+ private checkFreshness;
132
+ /**
133
+ * ROWS 12/13 — `<cure> && <work>` is allowed; `<cure> ; <work>` is not.
134
+ *
135
+ * The distinction is the shell's, not this guard's invention. `&&` short-circuits, so the work
136
+ * cannot run when the cure exits non-zero — which is precisely the property the block exists to
137
+ * guarantee, already enforced by the interpreter. Refusing it bought nothing and cost a round
138
+ * trip, and the fleet audit files that as a TOOLING defect.
139
+ *
140
+ * `;` discards the exit code and runs the work regardless, and it was measured with
141
+ * `>/dev/null 2>&1` on the cure in 7 of 9 observed cases — so the failure was invisible as well as
142
+ * ignored. The two-step is genuinely safer there: the NEXT tool call is a fresh evaluation that
143
+ * recomputes `localMain` against `originMain`, so a pull that failed re-blocks. An allowed `;`
144
+ * compound never gets that second look.
145
+ */
146
+ private judgeComposition;
147
+ /**
148
+ * The first segment that switches to the `main` BRANCH with no `git pull` anywhere in the same
149
+ * command, or null. The pull is looked for across the WHOLE command, not the matched segment,
150
+ * because `git checkout main && git pull origin main` splits into two segments and the pairing is
151
+ * the point.
152
+ */
153
+ private bareCheckoutOfMain;
154
+ /**
155
+ * The stale-`main` deny. Deliberately SHORT, and now deliberately ABOUT STALENESS — which is what
156
+ * the guard's name promised all along.
157
+ *
158
+ * The two versions before this one are both instructive. The oldest opened with how many commits
159
+ * behind `main` was, which invited the wrong cure: an agent that reads "behind" reaches for a pull,
160
+ * lands on a CURRENT `main`, and is still on `main`. The one after it swung the other way and said
161
+ * `main` is not a place to work "whether or not it is current" — true of a WRITE, but this guard
162
+ * does not see writes, and it made every refusal on a freshly-pulled `main` unanswerable.
163
+ *
164
+ * So the text says what is now actually true and nothing more: local `main` is BEHIND, so what you
165
+ * read here is out of date; Bash is default-deny in this state rather than a list of readers,
166
+ * because a command's stated purpose never says whether it also WRITES; and the branch cure fetches,
167
+ * so it makes the reads true as well as moving the work somewhere reviewable. Reading `main` to PLAN
168
+ * stays legitimate — on a CURRENT `main` nothing here fires at all.
169
+ *
170
+ * ONE cure, and it is the dirty-safe one, the same call feature-branch-guard made: `git checkout -b`
171
+ * carries uncommitted work onto the new branch. (Row 6 also lists the pull, and read-stale-guard
172
+ * prints it, because a Read really can be cured by staying put. A Bash session cannot — the next
173
+ * command is as likely to write as to read.)
174
+ */
175
+ private staleMainMessage;
176
+ /**
177
+ * ROW 13's deny. It NAMES the operator the agent typed, because the fix is a one-character edit
178
+ * and an agent told only "use `&&`" has to diff the two spellings itself to find where.
179
+ */
180
+ private compositionMessage;
181
+ private pairingMessage;
182
+ /**
183
+ * The guard could not ESTABLISH the state it judges on, so it judged nothing.
184
+ *
185
+ * A sibling of allow() rather than a reason string passed to it, because the difference has to
186
+ * reach the LOG as a value: `ALLOW_FAIL_OPEN` vs `ALLOW`. It was previously a `' (fail-open)'`
187
+ * suffix on the free-text reason, which meant an abstention and a real approval were the same
188
+ * verdict and the abstentions could not be counted — so nobody could tell whether these guards
189
+ * were protecting anything or quietly standing down. Never block on data you could not
190
+ * establish; but say out loud, in a field, that you did not establish it.
191
+ */
192
+ private failOpen;
193
+ private allow;
194
+ private block;
195
+ private truncate;
196
+ private logDecision;
197
+ private currentBranch;
198
+ }
@@ -0,0 +1,363 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.StaleMainBashGuardRule = void 0;
4
+ const child_process_1 = require("child_process");
5
+ const rules_config_1 = require("@webpieces/rules-config");
6
+ const policy_keys_1 = require("../../policy-keys");
7
+ const main_sync_guard_configs_1 = require("../../configs/main-sync-guard-configs");
8
+ const repo_workflow_core_1 = require("@webpieces/repo-workflow-core");
9
+ const hook_runtime_1 = require("@webpieces/hook-runtime");
10
+ const hook_runtime_2 = require("@webpieces/hook-runtime");
11
+ const hook_runtime_3 = require("@webpieces/hook-runtime");
12
+ const to_error_1 = require("@webpieces/tooling-common/to-error");
13
+ const main_sync_refresh_1 = require("../main-sync-refresh");
14
+ const main_sync_timeout_1 = require("../main-sync-timeout");
15
+ const decision_log_1 = require("../decision-log");
16
+ const l2_matrix_doc_1 = require("../l2-matrix-doc");
17
+ const rules_config_2 = require("@webpieces/rules-config");
18
+ const hook_runtime_4 = require("@webpieces/hook-runtime");
19
+ const tree_recovery_1 = require("./tree-recovery");
20
+ const branch_switch_scan_1 = require("./branch-switch-scan");
21
+ const recovery_allowlist_1 = require("./recovery-allowlist");
22
+ const main_freshness_1 = require("./main-freshness");
23
+ const cure_prefix_scan_1 = require("./cure-prefix-scan");
24
+ /**
25
+ * The BASH half of the STALE-MAIN protection (read-stale-guard's State A), in two halves of its own:
26
+ * a PREVENTIVE check that stops a session landing on a stale `main`, and the REACTIVE check that
27
+ * contains the damage once it is already there.
28
+ *
29
+ * ── PREVENTIVE: a bare `git checkout main` is blocked; the pull must ride along ──────────────────
30
+ *
31
+ * Everything below this paragraph fires only once the session is ALREADY sitting on a stale `main`.
32
+ * Nothing stopped it ARRIVING there, and arriving is one keystroke. In the incident that added this
33
+ * half, an agent ran `git checkout main` after a merge, in a clone whose local `main` was **157
34
+ * commits behind** origin. That checkout did not merely produce stale files — it reverted:
35
+ *
36
+ * 1. `package.json`'s `@webpieces` pin, to a version OLDER than the installed `node_modules`;
37
+ * 2. `.claude/webpieces/ai-hook.sh` — the version-drift guard ITSELF — to a 157-commit-old copy
38
+ * whose message stated the drift BACKWARDS ("your installed webpieces is older than required")
39
+ * and named a single cure, `pnpm install`;
40
+ * 3. and so the agent's judgment: it ran that `pnpm install`, DOWNGRADING `node_modules` to match
41
+ * the stale pin, and had to undo it with the `git pull` that should have come first.
42
+ *
43
+ * The shim on current main already diagnoses drift correctly — it distinguishes "the pin is newer"
44
+ * from "the pin is stale, and `pnpm install` would downgrade you". None of that helped, because the
45
+ * checkout had replaced the shim with the version that could not say it. **A guard a stale checkout
46
+ * can revert cannot be relied on to catch a stale checkout**, which is why this check is preventive
47
+ * and why it lives here rather than in a second rule: same failure, one step earlier, one switch.
48
+ *
49
+ * It matches on command TEXT alone and asks git nothing. That is not laziness — this runs BEFORE the
50
+ * checkout, so the only `main` it could measure is the one it is about to leave. The interesting
51
+ * `main` does not exist yet, and consulting HEAD-at-hook-time is the exact trap
52
+ * `redirect-how-to-merge-main` documents at length. Pairing is unconditionally correct instead: when
53
+ * `main` is already current the chained pull is a sub-second no-op, so no exception is worth carving.
54
+ *
55
+ * BLOCKED `git checkout main`, `git switch main` — with or without flags — when no `git pull`
56
+ * appears anywhere in the SAME command.
57
+ * ALLOWED `git checkout main && git pull origin main`, the pairing this forces — and
58
+ * `pnpm wp-sync-main`, which IS that pairing with the cleanup and the
59
+ * orphan-directory sweep welded on. The message prescribes the one command; the raw pair
60
+ * stays legal because it is plain git and because it is the L0 recovery cure, where
61
+ * `node_modules` is the thing in doubt and no `pnpm` bin can be relied on.
62
+ * ALLOWED `git checkout -b <x> origin/main` (current by construction), `git checkout <sha>`,
63
+ * `git checkout -- <file>`, and any other branch.
64
+ *
65
+ * ── ROWS 6/7: the block fires only beyond the configured stale threshold ────────────────────
66
+ *
67
+ * The finding is not "you are on `main`" — it is **"what you would read here is out of date"**. So the
68
+ * ladder below asks the main-sync cache, exactly as read-stale-guard's State A does, and BLOCKS only
69
+ * when cached `commitsBehind` is greater than `maxCommitsBehind`. Unknown → allow. At or below
70
+ * the threshold → allow. The detached refresher computes the count; this hot path never does.
71
+ *
72
+ * WHY, when this guard spent a release judging the branch alone: because the branch alone denies
73
+ * everything off a narrow allowlist on a PERFECTLY CURRENT `main`, and a current `main` is exactly
74
+ * where the prescribed cure leaves you. An agent lands a PR, runs `pnpm wp-sync-main` — the
75
+ * command this repo tells it to run — and the next `curl`, `gh pr close` or test run is refused by a
76
+ * guard whose own name says STALE. The tool that got it there could not be the cure for being there,
77
+ * and the refusal had nothing to do with staleness, which is the confusion reported from the field.
78
+ *
79
+ * THE ASYMMETRY WITH `E` IS DELIBERATE, and the docblocks that argued `B` should track `E` were right
80
+ * about the mechanism and wrong about the policy. A WRITE on `main` creates work in the wrong place
81
+ * whatever `main`'s freshness — unreviewable, and unrevertable as a unit — so feature-branch-guard
82
+ * stays unconditional and keeps its one `git rev-parse`. A READ or a BUILD on a CURRENT `main` harms
83
+ * nothing, and blocking it strands the agent at the exact moment the prescribed cure put it there.
84
+ * Same tree, different hazard, so one precondition was never right for both.
85
+ *
86
+ * THE ANCESTRY TEST, NOT HASH EQUALITY. `MainFreshness.containsOriginMain` asks "does local `main`
87
+ * already contain the cached `origin/main`?", so the block lifts the instant a pull lands rather than
88
+ * waiting for the detached refresher to catch up. It is the SAME object read-stale-guard uses — one
89
+ * implementation, so the Read and Bash halves of one state can never disagree about whether the pull
90
+ * took.
91
+ *
92
+ * FAIL-OPEN ON EVERYTHING NOT ESTABLISHED, logged as `ALLOW_FAIL_OPEN` so abstentions stay countable:
93
+ * no cache (the first call of every session), a cache for another branch, an empty `originMain`
94
+ * (offline), no local `main` at all (fresh clone / worktree), branch undeterminable. The refresher is
95
+ * fired detached on every call to keep the cache warm for the NEXT one; it is never waited on, and no
96
+ * synchronous `git fetch` is ever run on the blocking path.
97
+ *
98
+ * THE POLARITY INSIDE THE BLOCKED STATE IS UNCHANGED: default-DENY plus row 4's skip list, the shape
99
+ * merged-branch-bash-guard uses for state B, via the same shared RecoveryAllowlist. A content-read
100
+ * BLOCKLIST could not replace it — enumerating readers catches `cat` and `grep`, and structurally
101
+ * cannot catch `pnpm install`, `npx expo install`, a formatter, codegen or a `>` redirect: commands
102
+ * whose stated purpose is something else and whose effect is to modify tracked files. What changed is
103
+ * WHEN that polarity applies, not the polarity.
104
+ *
105
+ * BLOCKED on a `main` known beyond the configured threshold: anything not on the skip list — builds, tests,
106
+ * installers, formatters, codegen, `cat`/`grep`/`ls` of the tree, git writes.
107
+ * ALLOWED every command on a `main` that is current or whose freshness is unknown — and, in the
108
+ * blocked state, everything that gets you OUT or tells you where you are:
109
+ * `git checkout -b <new> origin/main`, `git switch`, `git pull`/`fetch`,
110
+ * `git status|log|diff|show|branch`, `git stash`, `gh` (it talks to GitHub, not to this
111
+ * tree), `curl`/`wget`, every `wp-*` bin, installs.
112
+ *
113
+ * ── ROWS 12/13: the cure may be COMPOSED with the work, but only with `&&` ───────────────────────
114
+ *
115
+ * `pnpm wp-sync-main && cat src/app.ts` is allowed and `pnpm wp-sync-main ; cat
116
+ * src/app.ts` is not, and the difference is the shell's rather than this guard's: `&&` short-circuits,
117
+ * so the work cannot run when the cure failed — the exact property the block is here to guarantee. `;`
118
+ * discards the exit code and runs the work anyway. See cure-prefix-scan.ts for the measured shapes.
119
+ *
120
+ * There is no dirty-tree valve here and none in read-stale-guard either: the cure is
121
+ * `git checkout -b`, which CARRIES uncommitted work onto the new branch, so a dirty tree traps nobody
122
+ * in any L2 state. (`git stash` covers the residual where origin/main touched the same files.)
123
+ */
124
+ class StaleMainBashGuardRule extends hook_runtime_2.BashRuleBase {
125
+ constructor(config) { super(config, 'stale-main-bash-guard', policy_keys_1.BRANCH_STATE_GUARD_KEY); }
126
+ scanner = new hook_runtime_4.CommandScanner();
127
+ recovery = new tree_recovery_1.TreeRecovery();
128
+ switches = new branch_switch_scan_1.BranchSwitchScan(this.scanner);
129
+ // ROW 4, the skip list — the SAME instance-shape merged-branch-bash-guard uses, so the two states
130
+ // cannot drift apart about what "gets you out" means. See recovery-allowlist.ts.
131
+ recoveryList = new recovery_allowlist_1.RecoveryAllowlist(this.scanner);
132
+ // The ancestry test and the cache summary, shared with read-stale-guard — see main-freshness.ts.
133
+ freshness = new main_freshness_1.MainFreshness();
134
+ // ROWS 12/13 — `<cure> && <work>` vs `<cure> ; <work>`. See cure-prefix-scan.ts.
135
+ curePrefix = new cure_prefix_scan_1.CurePrefixScan(this.scanner);
136
+ description = 'Block a bare `git checkout main` (use `pnpm wp-sync-main`, or chain the pull into ' +
137
+ 'the same command), and — once local main is beyond maxCommitsBehind — block Bash ' +
138
+ 'there, allowlisting only the commands that get you off it. A main that is current, or whose ' +
139
+ 'freshness is unknown, is left alone.';
140
+ defaultOptions = {
141
+ hangTimeoutMinutes: repo_workflow_core_1.DEFAULT_HANG_TIMEOUT_MINUTES,
142
+ };
143
+ fixHint = new hook_runtime_3.FixHint('Landing on `main` without pulling, or working on `main` at all, both put your work somewhere it does not belong.', 'Get onto a feature branch, or go to main with the one command that pulls it too:', [
144
+ // TREE-SHAPED, from the one source of tree-shaped cures. A static rule-level hint has no
145
+ // workspace root, so it renders the 'unknown' kind — TreeRecovery's deliberate answer for
146
+ // "we cannot detect the tree": both forms, each labelled. That matters here because the
147
+ // primary-clone form goes to `main`, and a linked worktree has no `main` to go to — it is
148
+ // checked out in the primary clone — so a preferred option naming it unconditionally hands
149
+ // the AI a cure that cannot work where it is standing. The per-block message
150
+ // (pairingMessage) is detected and prints exactly one form; this is the fallback for the
151
+ // hint that cannot look.
152
+ new rules_config_1.Option(this.recovery.updateMainSteps('unknown').join('\n')
153
+ + '\nIf you hand-roll the git instead, the pull must be in the SAME command as the checkout.', true),
154
+ new rules_config_1.Option('Already on main: pnpm wp-sync-main (then re-run) — it pulls main and takes the trash out in the one command this repo prescribes. You may chain your command onto it with && (pnpm wp-sync-main && <your command>), which is skipped if the pull fails; a ; instead runs your command anyway and is refused.'),
155
+ new rules_config_1.Option('Still allowed: every BASH command, on a main at or below branch-state-guard.maxCommitsBehind or whose commit distance is not known. (Write/Edit on main is a different policy and is blocked by feature-branch-guard however current main is.) Beyond that threshold you keep the commands that get you OUT or tell you where you are: git checkout -b <new> origin/main, git switch, git pull/fetch, git status|log|diff|show|branch, git stash, gh, curl/wget, every wp-* bin, installs, and reading webpieces.config.json.'),
156
+ new rules_config_1.Option('Disable in webpieces.config.json under hookGuards → branch-state-guard (mode OFF) if intentional — that one key governs the Write, Read and Bash halves of this policy together.'),
157
+ ]);
158
+ check(ctx) {
159
+ // PREVENTIVE half, FIRST and unconditional. Deliberately ahead of every fail-open bailout
160
+ // below: those all ask "is the main we are ON stale?", and this asks about the main we are
161
+ // about to MOVE TO — a different branch, and one no cache can describe yet.
162
+ const bare = this.bareCheckoutOfMain(ctx);
163
+ if (bare !== null) {
164
+ return this.block(ctx, 'any', `bare checkout of main (${bare})`, this.pairingMessage(ctx), '-');
165
+ }
166
+ const branch = this.currentBranch(ctx.workspaceRoot);
167
+ if (branch === null)
168
+ return this.failOpen(ctx, branch, 'branch-undeterminable');
169
+ // Keep the shared cache warm for the next call. Detached; never blocks this command.
170
+ (0, main_sync_refresh_1.triggerMainSyncRefresh)(ctx.workspaceRoot, (0, main_sync_timeout_1.hangTimeoutOf)(this.config));
171
+ // State A is on `main` only. A merged feature branch is merged-branch-bash-guard's job.
172
+ if (branch !== 'main')
173
+ return this.allow(ctx, branch, 'not-on-main (state B is another guard)');
174
+ // ROW 4 — the skip list, ahead of the block, so no command that gets you OUT is ever denied.
175
+ if (this.recoveryList.isFullyRecovery(ctx)) {
176
+ return this.allow(ctx, branch, 'not-a-content-read (cure/build/metadata)');
177
+ }
178
+ return this.checkFreshness(ctx, branch);
179
+ }
180
+ /**
181
+ * ROWS 6/7 — block ONLY when cached `commitsBehind` exceeds `maxCommitsBehind`.
182
+ *
183
+ * Read this beside read-stale-guard.checkStaleMain: it is the same ladder over the same cache, and
184
+ * that is on purpose — the Read and the Bash halves of one state must not disagree about whether
185
+ * `main` is stale. What differs is the VERDICT SHAPE once it is stale, because a Read names one
186
+ * file and a Bash command is opaque: the Read is judged per file, Bash is default-deny plus the
187
+ * row 4 skip list already applied above.
188
+ *
189
+ * Every exit that is not "established BEHIND" is an ALLOW, and the not-established ones are
190
+ * `ALLOW_FAIL_OPEN` so they stay countable. A guard that cannot see the state judges nothing.
191
+ */
192
+ checkFreshness(ctx, branch) {
193
+ const status = (0, repo_workflow_core_1.readMainSyncStatus)(ctx.workspaceRoot, 'main');
194
+ // The first call of every session, and every call while another worktree holds the refresh
195
+ // lock. The refresher fired above populates it for the NEXT call; nothing waits here.
196
+ if (status === null)
197
+ return this.failOpen(ctx, branch, 'no-sync-cache', 'cache=none');
198
+ const cache = this.freshness.summarize(status);
199
+ // BELT-AND-BRACES since the cache became branch-keyed: we asked for the 'main' entry BY KEY, so
200
+ // a mismatch means the map's key and the entry's own `branch` disagree — a shape bug. Kept so
201
+ // that degrades to an allow. Unreachable in normal operation.
202
+ if (status.branch !== 'main')
203
+ return this.failOpen(ctx, branch, 'stale-cross-branch-cache', cache);
204
+ // Offline / origin unresolvable, or no local main to compare against.
205
+ if (status.originMain === '')
206
+ return this.failOpen(ctx, branch, 'origin-main-unknown', cache);
207
+ // ANCESTRY, not equality — the line that makes a pull take effect immediately. See
208
+ // MainFreshness.containsOriginMain.
209
+ if (this.freshness.containsOriginMain(ctx.workspaceRoot, status.originMain)) {
210
+ return this.allow(ctx, branch, 'local-main-contains-origin (up to date)', cache);
211
+ }
212
+ const maxCommitsBehind = this.config.maxCommitsBehind ?? main_sync_guard_configs_1.DEFAULT_MAX_COMMITS_BEHIND;
213
+ const withinThreshold = this.freshness.isWithinAllowedDrift(status, maxCommitsBehind);
214
+ if (withinThreshold === null)
215
+ return this.failOpen(ctx, branch, 'commit-distance-unknown', cache);
216
+ if (withinThreshold)
217
+ return this.allow(ctx, branch, 'within-max-commits-behind', cache);
218
+ // ESTABLISHED BEYOND THE CONFIGURED THRESHOLD. Only now does default-deny apply.
219
+ return this.judgeComposition(ctx, branch, cache, status.commitsBehind ?? 0, maxCommitsBehind);
220
+ }
221
+ /**
222
+ * ROWS 12/13 — `<cure> && <work>` is allowed; `<cure> ; <work>` is not.
223
+ *
224
+ * The distinction is the shell's, not this guard's invention. `&&` short-circuits, so the work
225
+ * cannot run when the cure exits non-zero — which is precisely the property the block exists to
226
+ * guarantee, already enforced by the interpreter. Refusing it bought nothing and cost a round
227
+ * trip, and the fleet audit files that as a TOOLING defect.
228
+ *
229
+ * `;` discards the exit code and runs the work regardless, and it was measured with
230
+ * `>/dev/null 2>&1` on the cure in 7 of 9 observed cases — so the failure was invisible as well as
231
+ * ignored. The two-step is genuinely safer there: the NEXT tool call is a fresh evaluation that
232
+ * recomputes `localMain` against `originMain`, so a pull that failed re-blocks. An allowed `;`
233
+ * compound never gets that second look.
234
+ */
235
+ judgeComposition(ctx, branch, cache, commitsBehind, maxCommitsBehind) {
236
+ const prefix = this.curePrefix.classify(ctx.command);
237
+ if (prefix.kind === 'short-circuits') {
238
+ return this.allow(ctx, branch, 'cure-prefixed, && short-circuits the work', cache);
239
+ }
240
+ if (prefix.kind === 'runs-anyway') {
241
+ return this.block(ctx, branch, 'cure-prefixed, work runs anyway', this.compositionMessage(prefix), cache);
242
+ }
243
+ return this.block(ctx, branch, 'on-stale-main', this.staleMainMessage(ctx.workspaceRoot, commitsBehind, maxCommitsBehind), cache);
244
+ }
245
+ /**
246
+ * The first segment that switches to the `main` BRANCH with no `git pull` anywhere in the same
247
+ * command, or null. The pull is looked for across the WHOLE command, not the matched segment,
248
+ * because `git checkout main && git pull origin main` splits into two segments and the pairing is
249
+ * the point.
250
+ */
251
+ bareCheckoutOfMain(ctx) {
252
+ for (const segment of this.scanner.commandSegments(ctx.command)) {
253
+ // BranchSwitchScan answers "which branch does this land on" for both guards, flag-tolerantly:
254
+ // `git checkout -q main` lands on main exactly as the bare form does, while
255
+ // `git checkout -b x origin/main` (creates), `git checkout -- main` (pathspec) and
256
+ // `git checkout <sha>` do not. See branch-switch-scan.ts for why that lives in one place.
257
+ if (!this.switches.landsOnExistingMain(segment))
258
+ continue;
259
+ return this.scanner.commandInvokesAnyGit(ctx.command, ['pull']) ? null : segment;
260
+ }
261
+ return null;
262
+ }
263
+ /**
264
+ * The stale-`main` deny. Deliberately SHORT, and now deliberately ABOUT STALENESS — which is what
265
+ * the guard's name promised all along.
266
+ *
267
+ * The two versions before this one are both instructive. The oldest opened with how many commits
268
+ * behind `main` was, which invited the wrong cure: an agent that reads "behind" reaches for a pull,
269
+ * lands on a CURRENT `main`, and is still on `main`. The one after it swung the other way and said
270
+ * `main` is not a place to work "whether or not it is current" — true of a WRITE, but this guard
271
+ * does not see writes, and it made every refusal on a freshly-pulled `main` unanswerable.
272
+ *
273
+ * So the text says what is now actually true and nothing more: local `main` is BEHIND, so what you
274
+ * read here is out of date; Bash is default-deny in this state rather than a list of readers,
275
+ * because a command's stated purpose never says whether it also WRITES; and the branch cure fetches,
276
+ * so it makes the reads true as well as moving the work somewhere reviewable. Reading `main` to PLAN
277
+ * stays legitimate — on a CURRENT `main` nothing here fires at all.
278
+ *
279
+ * ONE cure, and it is the dirty-safe one, the same call feature-branch-guard made: `git checkout -b`
280
+ * carries uncommitted work onto the new branch. (Row 6 also lists the pull, and read-stale-guard
281
+ * prints it, because a Read really can be cured by staying put. A Bash session cannot — the next
282
+ * command is as likely to write as to read.)
283
+ */
284
+ staleMainMessage(workspaceRoot, commitsBehind, maxCommitsBehind) {
285
+ return `Blocked: local \`main\` is ${commitsBehind} commits behind origin/main, exceeding `
286
+ + `branch-state-guard.maxCommitsBehind=${maxCommitsBehind}, so what you would read here is out of `
287
+ + 'date and a plan built on it is built on code upstream has moved past. A CURRENT main is '
288
+ + 'not blocked — reading main to PLAN is fine, and this fires only once being behind is '
289
+ + 'established. Bash is default-deny in this state rather than a list of readers, because a '
290
+ + "command's stated purpose never says whether it also WRITES. The feature branch is the "
291
+ + 'unit of work in any case: reviewable, revertable — and the cure fetches, so it makes '
292
+ + 'your reads true as well as moving you off main.\n'
293
+ + `Start a branch (uncommitted work comes with you):\n cd '${workspaceRoot}' && git fetch origin main && git checkout -b <new-branch> origin/main`;
294
+ }
295
+ /**
296
+ * ROW 13's deny. It NAMES the operator the agent typed, because the fix is a one-character edit
297
+ * and an agent told only "use `&&`" has to diff the two spellings itself to find where.
298
+ */
299
+ compositionMessage(prefix) {
300
+ return `Your cure is joined with \`${prefix.operator}\` — the work runs even if the pull fails. `
301
+ + 'Use `&&` so it is skipped:\n'
302
+ + '\n pnpm wp-sync-main && <your command>\n\n'
303
+ + 'Or run the cure alone and re-issue your command in the next call.';
304
+ }
305
+ pairingMessage(ctx) {
306
+ const steps = this.recovery.updateMainSteps(this.recovery.kindOf(ctx.workspaceRoot)).join('\n');
307
+ // Deliberately SHORT. The incident that bought this guard (a main 157 commits behind; the
308
+ // downgrade the reverted shim then prescribed) is maintainer material and lives in the class
309
+ // docblock above — the reader of THIS text needs only what changes what they type.
310
+ return 'Blocked: a bare `git checkout main` lands you on whatever local `main` you last had — '
311
+ + 'stale files, plus a reverted @webpieces pin and guard shim, so the drift guard then '
312
+ + 'reports the drift BACKWARDS. Go to main with the one command that also pulls it:\n' + steps;
313
+ }
314
+ /**
315
+ * The guard could not ESTABLISH the state it judges on, so it judged nothing.
316
+ *
317
+ * A sibling of allow() rather than a reason string passed to it, because the difference has to
318
+ * reach the LOG as a value: `ALLOW_FAIL_OPEN` vs `ALLOW`. It was previously a `' (fail-open)'`
319
+ * suffix on the free-text reason, which meant an abstention and a real approval were the same
320
+ * verdict and the abstentions could not be counted — so nobody could tell whether these guards
321
+ * were protecting anything or quietly standing down. Never block on data you could not
322
+ * establish; but say out loud, in a field, that you did not establish it.
323
+ */
324
+ failOpen(ctx, branch, reason, cache = '-') {
325
+ this.logDecision(ctx, branch, 'ALLOW_FAIL_OPEN', reason, cache);
326
+ return [];
327
+ }
328
+ allow(ctx, branch, reason, cache = '-') {
329
+ this.logDecision(ctx, branch, 'ALLOW', reason, cache);
330
+ return [];
331
+ }
332
+ block(ctx, branch, reason, message, cache) {
333
+ this.logDecision(ctx, branch, 'BLOCK_AI_CURE', reason, cache);
334
+ // Deliver the matrix and name the row, the same way an L0 block does. The doc is written
335
+ // LAZILY here rather than up front: only a blocked agent needs it, and this is the one path
336
+ // that knows the row it should be opened at.
337
+ const row = (0, decision_log_1.matrixL2Row)(reason).row;
338
+ const pointer = (0, l2_matrix_doc_1.branchStateMatrixPointer)((0, l2_matrix_doc_1.writeBranchStateMatrixDoc)(ctx.workspaceRoot), row);
339
+ return [new hook_runtime_1.Violation(1, this.truncate(ctx.command), message + pointer)];
340
+ }
341
+ truncate(s) {
342
+ const MAX = 120;
343
+ return s.length <= MAX ? s : s.slice(0, MAX) + '…';
344
+ }
345
+ logDecision(ctx, branch, verdict, reason, cache) {
346
+ (0, decision_log_1.logGuardDecision)(ctx.workspaceRoot, new decision_log_1.GuardDecision('stale-main-bash-guard', 'Bash', ctx.command, branch ?? 'unknown', verdict, reason, cache, rules_config_2.L0_FAULT_NONE, (0, decision_log_1.matrixL2Row)(reason)));
347
+ }
348
+ currentBranch(workspaceRoot) {
349
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
350
+ try {
351
+ return (0, child_process_1.execSync)('git rev-parse --abbrev-ref HEAD', {
352
+ cwd: workspaceRoot, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'],
353
+ }).trim();
354
+ }
355
+ catch (err) {
356
+ const error = (0, to_error_1.toError)(err);
357
+ void error;
358
+ return null;
359
+ }
360
+ }
361
+ }
362
+ exports.StaleMainBashGuardRule = StaleMainBashGuardRule;
363
+ //# sourceMappingURL=stale-main-bash-guard.js.map