@webpieces/ai-hook-rules 0.4.838 → 0.4.840

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 (390) hide show
  1. package/README.md +12 -140
  2. package/package.json +7 -15
  3. package/src/adapters/hook-app-fixtures.d.ts +1 -1
  4. package/src/adapters/hook-app-fixtures.js +0 -8
  5. package/src/adapters/hook-app-fixtures.js.map +1 -1
  6. package/src/adapters/hook-core.d.ts +1 -21
  7. package/src/adapters/hook-core.js +22 -341
  8. package/src/adapters/hook-core.js.map +1 -1
  9. package/src/core/load-rules.d.ts +4 -39
  10. package/src/core/load-rules.js +15 -127
  11. package/src/core/load-rules.js.map +1 -1
  12. package/src/core/rules/catch-error-pattern.d.ts +3 -3
  13. package/src/core/rules/catch-error-pattern.js +13 -13
  14. package/src/core/rules/catch-error-pattern.js.map +1 -1
  15. package/src/core/rules/index.d.ts +1 -14
  16. package/src/core/rules/index.js +1 -17
  17. package/src/core/rules/index.js.map +1 -1
  18. package/src/core/rules/match-rule.d.ts +3 -3
  19. package/src/core/rules/match-rule.js +6 -6
  20. package/src/core/rules/match-rule.js.map +1 -1
  21. package/src/core/rules/max-file-lines.d.ts +3 -3
  22. package/src/core/rules/max-file-lines.js +7 -7
  23. package/src/core/rules/max-file-lines.js.map +1 -1
  24. package/src/core/rules/no-any-unknown.d.ts +3 -3
  25. package/src/core/rules/no-any-unknown.js +6 -6
  26. package/src/core/rules/no-any-unknown.js.map +1 -1
  27. package/src/core/rules/no-custom-css.d.ts +3 -3
  28. package/src/core/rules/no-custom-css.js +7 -7
  29. package/src/core/rules/no-custom-css.js.map +1 -1
  30. package/src/core/rules/no-destructure.d.ts +3 -3
  31. package/src/core/rules/no-destructure.js +7 -7
  32. package/src/core/rules/no-destructure.js.map +1 -1
  33. package/src/core/rules/no-implicit-any.d.ts +3 -3
  34. package/src/core/rules/no-implicit-any.js +6 -6
  35. package/src/core/rules/no-implicit-any.js.map +1 -1
  36. package/src/core/rules/no-js-files.d.ts +3 -3
  37. package/src/core/rules/no-js-files.js +6 -6
  38. package/src/core/rules/no-js-files.js.map +1 -1
  39. package/src/core/rules/no-process-exit-outside-main.d.ts +3 -3
  40. package/src/core/rules/no-process-exit-outside-main.js +7 -7
  41. package/src/core/rules/no-process-exit-outside-main.js.map +1 -1
  42. package/src/core/rules/no-symbol-di-tokens.d.ts +3 -3
  43. package/src/core/rules/no-symbol-di-tokens.js +7 -7
  44. package/src/core/rules/no-symbol-di-tokens.js.map +1 -1
  45. package/src/core/rules/no-unmanaged-exceptions.d.ts +3 -3
  46. package/src/core/rules/no-unmanaged-exceptions.js +9 -9
  47. package/src/core/rules/no-unmanaged-exceptions.js.map +1 -1
  48. package/src/core/rules/require-return-type.d.ts +3 -3
  49. package/src/core/rules/require-return-type.js +6 -6
  50. package/src/core/rules/require-return-type.js.map +1 -1
  51. package/src/core/rules/throw-cause-required.d.ts +3 -3
  52. package/src/core/rules/throw-cause-required.js +9 -9
  53. package/src/core/rules/throw-cause-required.js.map +1 -1
  54. package/src/core/rules/validate-ts-in-src.d.ts +3 -3
  55. package/src/core/rules/validate-ts-in-src.js +7 -7
  56. package/src/core/rules/validate-ts-in-src.js.map +1 -1
  57. package/src/core/runner.d.ts +10 -19
  58. package/src/core/runner.js +24 -622
  59. package/src/core/runner.js.map +1 -1
  60. package/src/index.d.ts +2 -15
  61. package/src/index.js +4 -54
  62. package/src/index.js.map +1 -1
  63. package/openclaw.plugin.json +0 -15
  64. package/src/adapters/agent-adapters.d.ts +0 -13
  65. package/src/adapters/agent-adapters.js +0 -23
  66. package/src/adapters/agent-adapters.js.map +0 -1
  67. package/src/adapters/agent-payload.d.ts +0 -48
  68. package/src/adapters/agent-payload.js +0 -30
  69. package/src/adapters/agent-payload.js.map +0 -1
  70. package/src/adapters/agent-response.d.ts +0 -5
  71. package/src/adapters/agent-response.js +0 -86
  72. package/src/adapters/agent-response.js.map +0 -1
  73. package/src/adapters/claude-code-adapter.d.ts +0 -26
  74. package/src/adapters/claude-code-adapter.js +0 -69
  75. package/src/adapters/claude-code-adapter.js.map +0 -1
  76. package/src/adapters/codex-adapter.d.ts +0 -19
  77. package/src/adapters/codex-adapter.js +0 -48
  78. package/src/adapters/codex-adapter.js.map +0 -1
  79. package/src/adapters/codex-subagent-guard.d.ts +0 -45
  80. package/src/adapters/codex-subagent-guard.js +0 -88
  81. package/src/adapters/codex-subagent-guard.js.map +0 -1
  82. package/src/adapters/detect-ai.d.ts +0 -70
  83. package/src/adapters/detect-ai.js +0 -82
  84. package/src/adapters/detect-ai.js.map +0 -1
  85. package/src/adapters/guards-hook.d.ts +0 -3
  86. package/src/adapters/guards-hook.js +0 -30
  87. package/src/adapters/guards-hook.js.map +0 -1
  88. package/src/adapters/openclaw-plugin.d.ts +0 -14
  89. package/src/adapters/openclaw-plugin.js +0 -87
  90. package/src/adapters/openclaw-plugin.js.map +0 -1
  91. package/src/adapters/review-identity-stamper.d.ts +0 -20
  92. package/src/adapters/review-identity-stamper.js +0 -34
  93. package/src/adapters/review-identity-stamper.js.map +0 -1
  94. package/src/bin/codex-trust.d.ts +0 -105
  95. package/src/bin/codex-trust.js +0 -205
  96. package/src/bin/codex-trust.js.map +0 -1
  97. package/src/bin/dev-hook-install.d.ts +0 -1
  98. package/src/bin/dev-hook-install.js +0 -82
  99. package/src/bin/dev-hook-install.js.map +0 -1
  100. package/src/bin/dev-hook-uninstall.d.ts +0 -1
  101. package/src/bin/dev-hook-uninstall.js +0 -45
  102. package/src/bin/dev-hook-uninstall.js.map +0 -1
  103. package/src/bin/hook-registration.d.ts +0 -429
  104. package/src/bin/hook-registration.js +0 -661
  105. package/src/bin/hook-registration.js.map +0 -1
  106. package/src/bin/install-entry.d.ts +0 -19
  107. package/src/bin/install-entry.js +0 -128
  108. package/src/bin/install-entry.js.map +0 -1
  109. package/src/bin/l0-allowlist.d.ts +0 -49
  110. package/src/bin/l0-allowlist.js +0 -528
  111. package/src/bin/l0-allowlist.js.map +0 -1
  112. package/src/bin/l0-codex-read.d.ts +0 -21
  113. package/src/bin/l0-codex-read.js +0 -109
  114. package/src/bin/l0-codex-read.js.map +0 -1
  115. package/src/bin/l0-decide.d.ts +0 -50
  116. package/src/bin/l0-decide.js +0 -103
  117. package/src/bin/l0-decide.js.map +0 -1
  118. package/src/bin/l0-entry.d.ts +0 -103
  119. package/src/bin/l0-entry.js +0 -98
  120. package/src/bin/l0-entry.js.map +0 -1
  121. package/src/bin/l0-ignored-tools.d.ts +0 -38
  122. package/src/bin/l0-ignored-tools.js +0 -44
  123. package/src/bin/l0-ignored-tools.js.map +0 -1
  124. package/src/bin/managed-env.d.ts +0 -46
  125. package/src/bin/managed-env.js +0 -50
  126. package/src/bin/managed-env.js.map +0 -1
  127. package/src/bin/neighbour-hooks.d.ts +0 -42
  128. package/src/bin/neighbour-hooks.js +0 -177
  129. package/src/bin/neighbour-hooks.js.map +0 -1
  130. package/src/bin/reviewer-agent.d.ts +0 -19
  131. package/src/bin/reviewer-agent.js +0 -135
  132. package/src/bin/reviewer-agent.js.map +0 -1
  133. package/src/bin/settings-shape.d.ts +0 -37
  134. package/src/bin/settings-shape.js +0 -17
  135. package/src/bin/settings-shape.js.map +0 -1
  136. package/src/bin/setup-config.d.ts +0 -19
  137. package/src/bin/setup-config.js +0 -370
  138. package/src/bin/setup-config.js.map +0 -1
  139. package/src/bin/setup.d.ts +0 -78
  140. package/src/bin/setup.js +0 -400
  141. package/src/bin/setup.js.map +0 -1
  142. package/src/bin/shim-audit-log.d.ts +0 -119
  143. package/src/bin/shim-audit-log.js +0 -286
  144. package/src/bin/shim-audit-log.js.map +0 -1
  145. package/src/bin/shim-deny-reason.d.ts +0 -1
  146. package/src/bin/shim-deny-reason.js +0 -244
  147. package/src/bin/shim-deny-reason.js.map +0 -1
  148. package/src/bin/shim-drift-fix.d.ts +0 -1
  149. package/src/bin/shim-drift-fix.js +0 -72
  150. package/src/bin/shim-drift-fix.js.map +0 -1
  151. package/src/bin/shim-testkit.d.ts +0 -107
  152. package/src/bin/shim-testkit.js +0 -197
  153. package/src/bin/shim-testkit.js.map +0 -1
  154. package/src/bin/shim-version-drift.d.ts +0 -1
  155. package/src/bin/shim-version-drift.js +0 -164
  156. package/src/bin/shim-version-drift.js.map +0 -1
  157. package/src/bin/shim.d.ts +0 -16
  158. package/src/bin/shim.js +0 -636
  159. package/src/bin/shim.js.map +0 -1
  160. package/src/bin/upgrade-shim.d.ts +0 -18
  161. package/src/bin/upgrade-shim.js +0 -283
  162. package/src/bin/upgrade-shim.js.map +0 -1
  163. package/src/core/ai-type-context.d.ts +0 -36
  164. package/src/core/ai-type-context.js +0 -45
  165. package/src/core/ai-type-context.js.map +0 -1
  166. package/src/core/apply-patch-parse.d.ts +0 -36
  167. package/src/core/apply-patch-parse.js +0 -154
  168. package/src/core/apply-patch-parse.js.map +0 -1
  169. package/src/core/build-context.d.ts +0 -10
  170. package/src/core/build-context.js +0 -66
  171. package/src/core/build-context.js.map +0 -1
  172. package/src/core/command-scan.d.ts +0 -122
  173. package/src/core/command-scan.js +0 -282
  174. package/src/core/command-scan.js.map +0 -1
  175. package/src/core/custom-rule-adapter.d.ts +0 -22
  176. package/src/core/custom-rule-adapter.js +0 -50
  177. package/src/core/custom-rule-adapter.js.map +0 -1
  178. package/src/core/decision-log.d.ts +0 -190
  179. package/src/core/decision-log.js +0 -406
  180. package/src/core/decision-log.js.map +0 -1
  181. package/src/core/delete-scoped-rules.d.ts +0 -8
  182. package/src/core/delete-scoped-rules.js +0 -31
  183. package/src/core/delete-scoped-rules.js.map +0 -1
  184. package/src/core/disable-directives.d.ts +0 -8
  185. package/src/core/disable-directives.js +0 -80
  186. package/src/core/disable-directives.js.map +0 -1
  187. package/src/core/effective-tree.d.ts +0 -204
  188. package/src/core/effective-tree.js +0 -277
  189. package/src/core/effective-tree.js.map +0 -1
  190. package/src/core/excluded-path-escape.d.ts +0 -101
  191. package/src/core/excluded-path-escape.js +0 -236
  192. package/src/core/excluded-path-escape.js.map +0 -1
  193. package/src/core/excluded-paths.d.ts +0 -23
  194. package/src/core/excluded-paths.js +0 -54
  195. package/src/core/excluded-paths.js.map +0 -1
  196. package/src/core/fix-hint.d.ts +0 -40
  197. package/src/core/fix-hint.js +0 -53
  198. package/src/core/fix-hint.js.map +0 -1
  199. package/src/core/force-to-root.d.ts +0 -32
  200. package/src/core/force-to-root.js +0 -60
  201. package/src/core/force-to-root.js.map +0 -1
  202. package/src/core/guard-index-doc.d.ts +0 -63
  203. package/src/core/guard-index-doc.js +0 -172
  204. package/src/core/guard-index-doc.js.map +0 -1
  205. package/src/core/instruct-ai-writer.d.ts +0 -1
  206. package/src/core/instruct-ai-writer.js +0 -6
  207. package/src/core/instruct-ai-writer.js.map +0 -1
  208. package/src/core/l0-fault-codes.d.ts +0 -85
  209. package/src/core/l0-fault-codes.js +0 -121
  210. package/src/core/l0-fault-codes.js.map +0 -1
  211. package/src/core/l0-matrix.d.ts +0 -114
  212. package/src/core/l0-matrix.js +0 -416
  213. package/src/core/l0-matrix.js.map +0 -1
  214. package/src/core/l0-tooling-doc.d.ts +0 -45
  215. package/src/core/l0-tooling-doc.js +0 -258
  216. package/src/core/l0-tooling-doc.js.map +0 -1
  217. package/src/core/l1-doc.d.ts +0 -7
  218. package/src/core/l1-doc.js +0 -340
  219. package/src/core/l1-doc.js.map +0 -1
  220. package/src/core/l1-matrix-doc.d.ts +0 -31
  221. package/src/core/l1-matrix-doc.js +0 -111
  222. package/src/core/l1-matrix-doc.js.map +0 -1
  223. package/src/core/l1-rows.d.ts +0 -167
  224. package/src/core/l1-rows.js +0 -262
  225. package/src/core/l1-rows.js.map +0 -1
  226. package/src/core/l2-doc.d.ts +0 -7
  227. package/src/core/l2-doc.js +0 -385
  228. package/src/core/l2-doc.js.map +0 -1
  229. package/src/core/l2-matrix-doc.d.ts +0 -23
  230. package/src/core/l2-matrix-doc.js +0 -72
  231. package/src/core/l2-matrix-doc.js.map +0 -1
  232. package/src/core/l2-row.d.ts +0 -54
  233. package/src/core/l2-row.js +0 -75
  234. package/src/core/l2-row.js.map +0 -1
  235. package/src/core/l2-rows.d.ts +0 -56
  236. package/src/core/l2-rows.js +0 -272
  237. package/src/core/l2-rows.js.map +0 -1
  238. package/src/core/load-config.d.ts +0 -1
  239. package/src/core/load-config.js +0 -9
  240. package/src/core/load-config.js.map +0 -1
  241. package/src/core/log-stream.d.ts +0 -117
  242. package/src/core/log-stream.js +0 -156
  243. package/src/core/log-stream.js.map +0 -1
  244. package/src/core/log-streams.d.ts +0 -48
  245. package/src/core/log-streams.js +0 -55
  246. package/src/core/log-streams.js.map +0 -1
  247. package/src/core/log-target.d.ts +0 -21
  248. package/src/core/log-target.js +0 -29
  249. package/src/core/log-target.js.map +0 -1
  250. package/src/core/main-sync-log.d.ts +0 -16
  251. package/src/core/main-sync-log.js +0 -105
  252. package/src/core/main-sync-log.js.map +0 -1
  253. package/src/core/main-sync-refresh.d.ts +0 -39
  254. package/src/core/main-sync-refresh.js +0 -96
  255. package/src/core/main-sync-refresh.js.map +0 -1
  256. package/src/core/main-sync-timeout.d.ts +0 -32
  257. package/src/core/main-sync-timeout.js +0 -94
  258. package/src/core/main-sync-timeout.js.map +0 -1
  259. package/src/core/matrix-cures.d.ts +0 -12
  260. package/src/core/matrix-cures.js +0 -56
  261. package/src/core/matrix-cures.js.map +0 -1
  262. package/src/core/missing-directory.d.ts +0 -38
  263. package/src/core/missing-directory.js +0 -66
  264. package/src/core/missing-directory.js.map +0 -1
  265. package/src/core/read-only-inspection.d.ts +0 -34
  266. package/src/core/read-only-inspection.js +0 -88
  267. package/src/core/read-only-inspection.js.map +0 -1
  268. package/src/core/rejection-log.d.ts +0 -9
  269. package/src/core/rejection-log.js +0 -258
  270. package/src/core/rejection-log.js.map +0 -1
  271. package/src/core/report.d.ts +0 -21
  272. package/src/core/report.js +0 -73
  273. package/src/core/report.js.map +0 -1
  274. package/src/core/rule-base.d.ts +0 -39
  275. package/src/core/rule-base.js +0 -36
  276. package/src/core/rule-base.js.map +0 -1
  277. package/src/core/rules/branch-creation-guard.d.ts +0 -113
  278. package/src/core/rules/branch-creation-guard.js +0 -422
  279. package/src/core/rules/branch-creation-guard.js.map +0 -1
  280. package/src/core/rules/branch-switch-scan.d.ts +0 -43
  281. package/src/core/rules/branch-switch-scan.js +0 -132
  282. package/src/core/rules/branch-switch-scan.js.map +0 -1
  283. package/src/core/rules/build-output-pipe-guard.d.ts +0 -56
  284. package/src/core/rules/build-output-pipe-guard.js +0 -120
  285. package/src/core/rules/build-output-pipe-guard.js.map +0 -1
  286. package/src/core/rules/build-output-pipe-scan.d.ts +0 -47
  287. package/src/core/rules/build-output-pipe-scan.js +0 -84
  288. package/src/core/rules/build-output-pipe-scan.js.map +0 -1
  289. package/src/core/rules/cap-remedies.d.ts +0 -39
  290. package/src/core/rules/cap-remedies.js +0 -59
  291. package/src/core/rules/cap-remedies.js.map +0 -1
  292. package/src/core/rules/commit-message-substitution-guard.d.ts +0 -72
  293. package/src/core/rules/commit-message-substitution-guard.js +0 -134
  294. package/src/core/rules/commit-message-substitution-guard.js.map +0 -1
  295. package/src/core/rules/commit-message-substitution-scan.d.ts +0 -42
  296. package/src/core/rules/commit-message-substitution-scan.js +0 -145
  297. package/src/core/rules/commit-message-substitution-scan.js.map +0 -1
  298. package/src/core/rules/content-read-scan.d.ts +0 -76
  299. package/src/core/rules/content-read-scan.js +0 -176
  300. package/src/core/rules/content-read-scan.js.map +0 -1
  301. package/src/core/rules/cure-prefix-scan.d.ts +0 -64
  302. package/src/core/rules/cure-prefix-scan.js +0 -133
  303. package/src/core/rules/cure-prefix-scan.js.map +0 -1
  304. package/src/core/rules/feature-branch-guard.d.ts +0 -121
  305. package/src/core/rules/feature-branch-guard.js +0 -326
  306. package/src/core/rules/feature-branch-guard.js.map +0 -1
  307. package/src/core/rules/judged-tree.d.ts +0 -66
  308. package/src/core/rules/judged-tree.js +0 -97
  309. package/src/core/rules/judged-tree.js.map +0 -1
  310. package/src/core/rules/main-freshness.d.ts +0 -37
  311. package/src/core/rules/main-freshness.js +0 -61
  312. package/src/core/rules/main-freshness.js.map +0 -1
  313. package/src/core/rules/merge-in-progress-guard.d.ts +0 -17
  314. package/src/core/rules/merge-in-progress-guard.js +0 -122
  315. package/src/core/rules/merge-in-progress-guard.js.map +0 -1
  316. package/src/core/rules/merged-branch-bash-guard.d.ts +0 -62
  317. package/src/core/rules/merged-branch-bash-guard.js +0 -170
  318. package/src/core/rules/merged-branch-bash-guard.js.map +0 -1
  319. package/src/core/rules/merged-branch-message.d.ts +0 -59
  320. package/src/core/rules/merged-branch-message.js +0 -137
  321. package/src/core/rules/merged-branch-message.js.map +0 -1
  322. package/src/core/rules/pr-creation-or-push-guard.d.ts +0 -26
  323. package/src/core/rules/pr-creation-or-push-guard.js +0 -146
  324. package/src/core/rules/pr-creation-or-push-guard.js.map +0 -1
  325. package/src/core/rules/pr-merge-guard.d.ts +0 -36
  326. package/src/core/rules/pr-merge-guard.js +0 -86
  327. package/src/core/rules/pr-merge-guard.js.map +0 -1
  328. package/src/core/rules/read-stale-guard.d.ts +0 -136
  329. package/src/core/rules/read-stale-guard.js +0 -326
  330. package/src/core/rules/read-stale-guard.js.map +0 -1
  331. package/src/core/rules/recovery-allowlist.d.ts +0 -49
  332. package/src/core/rules/recovery-allowlist.js +0 -187
  333. package/src/core/rules/recovery-allowlist.js.map +0 -1
  334. package/src/core/rules/redirect-how-to-merge-main.d.ts +0 -16
  335. package/src/core/rules/redirect-how-to-merge-main.js +0 -157
  336. package/src/core/rules/redirect-how-to-merge-main.js.map +0 -1
  337. package/src/core/rules/shell-segment-scan.d.ts +0 -64
  338. package/src/core/rules/shell-segment-scan.js +0 -88
  339. package/src/core/rules/shell-segment-scan.js.map +0 -1
  340. package/src/core/rules/stale-main-bash-guard.d.ts +0 -198
  341. package/src/core/rules/stale-main-bash-guard.js +0 -361
  342. package/src/core/rules/stale-main-bash-guard.js.map +0 -1
  343. package/src/core/rules/stale-main-message.d.ts +0 -62
  344. package/src/core/rules/stale-main-message.js +0 -102
  345. package/src/core/rules/stale-main-message.js.map +0 -1
  346. package/src/core/rules/tree-recovery.d.ts +0 -92
  347. package/src/core/rules/tree-recovery.js +0 -165
  348. package/src/core/rules/tree-recovery.js.map +0 -1
  349. package/src/core/rules/wait-spin-guard.d.ts +0 -128
  350. package/src/core/rules/wait-spin-guard.js +0 -211
  351. package/src/core/rules/wait-spin-guard.js.map +0 -1
  352. package/src/core/rules/wait-spin-scan.d.ts +0 -118
  353. package/src/core/rules/wait-spin-scan.js +0 -203
  354. package/src/core/rules/wait-spin-scan.js.map +0 -1
  355. package/src/core/rules/whole-repo-build-guard.d.ts +0 -125
  356. package/src/core/rules/whole-repo-build-guard.js +0 -257
  357. package/src/core/rules/whole-repo-build-guard.js.map +0 -1
  358. package/src/core/rules/whole-repo-build-scan.d.ts +0 -28
  359. package/src/core/rules/whole-repo-build-scan.js +0 -198
  360. package/src/core/rules/whole-repo-build-scan.js.map +0 -1
  361. package/src/core/session-call-history.d.ts +0 -44
  362. package/src/core/session-call-history.js +0 -79
  363. package/src/core/session-call-history.js.map +0 -1
  364. package/src/core/shell-read-parity.d.ts +0 -56
  365. package/src/core/shell-read-parity.js +0 -155
  366. package/src/core/shell-read-parity.js.map +0 -1
  367. package/src/core/strip-ts-noise.d.ts +0 -1
  368. package/src/core/strip-ts-noise.js +0 -185
  369. package/src/core/strip-ts-noise.js.map +0 -1
  370. package/src/core/sync-main.d.ts +0 -46
  371. package/src/core/sync-main.js +0 -175
  372. package/src/core/sync-main.js.map +0 -1
  373. package/src/core/target-tree.d.ts +0 -84
  374. package/src/core/target-tree.js +0 -148
  375. package/src/core/target-tree.js.map +0 -1
  376. package/src/core/to-error.d.ts +0 -5
  377. package/src/core/to-error.js +0 -37
  378. package/src/core/to-error.js.map +0 -1
  379. package/src/core/types.d.ts +0 -152
  380. package/src/core/types.js +0 -200
  381. package/src/core/types.js.map +0 -1
  382. package/src/core/version-sync.d.ts +0 -219
  383. package/src/core/version-sync.js +0 -558
  384. package/src/core/version-sync.js.map +0 -1
  385. package/src/core/webpieces-versions.d.ts +0 -98
  386. package/src/core/webpieces-versions.js +0 -206
  387. package/src/core/webpieces-versions.js.map +0 -1
  388. package/templates/ai-hook.sh +0 -497
  389. package/templates/claude-settings-hook.json +0 -28
  390. package/templates/webpieces-reviewer.md +0 -60
@@ -1,113 +0,0 @@
1
- import { BranchCreationGuardConfig } from '@webpieces/rules-config';
2
- import type { BashContext, Violation } from '../types';
3
- import { BashRuleBase } from '../rule-base';
4
- import { FixHint } from '../fix-hint';
5
- export declare class BranchCreationGuardRule extends BashRuleBase<BranchCreationGuardConfig> {
6
- constructor(config: BranchCreationGuardConfig);
7
- readonly description: string;
8
- readonly defaultOptions: {
9
- branchFormat: string;
10
- maxLocalBranches: number;
11
- maxWorktrees: number;
12
- };
13
- private readonly worktrees;
14
- private readonly mergedBranches;
15
- private readonly branchIdentity;
16
- private capCache;
17
- private worktreeCapCache;
18
- private worktreeAdd;
19
- private get branchFormat();
20
- private get subBranchNaming();
21
- private get maxLocalBranches();
22
- private get maxWorktrees();
23
- private freshMainCommand;
24
- get fixHint(): FixHint;
25
- /**
26
- * Strip the parts of a shell command that are DATA rather than executable commands, so the guard
27
- * stops reading prose as instructions.
28
- *
29
- * This guard regex-scans the raw command string and has no notion of quoting, so
30
- * `git commit -m "... git checkout -b foo ..."` — or any heredoc commit message that mentions a
31
- * branch command — was parsed as an actual branch creation and blocked. That bit three separate
32
- * times while building the branch cap, including on the cap's own commit. It matters far more now
33
- * that the cap check runs BEFORE the origin/main allow: at the cap, a merely-MENTIONED branch
34
- * command would block your commit.
35
- *
36
- * A quoted span whose content has no whitespace is kept verbatim (it is a single token — the name
37
- * in `git checkout -b "dean/foo"`), so quoting a branch name cannot smuggle a creation past the
38
- * guard. Anything with whitespace inside quotes is prose, and collapses to a space.
39
- */
40
- check(ctx: BashContext): readonly Violation[];
41
- /**
42
- * `git worktree add ../dir <existing-branch>` onto a branch whose PR is ALREADY MERGED.
43
- *
44
- * The count caps never catch this: the command creates no branch, and if you are under the
45
- * worktree cap it sails straight through — materialising a fresh directory full of PRE-MERGE
46
- * code that the AI will then read, plan from and edit. read-stale-guard blocks the reads and
47
- * feature-branch-guard blocks the edits once you are in there, but that is a turn wasted per
48
- * tool call. Refuse at the moment of creation instead, using the SAME merged-PR proof the caps
49
- * already have precomputed on disk.
50
- *
51
- * Fails OPEN exactly like both caps: no cache (fresh clone, no `gh`, refresher hasn't run) or an
52
- * unparseable command → no opinion.
53
- */
54
- private checkWorktreeOntoDeadBranch;
55
- private checkReservedSuffix;
56
- /**
57
- * Both budgets, in the order that produces the most useful complaint.
58
- *
59
- * Called BEFORE the origin/main allow in check() — `... -b <name> origin/main` is the normal,
60
- * always-permitted path, so a cap checked after it would never once fire.
61
- *
62
- * Worktree cap first: a `git worktree add -b` spends BOTH budgets, and when both are full the
63
- * worktree is the thing the command was actually trying to make, so it is the thing to talk about.
64
- */
65
- private checkCaps;
66
- /**
67
- * The cap. Blocks branch #N+1 until already-merged branches are reaped, which is the ONLY thing
68
- * keeping the local branch list bounded.
69
- *
70
- * Fails OPEN when the cache is absent (fresh clone, `gh` unavailable, refresher hasn't run yet):
71
- * never block on data we don't have. The detached refresher regenerates it within one hook call,
72
- * so the cap starts enforcing on its own.
73
- */
74
- private checkBranchCap;
75
- /**
76
- * The cache, with entries for branches/worktrees that no longer exist dropped.
77
- *
78
- * Reconciling is the fix for the phantom count: the file is written by a detached refresher and is
79
- * DELIBERATELY allowed to go stale, so it keeps naming branches deleted minutes ago and worktrees
80
- * already removed. Quoting it verbatim is how the guard announced "8 parked local branches … none of
81
- * them are dead" over a repo that had ONE, and then blocked a legitimate `git worktree add` on that
82
- * figure. `reconcile` re-checks existence with instant local git reads; it does NOT re-derive any
83
- * verdict (that needs the network and belongs in the refresher).
84
- *
85
- * Its AGE is no longer read here. The cap messages stopped quoting verdict counts entirely, so
86
- * there is nothing left for a freshness caveat to qualify — `wp-cleanup` recomputes from scratch.
87
- */
88
- private loadReconciledCache;
89
- /**
90
- * The branch cap, yielding by ONE when the agent is standing on an already-merged branch.
91
- *
92
- * Two individually-correct guards were composing into a trap: merged-branch-bash-guard blocks
93
- * almost all Bash until you get off a merged branch, and the ONLY way off it that guard advertises
94
- * is creating a fresh branch — which this cap then refused. Every printed exit led to editing
95
- * webpieces.config.json, and that is what an unsupervised agent did.
96
- *
97
- * One over cap, and only while a merged branch is what is pushing you: the branch about to be
98
- * created replaces a branch that is already dead, so the steady-state count does not grow. The cap
99
- * still fires on the NEXT creation, so this defers the cleanup by exactly one branch, never skips it.
100
- *
101
- * Fails toward the strict cap: no cache, a cache for another branch, or a clean branch → no yield.
102
- */
103
- private effectiveBranchCap;
104
- private currentBranchOrNull;
105
- /**
106
- * The worktree cap — the second budget. Same gate, same fail-open rule as the branch cap: a
107
- * worktree list we cannot classify (no cache on disk) blocks nothing.
108
- *
109
- * Counts LINKED worktrees only. The primary clone is not a thing anyone can remove, so charging the
110
- * budget for it would just silently cost you one worktree.
111
- */
112
- private checkWorktreeCap;
113
- }
@@ -1,422 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.BranchCreationGuardRule = void 0;
4
- const child_process_1 = require("child_process");
5
- const rules_config_1 = require("@webpieces/rules-config");
6
- const repo_workflow_core_1 = require("@webpieces/repo-workflow-core");
7
- const types_1 = require("../types");
8
- const rule_base_1 = require("../rule-base");
9
- const fix_hint_1 = require("../fix-hint");
10
- const cap_remedies_1 = require("./cap-remedies");
11
- const to_error_1 = require("../to-error");
12
- // Defaults used when the rule has no explicit value in webpieces.config.json.
13
- // branchFormat is a human sentence telling the AI how to name a branch created off main; it is
14
- // intentionally NOT the sub-branch convention (sub-branches are a separate, human-approved path).
15
- const DEFAULT_BRANCH_FORMAT = 'Name it {whoami}/<short-feature-description> — lowercase, no version numbers, no sub/ prefix (e.g. dean/upgrade-webpieces)';
16
- // Hard cap on local feature branches. Enforced at CREATION because that is the one moment cleanup is
17
- // both cheap and obviously worth it — reaping happens over time, never "ASAP".
18
- //
19
- // The branch cap counts PARKED branches only — branches not checked out in any worktree. Worktree-held
20
- // branches are counted by the worktree cap instead. Two budgets, because they are not substitutes: if
21
- // held branches also spent the branch budget, five worktrees would leave room for zero branches and no
22
- // branch could ever be created again.
23
- const DEFAULT_MAX_LOCAL_BRANCHES = 5;
24
- const DEFAULT_MAX_WORKTREES = 5;
25
- // A plausible git ref name. Deliberately NOT `[^\s-]` — that class matches shell metacharacters, so
26
- // `git branch | wc -l` (a read-only LISTING, piped) was parsed as "create a branch named `|`" and
27
- // blocked. Cleanup work necessarily reads and deletes branches, so a listing must never trip this.
28
- const REF_NAME = String.raw `[A-Za-z0-9][A-Za-z0-9_./-]*`;
29
- const BRANCH_PATTERNS = [
30
- new RegExp(String.raw `git\s+checkout\s+-[bB]\s+(${REF_NAME})`),
31
- new RegExp(String.raw `git\s+switch\s+-[cC]\s+(${REF_NAME})`),
32
- new RegExp(String.raw `git\s+branch\s+(?!-)(${REF_NAME})`),
33
- // `git worktree add ../dir -b <name> origin/main` — the form docs/git-workflow.md recommends for
34
- // starting a feature. It creates a branch just as surely as `checkout -b` does, and until this
35
- // pattern existed it walked straight past the cap, the reserved-suffix check and the sub-branch
36
- // check. `(?:\S+\s+)*?` absorbs the path and any other flags, so the -b may precede or follow them.
37
- new RegExp(String.raw `git\s+worktree\s+add\s+(?:\S+\s+)*?-[bB]\s+(${REF_NAME})`),
38
- ];
39
- // ANY worktree creation, with or without -b. The no-`-b` forms (`git worktree add ../dir existing`,
40
- // `--detach`) create no branch but DO create a worktree, so they spend the worktree budget and must
41
- // still hit the cap.
42
- const WORKTREE_ADD = /git\s+worktree\s+add\b/;
43
- // `git worktree add <path> <existing-branch>` — the checkout-an-existing-branch form. Captures the
44
- // LAST bare (non-flag) argument, which is the committish; the first bare argument is the path.
45
- // Flags that take a value (`--reason <s>`, `-b <name>`) are excluded by the caller, which only uses
46
- // this on commands with no `-b`/`-B` at all.
47
- const WORKTREE_ADD_EXISTING = new RegExp(String.raw `git\s+worktree\s+add\s+(?:-{1,2}[A-Za-z-]+\s+)*\S+\s+(${REF_NAME})`);
48
- // `git branch <name> <sha>` — RESTORING a branch at an explicit commit, which is exactly the
49
- // `recover=` command wp-cleanup writes to branch-mutations.log for every branch it reaps.
50
- //
51
- // This must be allowed UNCONDITIONALLY, ahead of even the caps. The entire argument for letting the
52
- // tooling delete branches unattended is that any delete is one logged command away from being undone
53
- // — so a guard that blocks that command turns a real guarantee into a decorative one. (It did: the
54
- // generic `git branch <name>` creation pattern matched the restore and refused it, demanding the
55
- // branch be recreated off origin/main, which is precisely the content the restore is meant to bring
56
- // back.) A restore also cannot grow the branch list beyond what already existed.
57
- const RESTORE_AT_SHA = new RegExp(String.raw `git\s+branch\s+${REF_NAME}\s+[0-9a-f]{7,40}(?:\W|$)`);
58
- // A trailing `wp<number>` was the old squash-merge generation marker (base → basewp2 → basewp3).
59
- // The tooling NO LONGER produces it — a sync now lands back on the same feature name — but the suffix
60
- // stays RESERVED so a human branch can't collide with a leftover `…wpN` still floating in a consumer
61
- // repo mid-transition. Block it at creation time and steer the name back to the plain feature form.
62
- const RESERVED_GENERATION_SUFFIX = /wp\d+$/;
63
- // A branch-creation command that explicitly bases off origin/main (e.g. `git checkout -b feat
64
- // origin/main`). This is exactly the fresh-main base the guard wants, and it works from ANY current
65
- // branch or linked worktree — main need not (and in a worktree cannot) be checked out here. Allowed
66
- // unconditionally so the recovery messages can safely tell you to run it from a worktree.
67
- //
68
- // The trailing check is `\W|$`, not `\s|$`: the ALLOW pattern must not be stricter about delimiters
69
- // than the BLOCK pattern above, or a `git checkout -b x origin/main` that ends at a quote or backtick
70
- // is seen as a branch creation but NOT as an origin/main one — recognised, then wrongly blocked.
71
- const ORIGIN_MAIN_BASE = /git\s+(?:checkout\s+-[bB]|switch\s+-[cC])\s+\S+\s+origin\/main(?:\W|$)/;
72
- // The worktree arm of the same allow: `git worktree add ../dir -b <name> origin/main`. Same fresh-main
73
- // base, same reasoning — and in a worktree it is the ONLY workable base, since `git checkout main`
74
- // fatals there. Kept separate from ORIGIN_MAIN_BASE because the argument shape differs (a path sits
75
- // between the subcommand and the flags).
76
- const WORKTREE_ORIGIN_MAIN_BASE = /git\s+worktree\s+add\s+(?:\S+\s+)*origin\/main(?:\W|$)/;
77
- function extractBranchName(command) {
78
- for (const pattern of BRANCH_PATTERNS) {
79
- const m = pattern.exec(command);
80
- if (m)
81
- return m[1];
82
- }
83
- return null;
84
- }
85
- function truncate(s) {
86
- const MAX = 120;
87
- return s.length <= MAX ? s : s.slice(0, MAX) + '…';
88
- }
89
- function checkMainIsUpToDate(ctx, requestedName) {
90
- // `--no-write-fetch-head` for the same reason as the background refresher (see
91
- // MainSyncStatusService.fetchOriginMain): this refresh can run while the agent is mid
92
- // `git fetch`/`git pull`, and two overlapping writers of the unlocked `.git/FETCH_HEAD` can leave
93
- // a duplicate for-merge line that makes the agent's `git pull` fatal with "multiple branches". We
94
- // read `origin/main` below, never FETCH_HEAD. On a git too old for the flag, retry the plain form.
95
- // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
96
- try {
97
- (0, child_process_1.execSync)('git fetch --no-write-fetch-head origin main --quiet', {
98
- cwd: ctx.workspaceRoot,
99
- encoding: 'utf8',
100
- });
101
- }
102
- catch (err) {
103
- const error = (0, to_error_1.toError)(err);
104
- const text = error.message.toLowerCase();
105
- const tooOld = text.includes('unknown option') || text.includes('unknown switch') || text.includes('unrecognized option');
106
- if (!tooOld)
107
- throw error;
108
- (0, child_process_1.execSync)('git fetch origin main --quiet', { cwd: ctx.workspaceRoot, encoding: 'utf8' });
109
- }
110
- const countStr = (0, child_process_1.execSync)('git rev-list HEAD..origin/main --count', {
111
- cwd: ctx.workspaceRoot,
112
- encoding: 'utf8',
113
- }).trim();
114
- const count = parseInt(countStr, 10);
115
- if (count > 0) {
116
- return [new types_1.Violation(1, truncate(ctx.command), `Local main is ${count} commit(s) behind origin/main. Run 'git pull origin main' first, then retry creating branch '${requestedName}'.`)];
117
- }
118
- return [];
119
- }
120
- class BranchCreationGuardRule extends rule_base_1.BashRuleBase {
121
- constructor(config) {
122
- super(config, 'branch-creation-guard', 'branch-creation-guard');
123
- }
124
- description = 'Block new-branch and new-worktree creation when main is stale, when branching off a non-main ' + 'branch, or when the branch/worktree count is at its cap (forces cleanup of dead ones).';
125
- defaultOptions = {
126
- branchFormat: DEFAULT_BRANCH_FORMAT,
127
- maxLocalBranches: DEFAULT_MAX_LOCAL_BRANCHES,
128
- maxWorktrees: DEFAULT_MAX_WORKTREES,
129
- };
130
- worktrees = new repo_workflow_core_1.WorktreeService();
131
- mergedBranches = new repo_workflow_core_1.MergedBranchesService(this.worktrees);
132
- branchIdentity = new repo_workflow_core_1.BranchIdentity();
133
- // Set by check() when (and only when) a cap is what blocked, so fixHint can render the reap
134
- // instructions instead of the branch-naming ones. Same instance-field handoff pr-merge-guard uses.
135
- // Two fields, because the two caps reap different things and their hints share no wording.
136
- capCache = null;
137
- worktreeCapCache = null;
138
- // True when the blocked command was a `git worktree add`, so the recovery command we hand back is
139
- // a worktree command and not a `git checkout -b` the user cannot use here.
140
- worktreeAdd = false;
141
- get branchFormat() {
142
- return this.config.branchFormat ?? DEFAULT_BRANCH_FORMAT;
143
- }
144
- // No `??` fallback: `subBranchNaming` is schema-REQUIRED (#1017), so a config that reached here
145
- // stated it. A default here would be the framework choosing a consumer's branch convention.
146
- get subBranchNaming() {
147
- return this.config.subBranchNaming;
148
- }
149
- get maxLocalBranches() {
150
- return this.config.maxLocalBranches ?? DEFAULT_MAX_LOCAL_BRANCHES;
151
- }
152
- get maxWorktrees() {
153
- return this.config.maxWorktrees ?? DEFAULT_MAX_WORKTREES;
154
- }
155
- // The recovery command for "base this off fresh main", in the flavour of whatever was blocked.
156
- freshMainCommand(name) {
157
- return this.worktreeAdd ? `git fetch origin main && git worktree add ../${name.replace(/\//g, '-')} -b ${name} origin/main` : `git fetch origin main && git checkout -b ${name} origin/main`;
158
- }
159
- // Mode-aware fix hints. Branches off main follow branchFormat — never the sub-branch
160
- // convention. The sub-branch affordance only appears under mode 'ON'; 'ON_NO_SUBBRANCHES'
161
- // hard-blocks it and points instead at the turnOffRuleUntilEpoch escape hatch.
162
- get fixHint() {
163
- const remedies = new cap_remedies_1.CapRemedies();
164
- if (this.worktreeCapCache)
165
- return remedies.worktreeCap();
166
- if (this.capCache)
167
- return remedies.branchCap();
168
- const create = this.worktreeAdd ? 'Create it off fresh main: git fetch origin main && git worktree add ../<dir> -b <name> origin/main' : 'Create it off fresh main from anywhere (incl. a worktree): git fetch origin main && git checkout -b <name> origin/main';
169
- const options = [new rules_config_1.Option(create, true), new rules_config_1.Option(`Name a branch off main per branch-creation-guard.branchFormat: ${this.branchFormat}`)];
170
- if (this.config.mode === 'ON_NO_SUBBRANCHES') {
171
- options.push(new rules_config_1.Option('Sub-branches (branching off another feature branch) are disabled. To temporarily allow one, set ' + 'branch-creation-guard.turnOffRuleUntilEpoch to a future epoch in webpieces.config.json'));
172
- }
173
- else {
174
- options.push(new rules_config_1.Option(`If you truly need a stacked sub-branch (requires human approval), name it per branch-creation-guard.subBranchNaming: ${this.subBranchNaming}`));
175
- }
176
- return new fix_hint_1.FixHint('Cannot create this branch (main is stale, or branching off a non-main branch).', 'Create your branch from an up-to-date main. Pick one:', options);
177
- }
178
- /**
179
- * Strip the parts of a shell command that are DATA rather than executable commands, so the guard
180
- * stops reading prose as instructions.
181
- *
182
- * This guard regex-scans the raw command string and has no notion of quoting, so
183
- * `git commit -m "... git checkout -b foo ..."` — or any heredoc commit message that mentions a
184
- * branch command — was parsed as an actual branch creation and blocked. That bit three separate
185
- * times while building the branch cap, including on the cap's own commit. It matters far more now
186
- * that the cap check runs BEFORE the origin/main allow: at the cap, a merely-MENTIONED branch
187
- * command would block your commit.
188
- *
189
- * A quoted span whose content has no whitespace is kept verbatim (it is a single token — the name
190
- * in `git checkout -b "dean/foo"`), so quoting a branch name cannot smuggle a creation past the
191
- * guard. Anything with whitespace inside quotes is prose, and collapses to a space.
192
- */
193
- check(ctx) {
194
- this.capCache = this.worktreeCapCache = null;
195
- // Match against the command with heredoc bodies and prose-in-quotes removed (BashContext
196
- // computes it for every guard now — this rule's private copy was the original).
197
- const command = ctx.commandCode;
198
- const requestedName = extractBranchName(command);
199
- this.worktreeAdd = WORKTREE_ADD.test(command);
200
- // A worktree add with no -b creates no branch, but it DOES spend the worktree budget, so it must
201
- // survive this early-out and reach the worktree cap below.
202
- if (!requestedName && !this.worktreeAdd)
203
- return [];
204
- // Restoring a reaped branch at its logged SHA is undo, not creation — always allowed, and
205
- // checked before the caps so a full branch list can never trap you on the recovery path.
206
- if (!this.worktreeAdd && RESTORE_AT_SHA.test(command))
207
- return [];
208
- const reserved = this.checkReservedSuffix(ctx, requestedName);
209
- if (reserved)
210
- return [reserved];
211
- const capViolation = this.checkCaps(ctx, requestedName !== null);
212
- if (capViolation)
213
- return [capViolation];
214
- // `git worktree add` of an EXISTING branch (or --detach) creates no branch, so the naming and
215
- // fresh-main rules below do not apply — but one thing still does: the branch may be DEAD.
216
- if (!requestedName)
217
- return this.checkWorktreeOntoDeadBranch(ctx, command);
218
- // Explicitly basing off origin/main is always allowed — it creates the branch from fresh main
219
- // regardless of the current branch, and is the ONLY way that also works inside a linked worktree
220
- // (where `git checkout main` fatals). Reserved-name check above still applies.
221
- if (ORIGIN_MAIN_BASE.test(command))
222
- return [];
223
- if (this.worktreeAdd && WORKTREE_ORIGIN_MAIN_BASE.test(command))
224
- return [];
225
- // The exact `/hotfix/` convention explicitly authorizes a nested emergency branch.
226
- if (this.branchIdentity.isHotfix(requestedName))
227
- return [];
228
- const currentBranch = (0, child_process_1.execSync)('git rev-parse --abbrev-ref HEAD', {
229
- cwd: ctx.workspaceRoot,
230
- encoding: 'utf8',
231
- }).trim();
232
- if (currentBranch === 'main') {
233
- return checkMainIsUpToDate(ctx, requestedName);
234
- }
235
- // Not on main: creating this branch would stack it on a feature branch (a sub-branch).
236
- if (this.config.mode === 'ON_NO_SUBBRANCHES') {
237
- return [
238
- new types_1.Violation(1, truncate(ctx.command), `You are on '${currentBranch}', not main. Create the branch OFF origin/main instead of ` +
239
- `stacking it on this branch: ${this.freshMainCommand(requestedName)} ` +
240
- `(works here and inside a worktree). ${this.branchFormat}. ` +
241
- `You can temporarily turn this off if you truly need a sub-branch by setting ` +
242
- `branch-creation-guard.turnOffRuleUntilEpoch (a future epoch) in webpieces.config.json.`),
243
- ];
244
- }
245
- return [
246
- new types_1.Violation(1, truncate(ctx.command), `You are on '${currentBranch}', not main. Branches must be created from fresh main: ` +
247
- `${this.freshMainCommand(requestedName)}. ${this.branchFormat}. ` +
248
- `If you truly need a stacked sub-branch (requires human approval), name it per ` +
249
- `branch-creation-guard.subBranchNaming ('${this.subBranchNaming}').`),
250
- ];
251
- }
252
- /**
253
- * `git worktree add ../dir <existing-branch>` onto a branch whose PR is ALREADY MERGED.
254
- *
255
- * The count caps never catch this: the command creates no branch, and if you are under the
256
- * worktree cap it sails straight through — materialising a fresh directory full of PRE-MERGE
257
- * code that the AI will then read, plan from and edit. read-stale-guard blocks the reads and
258
- * feature-branch-guard blocks the edits once you are in there, but that is a turn wasted per
259
- * tool call. Refuse at the moment of creation instead, using the SAME merged-PR proof the caps
260
- * already have precomputed on disk.
261
- *
262
- * Fails OPEN exactly like both caps: no cache (fresh clone, no `gh`, refresher hasn't run) or an
263
- * unparseable command → no opinion.
264
- */
265
- checkWorktreeOntoDeadBranch(ctx, command) {
266
- if (!this.worktreeAdd)
267
- return [];
268
- const match = WORKTREE_ADD_EXISTING.exec(command);
269
- if (!match)
270
- return [];
271
- const branch = match[1];
272
- // `origin/main` (and any remote-tracking ref) is the RECOMMENDED base, never a dead branch.
273
- if (branch.startsWith('origin/'))
274
- return [];
275
- const cache = this.mergedBranches.readMergedBranches(ctx.workspaceRoot);
276
- if (!cache)
277
- return [];
278
- const dead = cache.deletable.find((entry) => entry.branch === branch);
279
- if (!dead)
280
- return [];
281
- const dir = branch.replace(/\//g, '-');
282
- return [
283
- new types_1.Violation(1, truncate(ctx.command), `Branch '${branch}' is dead — ${dead.reason}. A worktree on it would be a directory full of ` +
284
- `PRE-MERGE code: everything you read there is stale relative to origin/main (read-stale-guard ` +
285
- `blocks those reads) and every edit is blocked by feature-branch-guard. Base the new worktree ` +
286
- `on fresh main instead: git fetch origin main && git worktree add ../${dir} -b <new-branch> origin/main`),
287
- ];
288
- }
289
- // The reserved `…wpN` generation suffix — see RESERVED_GENERATION_SUFFIX for why it stays blocked
290
- // even though the tooling no longer produces it.
291
- checkReservedSuffix(ctx, requestedName) {
292
- if (!requestedName || !RESERVED_GENERATION_SUFFIX.test(requestedName))
293
- return null;
294
- return new types_1.Violation(1, truncate(ctx.command), `Branch name '${requestedName}' ends in 'wp<number>', which is reserved for the ` + `squash-merge tool's generation marker (base → basewp2 → basewp3). ` + `Rename it to a plain feature branch. ${this.branchFormat}.`);
295
- }
296
- /**
297
- * Both budgets, in the order that produces the most useful complaint.
298
- *
299
- * Called BEFORE the origin/main allow in check() — `... -b <name> origin/main` is the normal,
300
- * always-permitted path, so a cap checked after it would never once fire.
301
- *
302
- * Worktree cap first: a `git worktree add -b` spends BOTH budgets, and when both are full the
303
- * worktree is the thing the command was actually trying to make, so it is the thing to talk about.
304
- */
305
- checkCaps(ctx, createsBranch) {
306
- if (this.worktreeAdd) {
307
- const worktreeViolation = this.checkWorktreeCap(ctx);
308
- if (worktreeViolation)
309
- return worktreeViolation;
310
- }
311
- if (createsBranch)
312
- return this.checkBranchCap(ctx);
313
- return null;
314
- }
315
- /**
316
- * The cap. Blocks branch #N+1 until already-merged branches are reaped, which is the ONLY thing
317
- * keeping the local branch list bounded.
318
- *
319
- * Fails OPEN when the cache is absent (fresh clone, `gh` unavailable, refresher hasn't run yet):
320
- * never block on data we don't have. The detached refresher regenerates it within one hook call,
321
- * so the cap starts enforcing on its own.
322
- */
323
- checkBranchCap(ctx) {
324
- // PARKED branches only — a branch checked out in a worktree is the worktree cap's problem, and
325
- // counting it twice would let five worktrees exhaust the branch budget on their own.
326
- const held = this.worktrees.heldBranches(ctx.workspaceRoot);
327
- const parked = this.mergedBranches.localBranches(ctx.workspaceRoot).filter((branch) => !held.has(branch));
328
- const count = parked.length;
329
- const cap = this.effectiveBranchCap(ctx);
330
- if (count < cap)
331
- return null;
332
- const cache = this.loadReconciledCache(ctx);
333
- if (!cache)
334
- return null;
335
- this.capCache = cache;
336
- // No count of "how many are dead" any more. It was read off a cache that is stale BY DESIGN,
337
- // so every branch of that sentence had to hedge ("None of them are dead", "NOT known right
338
- // now — the cached verdicts are stale"), and none of the three variants changed the next
339
- // move: run pnpm wp-cleanup, which recomputes from scratch. Say the one thing that is true.
340
- return new types_1.Violation(1, truncate(ctx.command), `You have ${String(count)} parked local branches (worktree-held ones not counted); the cap ` + `(branch-creation-guard.maxLocalBranches) is ${String(this.maxLocalBranches)}. Run pnpm wp-cleanup.`);
341
- }
342
- /**
343
- * The cache, with entries for branches/worktrees that no longer exist dropped.
344
- *
345
- * Reconciling is the fix for the phantom count: the file is written by a detached refresher and is
346
- * DELIBERATELY allowed to go stale, so it keeps naming branches deleted minutes ago and worktrees
347
- * already removed. Quoting it verbatim is how the guard announced "8 parked local branches … none of
348
- * them are dead" over a repo that had ONE, and then blocked a legitimate `git worktree add` on that
349
- * figure. `reconcile` re-checks existence with instant local git reads; it does NOT re-derive any
350
- * verdict (that needs the network and belongs in the refresher).
351
- *
352
- * Its AGE is no longer read here. The cap messages stopped quoting verdict counts entirely, so
353
- * there is nothing left for a freshness caveat to qualify — `wp-cleanup` recomputes from scratch.
354
- */
355
- loadReconciledCache(ctx) {
356
- const raw = this.mergedBranches.readMergedBranches(ctx.workspaceRoot);
357
- if (!raw)
358
- return null;
359
- return this.mergedBranches.reconcile(ctx.workspaceRoot, raw);
360
- }
361
- /**
362
- * The branch cap, yielding by ONE when the agent is standing on an already-merged branch.
363
- *
364
- * Two individually-correct guards were composing into a trap: merged-branch-bash-guard blocks
365
- * almost all Bash until you get off a merged branch, and the ONLY way off it that guard advertises
366
- * is creating a fresh branch — which this cap then refused. Every printed exit led to editing
367
- * webpieces.config.json, and that is what an unsupervised agent did.
368
- *
369
- * One over cap, and only while a merged branch is what is pushing you: the branch about to be
370
- * created replaces a branch that is already dead, so the steady-state count does not grow. The cap
371
- * still fires on the NEXT creation, so this defers the cleanup by exactly one branch, never skips it.
372
- *
373
- * Fails toward the strict cap: no cache, a cache for another branch, or a clean branch → no yield.
374
- */
375
- effectiveBranchCap(ctx) {
376
- // The cache is branch-keyed, so the branch we are standing on is what we look the entry up by.
377
- // A branch the last refresh never saw misses (null) → the strict cap, as before.
378
- const current = this.currentBranchOrNull(ctx.workspaceRoot);
379
- if (current === null)
380
- return this.maxLocalBranches;
381
- const status = (0, repo_workflow_core_1.readMainSyncStatus)(ctx.workspaceRoot, current);
382
- if (status === null || !status.branchAlreadyMerged)
383
- return this.maxLocalBranches;
384
- if (status.branch !== current)
385
- return this.maxLocalBranches;
386
- return this.maxLocalBranches + 1;
387
- }
388
- currentBranchOrNull(workspaceRoot) {
389
- // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
390
- try {
391
- return (0, child_process_1.execSync)('git rev-parse --abbrev-ref HEAD', {
392
- cwd: workspaceRoot,
393
- encoding: 'utf8',
394
- stdio: ['pipe', 'pipe', 'pipe'],
395
- }).trim();
396
- }
397
- catch (err) {
398
- const error = (0, to_error_1.toError)(err);
399
- void error;
400
- return null;
401
- }
402
- }
403
- /**
404
- * The worktree cap — the second budget. Same gate, same fail-open rule as the branch cap: a
405
- * worktree list we cannot classify (no cache on disk) blocks nothing.
406
- *
407
- * Counts LINKED worktrees only. The primary clone is not a thing anyone can remove, so charging the
408
- * budget for it would just silently cost you one worktree.
409
- */
410
- checkWorktreeCap(ctx) {
411
- const count = this.worktrees.linkedWorktrees(ctx.workspaceRoot).length;
412
- if (count < this.maxWorktrees)
413
- return null;
414
- const cache = this.loadReconciledCache(ctx);
415
- if (!cache)
416
- return null;
417
- this.worktreeCapCache = cache;
418
- return new types_1.Violation(1, truncate(ctx.command), `You have ${String(count)} linked worktrees; the cap (branch-creation-guard.maxWorktrees) ` + `is ${String(this.maxWorktrees)}. Run pnpm wp-cleanup.`);
419
- }
420
- }
421
- exports.BranchCreationGuardRule = BranchCreationGuardRule;
422
- //# sourceMappingURL=branch-creation-guard.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"branch-creation-guard.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/ai-hook-rules/src/core/rules/branch-creation-guard.ts"],"names":[],"mappings":";;;AAAA,iDAAyC;AAEzC,0DAA4E;AAC5E,sEAAiK;AAGjK,oCAA0C;AAC1C,4CAA4C;AAC5C,0CAAsC;AACtC,iDAA6C;AAC7C,0CAAsC;AAEtC,8EAA8E;AAC9E,+FAA+F;AAC/F,kGAAkG;AAClG,MAAM,qBAAqB,GAAG,4HAA4H,CAAC;AAE3J,qGAAqG;AACrG,+EAA+E;AAC/E,EAAE;AACF,uGAAuG;AACvG,sGAAsG;AACtG,uGAAuG;AACvG,sCAAsC;AACtC,MAAM,0BAA0B,GAAG,CAAC,CAAC;AACrC,MAAM,qBAAqB,GAAG,CAAC,CAAC;AAEhC,oGAAoG;AACpG,kGAAkG;AAClG,mGAAmG;AACnG,MAAM,QAAQ,GAAG,MAAM,CAAC,GAAG,CAAA,6BAA6B,CAAC;AAEzD,MAAM,eAAe,GAAa;IAC9B,IAAI,MAAM,CAAC,MAAM,CAAC,GAAG,CAAA,6BAA6B,QAAQ,GAAG,CAAC;IAC9D,IAAI,MAAM,CAAC,MAAM,CAAC,GAAG,CAAA,2BAA2B,QAAQ,GAAG,CAAC;IAC5D,IAAI,MAAM,CAAC,MAAM,CAAC,GAAG,CAAA,wBAAwB,QAAQ,GAAG,CAAC;IACzD,iGAAiG;IACjG,+FAA+F;IAC/F,gGAAgG;IAChG,oGAAoG;IACpG,IAAI,MAAM,CAAC,MAAM,CAAC,GAAG,CAAA,+CAA+C,QAAQ,GAAG,CAAC;CACnF,CAA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AK,GAAG,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAAC,CAAC;QAC5C,IAAI,CAAC,KAAK;YAAE,OAAO,IAAI,CAAC;QAExB,IAAI,CAAC,gBAAgB,GAAG,KAAK,CAAC;QAE9B,OAAO,IAAI,iBAAC,CAAC,CAAC,EAAE,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,YAAY,MAAM,CAAC,KAAK,CAAC,kEAAkE,GAAG,MAAM,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,wBAAwB,CAAC,CAAC;IAClM,CAAC;CACJ;AAtUD,0DAsUC","sourcesContent":["import { execSync } from 'child_process';\n\nimport { BranchCreationGuardConfig, Option } from '@webpieces/rules-config';\nimport { BranchIdentity, DeletableBranch, MergedBranchesCache, MergedBranchesService, WorktreeService, readMainSyncStatus } from '@webpieces/repo-workflow-core';\n\nimport type { BashContext, Violation } from '../types';\nimport { Violation as V } from '../types';\nimport { BashRuleBase } from '../rule-base';\nimport { FixHint } from '../fix-hint';\nimport { CapRemedies } from './cap-remedies';\nimport { toError } from '../to-error';\n\n// Defaults used when the rule has no explicit value in webpieces.config.json.\n// branchFormat is a human sentence telling the AI how to name a branch created off main; it is\n// intentionally NOT the sub-branch convention (sub-branches are a separate, human-approved path).\nconst DEFAULT_BRANCH_FORMAT = 'Name it {whoami}/<short-feature-description> — lowercase, no version numbers, no sub/ prefix (e.g. dean/upgrade-webpieces)';\n\n// Hard cap on local feature branches. Enforced at CREATION because that is the one moment cleanup is\n// both cheap and obviously worth it — reaping happens over time, never \"ASAP\".\n//\n// The branch cap counts PARKED branches only — branches not checked out in any worktree. Worktree-held\n// branches are counted by the worktree cap instead. Two budgets, because they are not substitutes: if\n// held branches also spent the branch budget, five worktrees would leave room for zero branches and no\n// branch could ever be created again.\nconst DEFAULT_MAX_LOCAL_BRANCHES = 5;\nconst DEFAULT_MAX_WORKTREES = 5;\n\n// A plausible git ref name. Deliberately NOT `[^\\s-]` — that class matches shell metacharacters, so\n// `git branch | wc -l` (a read-only LISTING, piped) was parsed as \"create a branch named `|`\" and\n// blocked. Cleanup work necessarily reads and deletes branches, so a listing must never trip this.\nconst REF_NAME = String.raw`[A-Za-z0-9][A-Za-z0-9_./-]*`;\n\nconst BRANCH_PATTERNS: RegExp[] = [\n new RegExp(String.raw`git\\s+checkout\\s+-[bB]\\s+(${REF_NAME})`),\n new RegExp(String.raw`git\\s+switch\\s+-[cC]\\s+(${REF_NAME})`),\n new RegExp(String.raw`git\\s+branch\\s+(?!-)(${REF_NAME})`),\n // `git worktree add ../dir -b <name> origin/main` — the form docs/git-workflow.md recommends for\n // starting a feature. It creates a branch just as surely as `checkout -b` does, and until this\n // pattern existed it walked straight past the cap, the reserved-suffix check and the sub-branch\n // check. `(?:\\S+\\s+)*?` absorbs the path and any other flags, so the -b may precede or follow them.\n new RegExp(String.raw`git\\s+worktree\\s+add\\s+(?:\\S+\\s+)*?-[bB]\\s+(${REF_NAME})`),\n];\n\n// ANY worktree creation, with or without -b. The no-`-b` forms (`git worktree add ../dir existing`,\n// `--detach`) create no branch but DO create a worktree, so they spend the worktree budget and must\n// still hit the cap.\nconst WORKTREE_ADD = /git\\s+worktree\\s+add\\b/;\n\n// `git worktree add <path> <existing-branch>` — the checkout-an-existing-branch form. Captures the\n// LAST bare (non-flag) argument, which is the committish; the first bare argument is the path.\n// Flags that take a value (`--reason <s>`, `-b <name>`) are excluded by the caller, which only uses\n// this on commands with no `-b`/`-B` at all.\nconst WORKTREE_ADD_EXISTING = new RegExp(String.raw`git\\s+worktree\\s+add\\s+(?:-{1,2}[A-Za-z-]+\\s+)*\\S+\\s+(${REF_NAME})`);\n\n// `git branch <name> <sha>` — RESTORING a branch at an explicit commit, which is exactly the\n// `recover=` command wp-cleanup writes to branch-mutations.log for every branch it reaps.\n//\n// This must be allowed UNCONDITIONALLY, ahead of even the caps. The entire argument for letting the\n// tooling delete branches unattended is that any delete is one logged command away from being undone\n// — so a guard that blocks that command turns a real guarantee into a decorative one. (It did: the\n// generic `git branch <name>` creation pattern matched the restore and refused it, demanding the\n// branch be recreated off origin/main, which is precisely the content the restore is meant to bring\n// back.) A restore also cannot grow the branch list beyond what already existed.\nconst RESTORE_AT_SHA = new RegExp(String.raw`git\\s+branch\\s+${REF_NAME}\\s+[0-9a-f]{7,40}(?:\\W|$)`);\n\n// A trailing `wp<number>` was the old squash-merge generation marker (base → basewp2 → basewp3).\n// The tooling NO LONGER produces it — a sync now lands back on the same feature name — but the suffix\n// stays RESERVED so a human branch can't collide with a leftover `…wpN` still floating in a consumer\n// repo mid-transition. Block it at creation time and steer the name back to the plain feature form.\nconst RESERVED_GENERATION_SUFFIX = /wp\\d+$/;\n\n// A branch-creation command that explicitly bases off origin/main (e.g. `git checkout -b feat\n// origin/main`). This is exactly the fresh-main base the guard wants, and it works from ANY current\n// branch or linked worktree — main need not (and in a worktree cannot) be checked out here. Allowed\n// unconditionally so the recovery messages can safely tell you to run it from a worktree.\n//\n// The trailing check is `\\W|$`, not `\\s|$`: the ALLOW pattern must not be stricter about delimiters\n// than the BLOCK pattern above, or a `git checkout -b x origin/main` that ends at a quote or backtick\n// is seen as a branch creation but NOT as an origin/main one — recognised, then wrongly blocked.\nconst ORIGIN_MAIN_BASE = /git\\s+(?:checkout\\s+-[bB]|switch\\s+-[cC])\\s+\\S+\\s+origin\\/main(?:\\W|$)/;\n\n// The worktree arm of the same allow: `git worktree add ../dir -b <name> origin/main`. Same fresh-main\n// base, same reasoning — and in a worktree it is the ONLY workable base, since `git checkout main`\n// fatals there. Kept separate from ORIGIN_MAIN_BASE because the argument shape differs (a path sits\n// between the subcommand and the flags).\nconst WORKTREE_ORIGIN_MAIN_BASE = /git\\s+worktree\\s+add\\s+(?:\\S+\\s+)*origin\\/main(?:\\W|$)/;\n\nfunction extractBranchName(command: string): string | null {\n for (const pattern of BRANCH_PATTERNS) {\n const m = pattern.exec(command);\n if (m) return m[1];\n }\n return null;\n}\n\nfunction truncate(s: string): string {\n const MAX = 120;\n return s.length <= MAX ? s : s.slice(0, MAX) + '…';\n}\n\nfunction checkMainIsUpToDate(ctx: BashContext, requestedName: string): readonly Violation[] {\n // `--no-write-fetch-head` for the same reason as the background refresher (see\n // MainSyncStatusService.fetchOriginMain): this refresh can run while the agent is mid\n // `git fetch`/`git pull`, and two overlapping writers of the unlocked `.git/FETCH_HEAD` can leave\n // a duplicate for-merge line that makes the agent's `git pull` fatal with \"multiple branches\". We\n // read `origin/main` below, never FETCH_HEAD. On a git too old for the flag, retry the plain form.\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n execSync('git fetch --no-write-fetch-head origin main --quiet', {\n cwd: ctx.workspaceRoot,\n encoding: 'utf8',\n });\n } catch (err: unknown) {\n const error = toError(err);\n const text = error.message.toLowerCase();\n const tooOld = text.includes('unknown option') || text.includes('unknown switch') || text.includes('unrecognized option');\n if (!tooOld) throw error;\n execSync('git fetch origin main --quiet', { cwd: ctx.workspaceRoot, encoding: 'utf8' });\n }\n const countStr = execSync('git rev-list HEAD..origin/main --count', {\n cwd: ctx.workspaceRoot,\n encoding: 'utf8',\n }).trim();\n const count = parseInt(countStr, 10);\n if (count > 0) {\n return [new V(1, truncate(ctx.command), `Local main is ${count} commit(s) behind origin/main. Run 'git pull origin main' first, then retry creating branch '${requestedName}'.`)];\n }\n return [];\n}\n\nexport class BranchCreationGuardRule extends BashRuleBase<BranchCreationGuardConfig> {\n constructor(config: BranchCreationGuardConfig) {\n super(config, 'branch-creation-guard', 'branch-creation-guard');\n }\n\n readonly description = 'Block new-branch and new-worktree creation when main is stale, when branching off a non-main ' + 'branch, or when the branch/worktree count is at its cap (forces cleanup of dead ones).';\n override readonly defaultOptions = {\n branchFormat: DEFAULT_BRANCH_FORMAT,\n maxLocalBranches: DEFAULT_MAX_LOCAL_BRANCHES,\n maxWorktrees: DEFAULT_MAX_WORKTREES,\n };\n\n private readonly worktrees = new WorktreeService();\n private readonly mergedBranches = new MergedBranchesService(this.worktrees);\n private readonly branchIdentity = new BranchIdentity();\n\n // Set by check() when (and only when) a cap is what blocked, so fixHint can render the reap\n // instructions instead of the branch-naming ones. Same instance-field handoff pr-merge-guard uses.\n // Two fields, because the two caps reap different things and their hints share no wording.\n private capCache: MergedBranchesCache | null = null;\n private worktreeCapCache: MergedBranchesCache | null = null;\n\n // True when the blocked command was a `git worktree add`, so the recovery command we hand back is\n // a worktree command and not a `git checkout -b` the user cannot use here.\n private worktreeAdd = false;\n\n private get branchFormat(): string {\n return this.config.branchFormat ?? DEFAULT_BRANCH_FORMAT;\n }\n\n // No `??` fallback: `subBranchNaming` is schema-REQUIRED (#1017), so a config that reached here\n // stated it. A default here would be the framework choosing a consumer's branch convention.\n private get subBranchNaming(): string {\n return this.config.subBranchNaming;\n }\n\n private get maxLocalBranches(): number {\n return this.config.maxLocalBranches ?? DEFAULT_MAX_LOCAL_BRANCHES;\n }\n\n private get maxWorktrees(): number {\n return this.config.maxWorktrees ?? DEFAULT_MAX_WORKTREES;\n }\n\n // The recovery command for \"base this off fresh main\", in the flavour of whatever was blocked.\n private freshMainCommand(name: string): string {\n return this.worktreeAdd ? `git fetch origin main && git worktree add ../${name.replace(/\\//g, '-')} -b ${name} origin/main` : `git fetch origin main && git checkout -b ${name} origin/main`;\n }\n\n // Mode-aware fix hints. Branches off main follow branchFormat — never the sub-branch\n // convention. The sub-branch affordance only appears under mode 'ON'; 'ON_NO_SUBBRANCHES'\n // hard-blocks it and points instead at the turnOffRuleUntilEpoch escape hatch.\n get fixHint(): FixHint {\n const remedies = new CapRemedies();\n if (this.worktreeCapCache) return remedies.worktreeCap();\n if (this.capCache) return remedies.branchCap();\n\n const create = this.worktreeAdd ? 'Create it off fresh main: git fetch origin main && git worktree add ../<dir> -b <name> origin/main' : 'Create it off fresh main from anywhere (incl. a worktree): git fetch origin main && git checkout -b <name> origin/main';\n\n const options = [new Option(create, true), new Option(`Name a branch off main per branch-creation-guard.branchFormat: ${this.branchFormat}`)];\n if (this.config.mode === 'ON_NO_SUBBRANCHES') {\n options.push(new Option('Sub-branches (branching off another feature branch) are disabled. To temporarily allow one, set ' + 'branch-creation-guard.turnOffRuleUntilEpoch to a future epoch in webpieces.config.json'));\n } else {\n options.push(new Option(`If you truly need a stacked sub-branch (requires human approval), name it per branch-creation-guard.subBranchNaming: ${this.subBranchNaming}`));\n }\n return new FixHint('Cannot create this branch (main is stale, or branching off a non-main branch).', 'Create your branch from an up-to-date main. Pick one:', options);\n }\n\n /**\n * Strip the parts of a shell command that are DATA rather than executable commands, so the guard\n * stops reading prose as instructions.\n *\n * This guard regex-scans the raw command string and has no notion of quoting, so\n * `git commit -m \"... git checkout -b foo ...\"` — or any heredoc commit message that mentions a\n * branch command — was parsed as an actual branch creation and blocked. That bit three separate\n * times while building the branch cap, including on the cap's own commit. It matters far more now\n * that the cap check runs BEFORE the origin/main allow: at the cap, a merely-MENTIONED branch\n * command would block your commit.\n *\n * A quoted span whose content has no whitespace is kept verbatim (it is a single token — the name\n * in `git checkout -b \"dean/foo\"`), so quoting a branch name cannot smuggle a creation past the\n * guard. Anything with whitespace inside quotes is prose, and collapses to a space.\n */\n check(ctx: BashContext): readonly Violation[] {\n this.capCache = this.worktreeCapCache = null;\n // Match against the command with heredoc bodies and prose-in-quotes removed (BashContext\n // computes it for every guard now — this rule's private copy was the original).\n const command = ctx.commandCode;\n const requestedName = extractBranchName(command);\n this.worktreeAdd = WORKTREE_ADD.test(command);\n\n // A worktree add with no -b creates no branch, but it DOES spend the worktree budget, so it must\n // survive this early-out and reach the worktree cap below.\n if (!requestedName && !this.worktreeAdd) return [];\n\n // Restoring a reaped branch at its logged SHA is undo, not creation — always allowed, and\n // checked before the caps so a full branch list can never trap you on the recovery path.\n if (!this.worktreeAdd && RESTORE_AT_SHA.test(command)) return [];\n\n const reserved = this.checkReservedSuffix(ctx, requestedName);\n if (reserved) return [reserved];\n\n const capViolation = this.checkCaps(ctx, requestedName !== null);\n if (capViolation) return [capViolation];\n\n // `git worktree add` of an EXISTING branch (or --detach) creates no branch, so the naming and\n // fresh-main rules below do not apply — but one thing still does: the branch may be DEAD.\n if (!requestedName) return this.checkWorktreeOntoDeadBranch(ctx, command);\n\n // Explicitly basing off origin/main is always allowed — it creates the branch from fresh main\n // regardless of the current branch, and is the ONLY way that also works inside a linked worktree\n // (where `git checkout main` fatals). Reserved-name check above still applies.\n if (ORIGIN_MAIN_BASE.test(command)) return [];\n if (this.worktreeAdd && WORKTREE_ORIGIN_MAIN_BASE.test(command)) return [];\n\n // The exact `/hotfix/` convention explicitly authorizes a nested emergency branch.\n if (this.branchIdentity.isHotfix(requestedName)) return [];\n\n const currentBranch = execSync('git rev-parse --abbrev-ref HEAD', {\n cwd: ctx.workspaceRoot,\n encoding: 'utf8',\n }).trim();\n\n if (currentBranch === 'main') {\n return checkMainIsUpToDate(ctx, requestedName);\n }\n\n // Not on main: creating this branch would stack it on a feature branch (a sub-branch).\n if (this.config.mode === 'ON_NO_SUBBRANCHES') {\n return [\n new V(\n 1,\n truncate(ctx.command),\n `You are on '${currentBranch}', not main. Create the branch OFF origin/main instead of ` +\n `stacking it on this branch: ${this.freshMainCommand(requestedName)} ` +\n `(works here and inside a worktree). ${this.branchFormat}. ` +\n `You can temporarily turn this off if you truly need a sub-branch by setting ` +\n `branch-creation-guard.turnOffRuleUntilEpoch (a future epoch) in webpieces.config.json.`,\n ),\n ];\n }\n\n return [\n new V(\n 1,\n truncate(ctx.command),\n `You are on '${currentBranch}', not main. Branches must be created from fresh main: ` +\n `${this.freshMainCommand(requestedName)}. ${this.branchFormat}. ` +\n `If you truly need a stacked sub-branch (requires human approval), name it per ` +\n `branch-creation-guard.subBranchNaming ('${this.subBranchNaming}').`,\n ),\n ];\n }\n\n /**\n * `git worktree add ../dir <existing-branch>` onto a branch whose PR is ALREADY MERGED.\n *\n * The count caps never catch this: the command creates no branch, and if you are under the\n * worktree cap it sails straight through — materialising a fresh directory full of PRE-MERGE\n * code that the AI will then read, plan from and edit. read-stale-guard blocks the reads and\n * feature-branch-guard blocks the edits once you are in there, but that is a turn wasted per\n * tool call. Refuse at the moment of creation instead, using the SAME merged-PR proof the caps\n * already have precomputed on disk.\n *\n * Fails OPEN exactly like both caps: no cache (fresh clone, no `gh`, refresher hasn't run) or an\n * unparseable command → no opinion.\n */\n private checkWorktreeOntoDeadBranch(ctx: BashContext, command: string): readonly Violation[] {\n if (!this.worktreeAdd) return [];\n\n const match = WORKTREE_ADD_EXISTING.exec(command);\n if (!match) return [];\n const branch = match[1];\n // `origin/main` (and any remote-tracking ref) is the RECOMMENDED base, never a dead branch.\n if (branch.startsWith('origin/')) return [];\n\n const cache = this.mergedBranches.readMergedBranches(ctx.workspaceRoot);\n if (!cache) return [];\n\n const dead = cache.deletable.find((entry: DeletableBranch): boolean => entry.branch === branch);\n if (!dead) return [];\n\n const dir = branch.replace(/\\//g, '-');\n return [\n new V(\n 1,\n truncate(ctx.command),\n `Branch '${branch}' is dead — ${dead.reason}. A worktree on it would be a directory full of ` +\n `PRE-MERGE code: everything you read there is stale relative to origin/main (read-stale-guard ` +\n `blocks those reads) and every edit is blocked by feature-branch-guard. Base the new worktree ` +\n `on fresh main instead: git fetch origin main && git worktree add ../${dir} -b <new-branch> origin/main`,\n ),\n ];\n }\n\n // The reserved `…wpN` generation suffix — see RESERVED_GENERATION_SUFFIX for why it stays blocked\n // even though the tooling no longer produces it.\n private checkReservedSuffix(ctx: BashContext, requestedName: string | null): Violation | null {\n if (!requestedName || !RESERVED_GENERATION_SUFFIX.test(requestedName)) return null;\n return new V(1, truncate(ctx.command), `Branch name '${requestedName}' ends in 'wp<number>', which is reserved for the ` + `squash-merge tool's generation marker (base → basewp2 → basewp3). ` + `Rename it to a plain feature branch. ${this.branchFormat}.`);\n }\n\n /**\n * Both budgets, in the order that produces the most useful complaint.\n *\n * Called BEFORE the origin/main allow in check() — `... -b <name> origin/main` is the normal,\n * always-permitted path, so a cap checked after it would never once fire.\n *\n * Worktree cap first: a `git worktree add -b` spends BOTH budgets, and when both are full the\n * worktree is the thing the command was actually trying to make, so it is the thing to talk about.\n */\n private checkCaps(ctx: BashContext, createsBranch: boolean): Violation | null {\n if (this.worktreeAdd) {\n const worktreeViolation = this.checkWorktreeCap(ctx);\n if (worktreeViolation) return worktreeViolation;\n }\n if (createsBranch) return this.checkBranchCap(ctx);\n return null;\n }\n\n /**\n * The cap. Blocks branch #N+1 until already-merged branches are reaped, which is the ONLY thing\n * keeping the local branch list bounded.\n *\n * Fails OPEN when the cache is absent (fresh clone, `gh` unavailable, refresher hasn't run yet):\n * never block on data we don't have. The detached refresher regenerates it within one hook call,\n * so the cap starts enforcing on its own.\n */\n private checkBranchCap(ctx: BashContext): Violation | null {\n // PARKED branches only — a branch checked out in a worktree is the worktree cap's problem, and\n // counting it twice would let five worktrees exhaust the branch budget on their own.\n const held = this.worktrees.heldBranches(ctx.workspaceRoot);\n const parked = this.mergedBranches.localBranches(ctx.workspaceRoot).filter((branch: string): boolean => !held.has(branch));\n const count = parked.length;\n const cap = this.effectiveBranchCap(ctx);\n if (count < cap) return null;\n\n const cache = this.loadReconciledCache(ctx);\n if (!cache) return null;\n\n this.capCache = cache;\n\n // No count of \"how many are dead\" any more. It was read off a cache that is stale BY DESIGN,\n // so every branch of that sentence had to hedge (\"None of them are dead\", \"NOT known right\n // now — the cached verdicts are stale\"), and none of the three variants changed the next\n // move: run pnpm wp-cleanup, which recomputes from scratch. Say the one thing that is true.\n return new V(1, truncate(ctx.command), `You have ${String(count)} parked local branches (worktree-held ones not counted); the cap ` + `(branch-creation-guard.maxLocalBranches) is ${String(this.maxLocalBranches)}. Run pnpm wp-cleanup.`);\n }\n\n /**\n * The cache, with entries for branches/worktrees that no longer exist dropped.\n *\n * Reconciling is the fix for the phantom count: the file is written by a detached refresher and is\n * DELIBERATELY allowed to go stale, so it keeps naming branches deleted minutes ago and worktrees\n * already removed. Quoting it verbatim is how the guard announced \"8 parked local branches … none of\n * them are dead\" over a repo that had ONE, and then blocked a legitimate `git worktree add` on that\n * figure. `reconcile` re-checks existence with instant local git reads; it does NOT re-derive any\n * verdict (that needs the network and belongs in the refresher).\n *\n * Its AGE is no longer read here. The cap messages stopped quoting verdict counts entirely, so\n * there is nothing left for a freshness caveat to qualify — `wp-cleanup` recomputes from scratch.\n */\n private loadReconciledCache(ctx: BashContext): MergedBranchesCache | null {\n const raw = this.mergedBranches.readMergedBranches(ctx.workspaceRoot);\n if (!raw) return null;\n return this.mergedBranches.reconcile(ctx.workspaceRoot, raw);\n }\n\n /**\n * The branch cap, yielding by ONE when the agent is standing on an already-merged branch.\n *\n * Two individually-correct guards were composing into a trap: merged-branch-bash-guard blocks\n * almost all Bash until you get off a merged branch, and the ONLY way off it that guard advertises\n * is creating a fresh branch — which this cap then refused. Every printed exit led to editing\n * webpieces.config.json, and that is what an unsupervised agent did.\n *\n * One over cap, and only while a merged branch is what is pushing you: the branch about to be\n * created replaces a branch that is already dead, so the steady-state count does not grow. The cap\n * still fires on the NEXT creation, so this defers the cleanup by exactly one branch, never skips it.\n *\n * Fails toward the strict cap: no cache, a cache for another branch, or a clean branch → no yield.\n */\n private effectiveBranchCap(ctx: BashContext): number {\n // The cache is branch-keyed, so the branch we are standing on is what we look the entry up by.\n // A branch the last refresh never saw misses (null) → the strict cap, as before.\n const current = this.currentBranchOrNull(ctx.workspaceRoot);\n if (current === null) return this.maxLocalBranches;\n const status = readMainSyncStatus(ctx.workspaceRoot, current);\n if (status === null || !status.branchAlreadyMerged) return this.maxLocalBranches;\n if (status.branch !== current) return this.maxLocalBranches;\n return this.maxLocalBranches + 1;\n }\n\n private currentBranchOrNull(workspaceRoot: string): string | null {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return execSync('git rev-parse --abbrev-ref HEAD', {\n cwd: workspaceRoot,\n encoding: 'utf8',\n stdio: ['pipe', 'pipe', 'pipe'],\n }).trim();\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n\n /**\n * The worktree cap — the second budget. Same gate, same fail-open rule as the branch cap: a\n * worktree list we cannot classify (no cache on disk) blocks nothing.\n *\n * Counts LINKED worktrees only. The primary clone is not a thing anyone can remove, so charging the\n * budget for it would just silently cost you one worktree.\n */\n private checkWorktreeCap(ctx: BashContext): Violation | null {\n const count = this.worktrees.linkedWorktrees(ctx.workspaceRoot).length;\n if (count < this.maxWorktrees) return null;\n\n const cache = this.loadReconciledCache(ctx);\n if (!cache) return null;\n\n this.worktreeCapCache = cache;\n\n return new V(1, truncate(ctx.command), `You have ${String(count)} linked worktrees; the cap (branch-creation-guard.maxWorktrees) ` + `is ${String(this.maxWorktrees)}. Run pnpm wp-cleanup.`);\n }\n}\n"]}