@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,187 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RecoveryAllowlist = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const path = tslib_1.__importStar(require("path"));
6
+ const hook_runtime_1 = require("@webpieces/hook-runtime");
7
+ const content_read_scan_1 = require("./content-read-scan");
8
+ // ---------------------------------------------------------------------------
9
+ // THE SKIP LIST — L2 row 4, as one implementation.
10
+ //
11
+ // "These get you OUT, or tell you where you are." That is the whole principle: a command on this list
12
+ // is not "working here", so it is safe in every state where working here is not.
13
+ //
14
+ // It was written for state B (a merged branch) and lived inside merged-branch-bash-guard. Row 5 —
15
+ // on `main` — needs the identical question answered, and the answer must not be a second copy: two
16
+ // skip lists drift, and the half that drifts is the half that wedges a session on its own cure. So the
17
+ // list is ONE class, and both guards ask it.
18
+ //
19
+ // This is the DEFAULT-DENY half of L2. Its sibling ContentReadScan is the default-ALLOW blocklist used
20
+ // where only stale CONTENT is the hazard. The guards docblock is right that the two polarities cannot
21
+ // collapse into one function — but the allowlist itself was never the reason they could not, and
22
+ // sharing it is what makes row 5's `B` half affordable at all.
23
+ //
24
+ // WHAT BELONGS ON THIS LIST — one question, asked of the COMMAND, not of your sympathy for it:
25
+ // **does it read or write repo content?** If it cannot do either, it cannot be "working here", so it
26
+ // belongs here regardless of what else it does. That is why `curl`/`wget` and `gh` are on it: they talk
27
+ // to a network, not to the working tree, and a session parked in an L2 state still has to be able to
28
+ // close a PR, comment on one, or fetch a URL. It is also why the exclusions are the FORMS that write a
29
+ // local file (`curl -o`, `gh repo clone`, `gh pr checkout`, any `> file` redirect) rather than whole
30
+ // programs: the write is the hazard, not the binary.
31
+ //
32
+ // EVERY segment must pass. One `… && scripts/local.sh start` in a chain denies the whole command,
33
+ // because the chain runs it. Segments are judged by ROLE first: shell STRUCTURE (`for … in`, `do`,
34
+ // `done`) invokes nothing and output SHAPING (`| tail -40`) cannot touch the repo, so neither may veto
35
+ // a chain — judging the raw string instead is what once made the guard reject
36
+ // `git fetch origin main 2>&1 | tail -5`, a command its own redirect had just prescribed.
37
+ // ---------------------------------------------------------------------------
38
+ class RecoveryAllowlist {
39
+ scanner;
40
+ shell;
41
+ constructor(scanner) {
42
+ this.scanner = scanner;
43
+ this.shell = new hook_runtime_1.ShellSegmentScan(scanner);
44
+ }
45
+ /**
46
+ * Is EVERY segment of this command one that gets you out, or tells you where you are?
47
+ *
48
+ * An empty command is `false` — nothing to be sure about, and the default here is deny. (Note this
49
+ * is one of the three places the two Bash guards genuinely differ; the stale-main blocklist allows
50
+ * the empty command because its default is the other way round.)
51
+ */
52
+ isFullyRecovery(ctx) {
53
+ const segments = this.scanner.segmentsWithJoins(ctx.command);
54
+ if (segments.length === 0)
55
+ return false;
56
+ const content = new content_read_scan_1.ContentReadScan(this.scanner, ctx.workspaceRoot, ctx.effectiveCwd);
57
+ return segments.every((segment) => this.isRecoverySegment(segment, content));
58
+ }
59
+ isRecoverySegment(segment, content) {
60
+ const verdict = this.shell.classify(segment);
61
+ if (verdict.role === 'structure')
62
+ return true;
63
+ // Inert / piped-into filters are fine EXCEPT when they name a workspace path: `git status |
64
+ // cat src/foo.ts` still hands the agent file content out of a tree it should not be reading.
65
+ if (verdict.role === 'shaping')
66
+ return content.readsStaleContent(segment) === null;
67
+ // A read that names NOTHING in this tree cannot be affected by which branch this tree is on.
68
+ // `ls -la ~/.claude/projects/ | grep -i foo` was blocked as "this branch is merged" — the
69
+ // command touches no repo at all. Only CONTENT READERS qualify, so a build, a server or a git
70
+ // write never slips through on the strength of its paths.
71
+ if (content.readsOnlyOutsideContent(segment))
72
+ return true;
73
+ // A segment that reads CONTENT out of this tree is never "getting you out", whatever command
74
+ // it is spelled as. This must come BEFORE the git allowlist, because `show` and `grep` are on
75
+ // that list for their metadata/upstream forms and would otherwise wave through the two git
76
+ // spellings of a local content read: `git show HEAD:package.json` and `git grep TODO`. Their
77
+ // upstream forms (`git show origin/main:…`, `git grep TODO origin/main`) read the CURRENT tree
78
+ // and ContentReadScan already returns null for those, so they stay allowed — which is the
79
+ // point, since reading upstream is exactly what a blocked agent should be doing.
80
+ if (content.readsStaleContent(segment) !== null)
81
+ return false;
82
+ const gitSub = this.scanner.gitSubcommandOf(verdict.words);
83
+ if (gitSub !== null)
84
+ return ALLOWED_GIT_SUBCOMMANDS.has(gitSub);
85
+ if (this.isGh(verdict))
86
+ return true;
87
+ if (this.isNetworkClient(verdict))
88
+ return true;
89
+ return this.isPackageRecovery(verdict);
90
+ }
91
+ /**
92
+ * `gh` GENERALLY — it talks to GitHub, not to the working tree.
93
+ *
94
+ * This used to be an allowlist of read-only actions (`gh pr view|list|status|checks`, `gh run
95
+ * view`), which fell over the moment an agent needed `gh pr close`, `gh pr comment` or `gh api`
96
+ * from a parked session: those change something on GitHub and NOTHING in this tree, so the branch
97
+ * state cannot be an argument against them. The exclusions are therefore the `gh` subcommands that
98
+ * write LOCAL files — a clone, a checkout, a download — plus any segment carrying a `> file`
99
+ * redirect.
100
+ *
101
+ * gh commands that are wrong for OTHER reasons stay wrong: `gh pr create`/`push` is governed by
102
+ * pr-creation-or-push-guard and `gh pr merge` by pr-merge-guard. Those are separate policies and
103
+ * this list was never what enforced them.
104
+ *
105
+ * YES, THIS ONE SUBLIST IS A BLOCKLIST, and that is the opposite polarity to the guard around it.
106
+ * The argument against a blocklist elsewhere is that the hazardous set is UNBOUNDED — any program
107
+ * can write a file as a side effect of doing something else, so no enumeration could ever be
108
+ * complete. `gh`'s surface is not: it is one vendor's CLI, its verbs are documented, and writing
109
+ * into the working tree is the rare exception rather than the ambient default. A new `gh`
110
+ * subcommand that clones or downloads is a known, greppable maintenance point — `GH_LOCAL_FILE_WRITES`
111
+ * — where "every future program that might write" is not.
112
+ */
113
+ isGh(verdict) {
114
+ const words = verdict.words;
115
+ if (words.length === 0 || path.basename(words[0]) !== 'gh')
116
+ return false;
117
+ if (this.shell.redirectsToFile(words))
118
+ return false;
119
+ const top = words[1];
120
+ if (top === undefined)
121
+ return false;
122
+ const action = words[2];
123
+ const localWrites = GH_LOCAL_FILE_WRITES.get(top);
124
+ if (localWrites === undefined)
125
+ return true;
126
+ return action === undefined || !localWrites.has(action);
127
+ }
128
+ /**
129
+ * `curl` / `wget` — a network fetch reads a URL, not this repo.
130
+ *
131
+ * Excluded: the forms that name a local FILE to write (`curl -o`, `curl -O`, `wget -O`, an
132
+ * `--output-dir`/`-P`, or a `> file` redirect), because those are how a fetch becomes a write into
133
+ * the tree. A bare `wget <url>` still drops its download into the cwd; that CREATES an untracked
134
+ * file rather than modifying tracked content, which is the line this list draws everywhere else.
135
+ */
136
+ isNetworkClient(verdict) {
137
+ const words = verdict.words;
138
+ if (words.length === 0 || !NETWORK_CLIENTS.has(path.basename(words[0])))
139
+ return false;
140
+ if (this.shell.redirectsToFile(words))
141
+ return false;
142
+ return !words.some((word) => OUTPUT_FILE_FLAGS.has(word));
143
+ }
144
+ // pnpm/npm/yarn recovery bins: the `wp-*` cleanup/gated commands and package installs (a chained
145
+ // install that isInstallerCommand — the pure-install bypass — did not catch reaches here).
146
+ isPackageRecovery(verdict) {
147
+ const words = verdict.words;
148
+ if (words.length === 0 || !PACKAGE_MANAGERS.has(words[0]))
149
+ return false;
150
+ return words.slice(1).some((word) => /^wp-[a-z-]+$/.test(word) || PACKAGE_INSTALL_VERBS.has(word));
151
+ }
152
+ }
153
+ exports.RecoveryAllowlist = RecoveryAllowlist;
154
+ const ALLOWED_GIT_SUBCOMMANDS = new Set([
155
+ 'status', 'log', 'diff', 'show', 'branch', 'checkout', 'switch', 'worktree', 'fetch', 'pull',
156
+ 'rev-parse', 'rev-list', 'merge-base', 'ls-files', 'ls-tree', 'cat-file', 'for-each-ref',
157
+ 'symbolic-ref', 'describe', 'name-rev', 'reflog', 'shortlog', 'remote', 'config', 'stash', 'tag',
158
+ 'blame', 'whatchanged', 'cherry',
159
+ // `grep` is here ONLY for its upstream form (`git grep TODO origin/main`), which reads the CURRENT
160
+ // tree and is what a blocked agent should be reaching for. The local form is rejected one check
161
+ // earlier by ContentReadScan, as is `show <local-rev>:<path>`.
162
+ 'grep',
163
+ ]);
164
+ // The `gh` subcommands that write LOCAL files — the only ones the branch state has anything to say
165
+ // about. Everything else `gh` does happens on GitHub's side. (`gh pr create` / `gh pr merge` are absent
166
+ // on purpose: they are remote calls, and their policies live in pr-creation-or-push-guard and
167
+ // pr-merge-guard, which run whatever this list says.)
168
+ const GH_LOCAL_FILE_WRITES = new Map([
169
+ ['repo', new Set(['clone', 'fork', 'sync'])],
170
+ ['pr', new Set(['checkout'])],
171
+ ['run', new Set(['download'])],
172
+ ['release', new Set(['download'])],
173
+ ['gist', new Set(['clone'])],
174
+ ['codespace', new Set(['cp'])],
175
+ ['attestation', new Set(['download'])],
176
+ ]);
177
+ // Network clients: they read a URL, not the tree.
178
+ const NETWORK_CLIENTS = new Set(['curl', 'wget']);
179
+ // The flags that turn a fetch into a local file write. `-O` is curl's remote-name AND wget's
180
+ // output-document; both write, so one entry covers both.
181
+ const OUTPUT_FILE_FLAGS = new Set([
182
+ '-o', '--output', '-O', '--remote-name', '--remote-name-all', '--output-dir', '--create-dirs',
183
+ '--output-document', '-P', '--directory-prefix',
184
+ ]);
185
+ const PACKAGE_MANAGERS = new Set(['pnpm', 'npm', 'npx', 'pnpx', 'yarn']);
186
+ const PACKAGE_INSTALL_VERBS = new Set(['install', 'ci', 'add', 'i']);
187
+ //# sourceMappingURL=recovery-allowlist.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"recovery-allowlist.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/agent-workflow-rules/src/core/rules/recovery-allowlist.ts"],"names":[],"mappings":";;;;AAAA,mDAA6B;AAI7B,0DAA2E;AAC3E,2DAAsD;AAEtD,8EAA8E;AAC9E,mDAAmD;AACnD,EAAE;AACF,sGAAsG;AACtG,iFAAiF;AACjF,EAAE;AACF,kGAAkG;AAClG,mGAAmG;AACnG,uGAAuG;AACvG,6CAA6C;AAC7C,EAAE;AACF,uGAAuG;AACvG,sGAAsG;AACtG,iGAAiG;AACjG,+DAA+D;AAC/D,EAAE;AACF,+FAA+F;AAC/F,qGAAqG;AACrG,wGAAwG;AACxG,qGAAqG;AACrG,uGAAuG;AACvG,qGAAqG;AACrG,qDAAqD;AACrD,EAAE;AACF,kGAAkG;AAClG,mGAAmG;AACnG,uGAAuG;AACvG,8EAA8E;AAC9E,0FAA0F;AA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AAK,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;AAC9F,MAAM,qBAAqB,GAAwB,IAAI,GAAG,CAAC,CAAC,SAAS,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,CAAC,CAAC,CAAC","sourcesContent":["import * as path from 'path';\n\nimport type { BashContext } from '@webpieces/hook-runtime';\nimport { CommandScanner, CommandSegment } from '@webpieces/hook-runtime';\nimport { ShellSegmentScan, SegmentVerdict } from '@webpieces/hook-runtime';\nimport { ContentReadScan } from './content-read-scan';\n\n// ---------------------------------------------------------------------------\n// THE SKIP LIST — L2 row 4, as one implementation.\n//\n// \"These get you OUT, or tell you where you are.\" That is the whole principle: a command on this list\n// is not \"working here\", so it is safe in every state where working here is not.\n//\n// It was written for state B (a merged branch) and lived inside merged-branch-bash-guard. Row 5 —\n// on `main` — needs the identical question answered, and the answer must not be a second copy: two\n// skip lists drift, and the half that drifts is the half that wedges a session on its own cure. So the\n// list is ONE class, and both guards ask it.\n//\n// This is the DEFAULT-DENY half of L2. Its sibling ContentReadScan is the default-ALLOW blocklist used\n// where only stale CONTENT is the hazard. The guards docblock is right that the two polarities cannot\n// collapse into one function — but the allowlist itself was never the reason they could not, and\n// sharing it is what makes row 5's `B` half affordable at all.\n//\n// WHAT BELONGS ON THIS LIST — one question, asked of the COMMAND, not of your sympathy for it:\n// **does it read or write repo content?** If it cannot do either, it cannot be \"working here\", so it\n// belongs here regardless of what else it does. That is why `curl`/`wget` and `gh` are on it: they talk\n// to a network, not to the working tree, and a session parked in an L2 state still has to be able to\n// close a PR, comment on one, or fetch a URL. It is also why the exclusions are the FORMS that write a\n// local file (`curl -o`, `gh repo clone`, `gh pr checkout`, any `> file` redirect) rather than whole\n// programs: the write is the hazard, not the binary.\n//\n// EVERY segment must pass. One `… && scripts/local.sh start` in a chain denies the whole command,\n// because the chain runs it. Segments are judged by ROLE first: shell STRUCTURE (`for … in`, `do`,\n// `done`) invokes nothing and output SHAPING (`| tail -40`) cannot touch the repo, so neither may veto\n// a chain — judging the raw string instead is what once made the guard reject\n// `git fetch origin main 2>&1 | tail -5`, a command its own redirect had just prescribed.\n// ---------------------------------------------------------------------------\nexport class RecoveryAllowlist {\n private readonly scanner: CommandScanner;\n private readonly shell: ShellSegmentScan;\n\n constructor(scanner: CommandScanner) {\n this.scanner = scanner;\n this.shell = new ShellSegmentScan(scanner);\n }\n\n /**\n * Is EVERY segment of this command one that gets you out, or tells you where you are?\n *\n * An empty command is `false` — nothing to be sure about, and the default here is deny. (Note this\n * is one of the three places the two Bash guards genuinely differ; the stale-main blocklist allows\n * the empty command because its default is the other way round.)\n */\n isFullyRecovery(ctx: BashContext): boolean {\n const segments = this.scanner.segmentsWithJoins(ctx.command);\n if (segments.length === 0) return false;\n const content = new ContentReadScan(this.scanner, ctx.workspaceRoot, ctx.effectiveCwd);\n return segments.every((segment: CommandSegment): boolean => this.isRecoverySegment(segment, content));\n }\n\n private isRecoverySegment(segment: CommandSegment, content: ContentReadScan): boolean {\n const verdict = this.shell.classify(segment);\n if (verdict.role === 'structure') return true;\n // Inert / piped-into filters are fine EXCEPT when they name a workspace path: `git status |\n // cat src/foo.ts` still hands the agent file content out of a tree it should not be reading.\n if (verdict.role === 'shaping') return content.readsStaleContent(segment) === null;\n\n // A read that names NOTHING in this tree cannot be affected by which branch this tree is on.\n // `ls -la ~/.claude/projects/ | grep -i foo` was blocked as \"this branch is merged\" — the\n // command touches no repo at all. Only CONTENT READERS qualify, so a build, a server or a git\n // write never slips through on the strength of its paths.\n if (content.readsOnlyOutsideContent(segment)) return true;\n\n // A segment that reads CONTENT out of this tree is never \"getting you out\", whatever command\n // it is spelled as. This must come BEFORE the git allowlist, because `show` and `grep` are on\n // that list for their metadata/upstream forms and would otherwise wave through the two git\n // spellings of a local content read: `git show HEAD:package.json` and `git grep TODO`. Their\n // upstream forms (`git show origin/main:…`, `git grep TODO origin/main`) read the CURRENT tree\n // and ContentReadScan already returns null for those, so they stay allowed — which is the\n // point, since reading upstream is exactly what a blocked agent should be doing.\n if (content.readsStaleContent(segment) !== null) return false;\n\n const gitSub = this.scanner.gitSubcommandOf(verdict.words);\n if (gitSub !== null) return ALLOWED_GIT_SUBCOMMANDS.has(gitSub);\n if (this.isGh(verdict)) return true;\n if (this.isNetworkClient(verdict)) return true;\n return this.isPackageRecovery(verdict);\n }\n\n /**\n * `gh` GENERALLY — it talks to GitHub, not to the working tree.\n *\n * This used to be an allowlist of read-only actions (`gh pr view|list|status|checks`, `gh run\n * view`), which fell over the moment an agent needed `gh pr close`, `gh pr comment` or `gh api`\n * from a parked session: those change something on GitHub and NOTHING in this tree, so the branch\n * state cannot be an argument against them. The exclusions are therefore the `gh` subcommands that\n * write LOCAL files — a clone, a checkout, a download — plus any segment carrying a `> file`\n * redirect.\n *\n * gh commands that are wrong for OTHER reasons stay wrong: `gh pr create`/`push` is governed by\n * pr-creation-or-push-guard and `gh pr merge` by pr-merge-guard. Those are separate policies and\n * this list was never what enforced them.\n *\n * YES, THIS ONE SUBLIST IS A BLOCKLIST, and that is the opposite polarity to the guard around it.\n * The argument against a blocklist elsewhere is that the hazardous set is UNBOUNDED — any program\n * can write a file as a side effect of doing something else, so no enumeration could ever be\n * complete. `gh`'s surface is not: it is one vendor's CLI, its verbs are documented, and writing\n * into the working tree is the rare exception rather than the ambient default. A new `gh`\n * subcommand that clones or downloads is a known, greppable maintenance point — `GH_LOCAL_FILE_WRITES`\n * — where \"every future program that might write\" is not.\n */\n private isGh(verdict: SegmentVerdict): boolean {\n const words = verdict.words;\n if (words.length === 0 || path.basename(words[0]) !== 'gh') return false;\n if (this.shell.redirectsToFile(words)) return false;\n const top = words[1];\n if (top === undefined) return false;\n const action = words[2];\n const localWrites = GH_LOCAL_FILE_WRITES.get(top);\n if (localWrites === undefined) return true;\n return action === undefined || !localWrites.has(action);\n }\n\n /**\n * `curl` / `wget` — a network fetch reads a URL, not this repo.\n *\n * Excluded: the forms that name a local FILE to write (`curl -o`, `curl -O`, `wget -O`, an\n * `--output-dir`/`-P`, or a `> file` redirect), because those are how a fetch becomes a write into\n * the tree. A bare `wget <url>` still drops its download into the cwd; that CREATES an untracked\n * file rather than modifying tracked content, which is the line this list draws everywhere else.\n */\n private isNetworkClient(verdict: SegmentVerdict): boolean {\n const words = verdict.words;\n if (words.length === 0 || !NETWORK_CLIENTS.has(path.basename(words[0]))) return false;\n if (this.shell.redirectsToFile(words)) return false;\n return !words.some((word: string): boolean => OUTPUT_FILE_FLAGS.has(word));\n }\n\n // pnpm/npm/yarn recovery bins: the `wp-*` cleanup/gated commands and package installs (a chained\n // install that isInstallerCommand — the pure-install bypass — did not catch reaches here).\n private isPackageRecovery(verdict: SegmentVerdict): boolean {\n const words = verdict.words;\n if (words.length === 0 || !PACKAGE_MANAGERS.has(words[0])) return false;\n return words.slice(1).some((word: string): boolean =>\n /^wp-[a-z-]+$/.test(word) || PACKAGE_INSTALL_VERBS.has(word));\n }\n}\n\nconst ALLOWED_GIT_SUBCOMMANDS: ReadonlySet<string> = new Set([\n 'status', 'log', 'diff', 'show', 'branch', 'checkout', 'switch', 'worktree', 'fetch', 'pull',\n 'rev-parse', 'rev-list', 'merge-base', 'ls-files', 'ls-tree', 'cat-file', 'for-each-ref',\n 'symbolic-ref', 'describe', 'name-rev', 'reflog', 'shortlog', 'remote', 'config', 'stash', 'tag',\n 'blame', 'whatchanged', 'cherry',\n // `grep` is here ONLY for its upstream form (`git grep TODO origin/main`), which reads the CURRENT\n // tree and is what a blocked agent should be reaching for. The local form is rejected one check\n // earlier by ContentReadScan, as is `show <local-rev>:<path>`.\n 'grep',\n]);\n\n// The `gh` subcommands that write LOCAL files — the only ones the branch state has anything to say\n// about. Everything else `gh` does happens on GitHub's side. (`gh pr create` / `gh pr merge` are absent\n// on purpose: they are remote calls, and their policies live in pr-creation-or-push-guard and\n// pr-merge-guard, which run whatever this list says.)\nconst GH_LOCAL_FILE_WRITES: ReadonlyMap<string, ReadonlySet<string>> = new Map([\n ['repo', new Set(['clone', 'fork', 'sync'])],\n ['pr', new Set(['checkout'])],\n ['run', new Set(['download'])],\n ['release', new Set(['download'])],\n ['gist', new Set(['clone'])],\n ['codespace', new Set(['cp'])],\n ['attestation', new Set(['download'])],\n]);\n\n// Network clients: they read a URL, not the tree.\nconst NETWORK_CLIENTS: ReadonlySet<string> = new Set(['curl', 'wget']);\n// The flags that turn a fetch into a local file write. `-O` is curl's remote-name AND wget's\n// output-document; both write, so one entry covers both.\nconst OUTPUT_FILE_FLAGS: ReadonlySet<string> = new Set([\n '-o', '--output', '-O', '--remote-name', '--remote-name-all', '--output-dir', '--create-dirs',\n '--output-document', '-P', '--directory-prefix',\n]);\n\nconst PACKAGE_MANAGERS: ReadonlySet<string> = new Set(['pnpm', 'npm', 'npx', 'pnpx', 'yarn']);\nconst PACKAGE_INSTALL_VERBS: ReadonlySet<string> = new Set(['install', 'ci', 'add', 'i']);\n"]}
@@ -0,0 +1,16 @@
1
+ import { PrLifecycleGuardConfig } from "../../configs/rule-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
+ export declare class RedirectHowToMergeMainRule extends BashRuleBase<PrLifecycleGuardConfig> {
6
+ private readonly scanner;
7
+ private readonly recovery;
8
+ private readonly switches;
9
+ constructor(config: PrLifecycleGuardConfig);
10
+ readonly description = "Block ALL `git merge`/`git rebase` (any branch, any form) and `git pull origin main` on a feature branch. Use the squash-update process instead.";
11
+ readonly fixHint: FixHint;
12
+ check(ctx: BashContext): readonly Violation[];
13
+ private checkSegment;
14
+ private checkPull;
15
+ private block;
16
+ }
@@ -0,0 +1,159 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RedirectHowToMergeMainRule = 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 hook_runtime_1 = require("@webpieces/hook-runtime");
8
+ const hook_runtime_2 = require("@webpieces/hook-runtime");
9
+ const hook_runtime_3 = require("@webpieces/hook-runtime");
10
+ const hook_runtime_4 = require("@webpieces/hook-runtime");
11
+ const tree_recovery_1 = require("./tree-recovery");
12
+ const branch_switch_scan_1 = require("./branch-switch-scan");
13
+ const INSTRUCT_FILE = 'webpieces.git-workflow.md';
14
+ const GUIDANCE = new rules_config_1.SyncFlowGuidance();
15
+ const FIX_HINT = new hook_runtime_3.FixHint('`git merge` / `git rebase` are never run by AI — on any branch, in any form.', 'To bring main\'s changes into your feature branch:\n'
16
+ + '\n'
17
+ + GUIDANCE.flows().join('\n') + '\n'
18
+ + '\n'
19
+ // The fork-point DERIVATION (why the invariant has two halves, and the three consumers a polluted
20
+ // fork point corrupts) and the WORD-FOR-WORD warning to hand the human are NOT here on purpose.
21
+ // Both are stated in full in the git-workflow doc this hint links by absolute path, and a message
22
+ // that re-derives what the linked doc already says is a second copy to keep in step. What survives
23
+ // here is only what changes what the AI types next.
24
+ + 'Either flow does a 3-point merge, which keeps the fork point a pure main commit — what the build\n'
25
+ + 'gate\'s --base and the PR review diff are computed from; a raw merge/rebase destroys it. The\n'
26
+ + 'gated commands merge internally as child processes this hook never sees.\n'
27
+ + '\n'
28
+ + GUIDANCE.readOnlyChecks().join('\n') + '\n'
29
+ + '\n'
30
+ // The "do not run it, ask the human, tell them to push back" instruction is NOT repeated here: the
31
+ // violation line the AI reads first already says it. This paragraph's job is only the pointer.
32
+ // The liveness phrase is kept on ONE line deliberately: it is asserted in full, and a wrap would
33
+ // split the assertion's substring across two chunks. The retired wording ("a branch you do not own")
34
+ // was pinned only by a `never sync a branch` PREFIX, which passed under both framings — which is how
35
+ // this hint kept teaching the removed rule after the doc it links had replaced it.
36
+ + 'READ the instruct-ai git-workflow doc at the absolute path on the violation line above — the full\n'
37
+ + 'flow (incl. worktrees), the fork-point invariant, why you must\n'
38
+ + 'never sync a branch something is ACTIVELY holding (liveness, not authorship — a finished agent\n'
39
+ + 'holds nothing), and the exact words to warn a human with when you ask them to run a merge.\n'
40
+ // NOT "add that info to memory": "that info" was the whole git-workflow doc, which is REGENERATED
41
+ // per repo and per version — memorizing it guarantees a stale recall in the next session. Only the
42
+ // invariant is stable enough to persist; the doc must be re-read, never remembered.
43
+ + 'Add to memory: never run a raw `git merge`/`git rebase` — use this repo\'s gated sync flow and\n'
44
+ + 're-read its git-workflow doc each time rather than recalling it (regenerated per repo/version).');
45
+ // `git merge --abort` / `git rebase --abort|--quit` UNDO an in-progress operation — they cannot create
46
+ // a merge commit or rewrite history, so they cannot violate the fork-point invariant this rule
47
+ // protects. They stay allowed so a repo left mid-operation (e.g. by a human-run rebase) can still be
48
+ // cleaned up. `--continue` is deliberately NOT here: it COMPLETES the operation.
49
+ const UNDO_FLAG = /--(?:abort|quit)\b/;
50
+ // Typed as a query ("would this fast-forward?"), but a successful --ff-only IS the merge.
51
+ const FF_ONLY = /--ff-only\b/;
52
+ // webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API
53
+ function truncate(s) {
54
+ const MAX = 120;
55
+ return s.length <= MAX ? s : s.slice(0, MAX) + '…';
56
+ }
57
+ class RedirectHowToMergeMainRule extends hook_runtime_2.BashRuleBase {
58
+ scanner = new hook_runtime_4.CommandScanner();
59
+ recovery = new tree_recovery_1.TreeRecovery();
60
+ // "Which branch does this land on?" — see branch-switch-scan.ts. It replaced a pair of regexes
61
+ // here (`/git\s+(?:checkout|switch)\s+main\b/` and its negative-lookahead twin) that assumed the
62
+ // branch name is the token immediately after the subcommand. One flag broke both halves at once:
63
+ // `git checkout -q main && git pull -q origin main` missed the main EXEMPTION and then tripped the
64
+ // feature-switch block, so this guard rejected the very command stale-main-bash-guard prescribes,
65
+ // with a reason ("switches to a feature branch") that was the opposite of the truth.
66
+ switches = new branch_switch_scan_1.BranchSwitchScan(this.scanner);
67
+ constructor(config) { super(config, 'redirect-how-to-merge-main', policy_keys_1.PR_LIFECYCLE_GUARD_KEY); }
68
+ description = 'Block ALL `git merge`/`git rebase` (any branch, any form) and `git pull origin main` on a feature branch. Use the squash-update process instead.';
69
+ fixHint = FIX_HINT;
70
+ check(ctx) {
71
+ for (const segment of this.scanner.commandSegments(ctx.command)) {
72
+ const violation = this.checkSegment(ctx, segment);
73
+ if (violation !== null)
74
+ return [violation];
75
+ }
76
+ return [];
77
+ }
78
+ checkSegment(ctx, segment) {
79
+ // 1. merge/rebase: unconditional block. Deliberately NO branch lookup.
80
+ //
81
+ // This rule used to read hook-time HEAD and bail out when it was `main`. But a PreToolUse hook
82
+ // runs BEFORE the command, so HEAD-at-hook-time is a value the command itself is about to
83
+ // change: `git checkout feat && git rebase main`, issued while HEAD was still `main` from a
84
+ // prior cleanup, read as "we're on main, this is fine" and was waved through. That is the
85
+ // incident this rule exists to prevent. Since merge/rebase have no legitimate AI-run form on
86
+ // ANY branch, there is no branch to consult — and so no HEAD to spoof.
87
+ if (this.scanner.invokesGit(segment, 'merge') || this.scanner.invokesGit(segment, 'rebase')) {
88
+ if (UNDO_FLAG.test(segment))
89
+ return null;
90
+ // `--ff-only` reads like a probe ("can I fast-forward?") but it MUTATES whenever the answer
91
+ // is yes, so say that here — the AI that typed it was usually only trying to look.
92
+ const probe = FF_ONLY.test(segment)
93
+ ? ' `--ff-only` is NOT a read-only check — it moves your branch whenever it succeeds; see the read-only checks below.'
94
+ : '';
95
+ return this.block(ctx, segment, 'Direct `git merge`/`git rebase` is blocked — AI never runs it, on any branch.' + probe);
96
+ }
97
+ // 2. pull: unlike merge/rebase this DOES retain a legitimate on-main form
98
+ // (`git checkout main && git pull origin main`), so it must consult the branch — which is
99
+ // exactly why it also needs the branch-switch check that (1) no longer requires.
100
+ if (this.scanner.invokesGit(segment, 'pull') && /\borigin\s+main\b/.test(segment)) {
101
+ return this.checkPull(ctx, segment);
102
+ }
103
+ return null;
104
+ }
105
+ checkPull(ctx, segment) {
106
+ // The two branch questions are COMPLEMENTS of one parse, so they are asked of one parse —
107
+ // that is what keeps them from disagreeing. `git branch -D <x>` is not a checkout so it does
108
+ // not trip this, and `git checkout -` (previous branch, unknowable at hook time) lands
109
+ // nowhere we can name, so it counts as neither.
110
+ const switches = this.switches.switchesIn(ctx.command);
111
+ if (switches.some((s) => !this.switches.isExistingMain(s))) {
112
+ return this.block(ctx, segment, 'Blocked: this command switches to a feature branch and then pulls main into it.');
113
+ }
114
+ // The hand-rolled `git checkout main && git pull origin main` — still ALLOWED, but ONLY in the
115
+ // primary clone. Inside a linked worktree that checkout FATALS ("'main' is already checked out
116
+ // at <primary>"), so waving it through here hands the AI a command that cannot work and costs
117
+ // it a turn to discover. Steer to the fetch, which is all a worktree needs.
118
+ //
119
+ // Note this rule stays a pure ALLOW for the raw pair and always will: the workflow layer now
120
+ // PRESCRIBES `pnpm wp-sync-main` (see TreeRecovery.updateMainSteps, which block()
121
+ // below renders), but prescribing is not blocking. The pair is plain git, and it is the L0
122
+ // recovery cure — a state in which no `pnpm` bin can be trusted to run — so making it a block
123
+ // here would delete the only escape from a deadlock. What changed is what the guards TEACH.
124
+ if (switches.length > 0) {
125
+ if (this.recovery.kindOf(ctx.workspaceRoot) !== 'worktree')
126
+ return null;
127
+ // block() appends updateMainSteps for the tree we are in — don't say it twice here.
128
+ return this.block(ctx, segment, 'Blocked.');
129
+ }
130
+ const currentBranch = (0, child_process_1.execSync)('git rev-parse --abbrev-ref HEAD', {
131
+ cwd: ctx.workspaceRoot,
132
+ encoding: 'utf8',
133
+ }).trim();
134
+ if (currentBranch === 'main')
135
+ return null;
136
+ return this.block(ctx, segment, `Pulling main into feature branch '${currentBranch}' is blocked.`);
137
+ }
138
+ block(ctx, segment, what) {
139
+ // Materialize the doc we are about to send the AI to. This guard fires long before any `wp-*`
140
+ // command runs (those are what normally write it), so the linked path could easily not exist —
141
+ // and a STALE copy from an older @webpieces is just as misleading, hence overwrite.
142
+ (0, rules_config_1.writeTemplate)(ctx.workspaceRoot, INSTRUCT_FILE);
143
+ const docPath = new rules_config_1.RepoRootFinder().instructAiDocPath(ctx.workspaceRoot, INSTRUCT_FILE);
144
+ // "How do I get MAIN itself current?" is a different question from "sync my feature branch",
145
+ // and it used to have no answer anywhere on this path — the flows cover feature branches and
146
+ // the read-only checks cover looking. An AI on main with no third option improvises, and what
147
+ // it improvises is `git reset --hard origin/main`. Answer the question instead, shaped to the
148
+ // tree we are actually in (in a worktree `git checkout main` fatals).
149
+ const updateMain = [
150
+ '',
151
+ 'On main and just wanted to bring MAIN itself up to date? That is a different question from',
152
+ 'syncing a feature branch, and merge/reset is not the answer to it:',
153
+ ...this.recovery.updateMainSteps(this.recovery.kindOf(ctx.workspaceRoot)),
154
+ ].join('\n');
155
+ return new hook_runtime_1.Violation(1, truncate(segment), `${what} Use the gated 3-point flow instead: 'pnpm wp-start-update' → 'pnpm wp-finish-update' when NO PR is open, or 'pnpm wp-start-upsert-pr' → 'pnpm wp-finish-upsert-pr' when a PR IS open (required then — the merge rewrites the branch and the PR must be re-pointed in the same run). If you truly need a raw merge/rebase, ask the HUMAN to run it — and warn them to push back. Full flow: READ ${docPath}.${updateMain}`);
156
+ }
157
+ }
158
+ exports.RedirectHowToMergeMainRule = RedirectHowToMergeMainRule;
159
+ //# sourceMappingURL=redirect-how-to-merge-main.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redirect-how-to-merge-main.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/agent-workflow-rules/src/core/rules/redirect-how-to-merge-main.ts"],"names":[],"mappings":";;;AAAA,iDAAyC;AAEzC,0DAA0F;AAC1F,mDAA2D;AAI3D,0DAAyD;AACzD,0DAAuD;AACvD,0DAAkD;AAClD,0DAAyD;AACzD,mDAA+C;AAC/C,6DAAsE;AAEtE,MAAM,aAAa,GAAG,2BAA2B,CAAC;AAClD,MAAM,QAAQ,GAAG,IAAI,+BAAgB,EAAE,CAAC;AAExC,MAAM,QAAQ,GAAG,IAAI,sBAAO,CACxB,8EAA8E,EAC9E,sDAAsD;MACpD,IAAI;MACJ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K,CAAC,GAAG,EAAE,OAAO,EAAE,qCAAqC,aAAa,eAAe,CAAC,CAAC;IACvG,CAAC;IAEO,KAAK,CAAC,GAAgB,EAAE,OAAe,EAAE,IAAY;QACzD,8FAA8F;QAC9F,+FAA+F;QAC/F,oFAAoF;QACpF,IAAA,4BAAa,EAAC,GAAG,CAAC,aAAa,EAAE,aAAa,CAAC,CAAC;QAChD,MAAM,OAAO,GAAG,IAAI,6BAAc,EAAE,CAAC,iBAAiB,CAAC,GAAG,CAAC,aAAa,EAAE,aAAa,CAAC,CAAC;QACzF,6FAA6F;QAC7F,6FAA6F;QAC7F,8FAA8F;QAC9F,8FAA8F;QAC9F,sEAAsE;QACtE,MAAM,UAAU,GAAG;YACf,EAAE;YACF,4FAA4F;YAC5F,oEAAoE;YACpE,GAAG,IAAI,CAAC,QAAQ,CAAC,eAAe,CAAC,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;SAC5E,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACb,OAAO,IAAI,wBAAC,CACR,CAAC,EACD,QAAQ,CAAC,OAAO,CAAC,EACjB,GAAG,IAAI,oYAAoY,OAAO,IAAI,UAAU,EAAE,CACra,CAAC;IACN,CAAC;CACJ;AA9GD,gEA8GC","sourcesContent":["import { execSync } from 'child_process';\n\nimport { RepoRootFinder, SyncFlowGuidance, writeTemplate } from '@webpieces/rules-config';\nimport { PR_LIFECYCLE_GUARD_KEY } from '../../policy-keys';\nimport { PrLifecycleGuardConfig } from \"../../configs/rule-configs\";\n\nimport type { BashContext, Violation } from '@webpieces/hook-runtime';\nimport { Violation as V } from '@webpieces/hook-runtime';\nimport { BashRuleBase } from '@webpieces/hook-runtime';\nimport { FixHint } from '@webpieces/hook-runtime';\nimport { CommandScanner } from '@webpieces/hook-runtime';\nimport { TreeRecovery } from './tree-recovery';\nimport { BranchSwitch, BranchSwitchScan } from './branch-switch-scan';\n\nconst INSTRUCT_FILE = 'webpieces.git-workflow.md';\nconst GUIDANCE = new SyncFlowGuidance();\n\nconst FIX_HINT = new FixHint(\n '`git merge` / `git rebase` are never run by AI — on any branch, in any form.',\n 'To bring main\\'s changes into your feature branch:\\n'\n + '\\n'\n + GUIDANCE.flows().join('\\n') + '\\n'\n + '\\n'\n // The fork-point DERIVATION (why the invariant has two halves, and the three consumers a polluted\n // fork point corrupts) and the WORD-FOR-WORD warning to hand the human are NOT here on purpose.\n // Both are stated in full in the git-workflow doc this hint links by absolute path, and a message\n // that re-derives what the linked doc already says is a second copy to keep in step. What survives\n // here is only what changes what the AI types next.\n + 'Either flow does a 3-point merge, which keeps the fork point a pure main commit — what the build\\n'\n + 'gate\\'s --base and the PR review diff are computed from; a raw merge/rebase destroys it. The\\n'\n + 'gated commands merge internally as child processes this hook never sees.\\n'\n + '\\n'\n + GUIDANCE.readOnlyChecks().join('\\n') + '\\n'\n + '\\n'\n // The \"do not run it, ask the human, tell them to push back\" instruction is NOT repeated here: the\n // violation line the AI reads first already says it. This paragraph's job is only the pointer.\n // The liveness phrase is kept on ONE line deliberately: it is asserted in full, and a wrap would\n // split the assertion's substring across two chunks. The retired wording (\"a branch you do not own\")\n // was pinned only by a `never sync a branch` PREFIX, which passed under both framings — which is how\n // this hint kept teaching the removed rule after the doc it links had replaced it.\n + 'READ the instruct-ai git-workflow doc at the absolute path on the violation line above — the full\\n'\n + 'flow (incl. worktrees), the fork-point invariant, why you must\\n'\n + 'never sync a branch something is ACTIVELY holding (liveness, not authorship — a finished agent\\n'\n + 'holds nothing), and the exact words to warn a human with when you ask them to run a merge.\\n'\n // NOT \"add that info to memory\": \"that info\" was the whole git-workflow doc, which is REGENERATED\n // per repo and per version — memorizing it guarantees a stale recall in the next session. Only the\n // invariant is stable enough to persist; the doc must be re-read, never remembered.\n + 'Add to memory: never run a raw `git merge`/`git rebase` — use this repo\\'s gated sync flow and\\n'\n + 're-read its git-workflow doc each time rather than recalling it (regenerated per repo/version).',\n);\n\n// `git merge --abort` / `git rebase --abort|--quit` UNDO an in-progress operation — they cannot create\n// a merge commit or rewrite history, so they cannot violate the fork-point invariant this rule\n// protects. They stay allowed so a repo left mid-operation (e.g. by a human-run rebase) can still be\n// cleaned up. `--continue` is deliberately NOT here: it COMPLETES the operation.\nconst UNDO_FLAG = /--(?:abort|quit)\\b/;\n\n// Typed as a query (\"would this fast-forward?\"), but a successful --ff-only IS the merge.\nconst FF_ONLY = /--ff-only\\b/;\n\n// webpieces-disable no-function-outside-class -- existing stateless module helper moved intact with its callers; ownership extraction preserves its functional API\nfunction truncate(s: string): string {\n const MAX = 120;\n return s.length <= MAX ? s : s.slice(0, MAX) + '…';\n}\n\nexport class RedirectHowToMergeMainRule extends BashRuleBase<PrLifecycleGuardConfig> {\n private readonly scanner = new CommandScanner();\n private readonly recovery = new TreeRecovery();\n // \"Which branch does this land on?\" — see branch-switch-scan.ts. It replaced a pair of regexes\n // here (`/git\\s+(?:checkout|switch)\\s+main\\b/` and its negative-lookahead twin) that assumed the\n // branch name is the token immediately after the subcommand. One flag broke both halves at once:\n // `git checkout -q main && git pull -q origin main` missed the main EXEMPTION and then tripped the\n // feature-switch block, so this guard rejected the very command stale-main-bash-guard prescribes,\n // with a reason (\"switches to a feature branch\") that was the opposite of the truth.\n private readonly switches = new BranchSwitchScan(this.scanner);\n\n constructor(config: PrLifecycleGuardConfig) { super(config, 'redirect-how-to-merge-main', PR_LIFECYCLE_GUARD_KEY); }\n\n readonly description = 'Block ALL `git merge`/`git rebase` (any branch, any form) and `git pull origin main` on a feature branch. Use the squash-update process instead.';\n readonly fixHint = FIX_HINT;\n\n check(ctx: BashContext): readonly Violation[] {\n for (const segment of this.scanner.commandSegments(ctx.command)) {\n const violation = this.checkSegment(ctx, segment);\n if (violation !== null) return [violation];\n }\n return [];\n }\n\n private checkSegment(ctx: BashContext, segment: string): Violation | null {\n // 1. merge/rebase: unconditional block. Deliberately NO branch lookup.\n //\n // This rule used to read hook-time HEAD and bail out when it was `main`. But a PreToolUse hook\n // runs BEFORE the command, so HEAD-at-hook-time is a value the command itself is about to\n // change: `git checkout feat && git rebase main`, issued while HEAD was still `main` from a\n // prior cleanup, read as \"we're on main, this is fine\" and was waved through. That is the\n // incident this rule exists to prevent. Since merge/rebase have no legitimate AI-run form on\n // ANY branch, there is no branch to consult — and so no HEAD to spoof.\n if (this.scanner.invokesGit(segment, 'merge') || this.scanner.invokesGit(segment, 'rebase')) {\n if (UNDO_FLAG.test(segment)) return null;\n // `--ff-only` reads like a probe (\"can I fast-forward?\") but it MUTATES whenever the answer\n // is yes, so say that here — the AI that typed it was usually only trying to look.\n const probe = FF_ONLY.test(segment)\n ? ' `--ff-only` is NOT a read-only check — it moves your branch whenever it succeeds; see the read-only checks below.'\n : '';\n return this.block(ctx, segment, 'Direct `git merge`/`git rebase` is blocked — AI never runs it, on any branch.' + probe);\n }\n\n // 2. pull: unlike merge/rebase this DOES retain a legitimate on-main form\n // (`git checkout main && git pull origin main`), so it must consult the branch — which is\n // exactly why it also needs the branch-switch check that (1) no longer requires.\n if (this.scanner.invokesGit(segment, 'pull') && /\\borigin\\s+main\\b/.test(segment)) {\n return this.checkPull(ctx, segment);\n }\n\n return null;\n }\n\n private checkPull(ctx: BashContext, segment: string): Violation | null {\n // The two branch questions are COMPLEMENTS of one parse, so they are asked of one parse —\n // that is what keeps them from disagreeing. `git branch -D <x>` is not a checkout so it does\n // not trip this, and `git checkout -` (previous branch, unknowable at hook time) lands\n // nowhere we can name, so it counts as neither.\n const switches = this.switches.switchesIn(ctx.command);\n if (switches.some((s: BranchSwitch): boolean => !this.switches.isExistingMain(s))) {\n return this.block(ctx, segment, 'Blocked: this command switches to a feature branch and then pulls main into it.');\n }\n // The hand-rolled `git checkout main && git pull origin main` — still ALLOWED, but ONLY in the\n // primary clone. Inside a linked worktree that checkout FATALS (\"'main' is already checked out\n // at <primary>\"), so waving it through here hands the AI a command that cannot work and costs\n // it a turn to discover. Steer to the fetch, which is all a worktree needs.\n //\n // Note this rule stays a pure ALLOW for the raw pair and always will: the workflow layer now\n // PRESCRIBES `pnpm wp-sync-main` (see TreeRecovery.updateMainSteps, which block()\n // below renders), but prescribing is not blocking. The pair is plain git, and it is the L0\n // recovery cure — a state in which no `pnpm` bin can be trusted to run — so making it a block\n // here would delete the only escape from a deadlock. What changed is what the guards TEACH.\n if (switches.length > 0) {\n if (this.recovery.kindOf(ctx.workspaceRoot) !== 'worktree') return null;\n // block() appends updateMainSteps for the tree we are in — don't say it twice here.\n return this.block(ctx, segment, 'Blocked.');\n }\n\n const currentBranch = execSync('git rev-parse --abbrev-ref HEAD', {\n cwd: ctx.workspaceRoot,\n encoding: 'utf8',\n }).trim();\n if (currentBranch === 'main') return null;\n\n return this.block(ctx, segment, `Pulling main into feature branch '${currentBranch}' is blocked.`);\n }\n\n private block(ctx: BashContext, segment: string, what: string): Violation {\n // Materialize the doc we are about to send the AI to. This guard fires long before any `wp-*`\n // command runs (those are what normally write it), so the linked path could easily not exist —\n // and a STALE copy from an older @webpieces is just as misleading, hence overwrite.\n writeTemplate(ctx.workspaceRoot, INSTRUCT_FILE);\n const docPath = new RepoRootFinder().instructAiDocPath(ctx.workspaceRoot, INSTRUCT_FILE);\n // \"How do I get MAIN itself current?\" is a different question from \"sync my feature branch\",\n // and it used to have no answer anywhere on this path — the flows cover feature branches and\n // the read-only checks cover looking. An AI on main with no third option improvises, and what\n // it improvises is `git reset --hard origin/main`. Answer the question instead, shaped to the\n // tree we are actually in (in a worktree `git checkout main` fatals).\n const updateMain = [\n '',\n 'On main and just wanted to bring MAIN itself up to date? That is a different question from',\n 'syncing a feature branch, and merge/reset is not the answer to it:',\n ...this.recovery.updateMainSteps(this.recovery.kindOf(ctx.workspaceRoot)),\n ].join('\\n');\n return new V(\n 1,\n truncate(segment),\n `${what} Use the gated 3-point flow instead: 'pnpm wp-start-update' → 'pnpm wp-finish-update' when NO PR is open, or 'pnpm wp-start-upsert-pr' → 'pnpm wp-finish-upsert-pr' when a PR IS open (required then — the merge rewrites the branch and the PR must be re-pointed in the same run). If you truly need a raw merge/rebase, ask the HUMAN to run it — and warn them to push back. Full flow: READ ${docPath}.${updateMain}`,\n );\n }\n}\n"]}