oh-my-copilot 5.25.2 → 5.26.0

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 (257) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +1 -0
  4. package/bridge/claude-md-coordinator.cjs +2 -2
  5. package/bridge/cli.cjs +9249 -4138
  6. package/bridge/mcp-server.cjs +4894 -1400
  7. package/bridge/runtime-cli.cjs +14 -9
  8. package/bridge/team-mcp.cjs +3 -2
  9. package/bridge/team.js +14 -9
  10. package/dist/cli/commands/factory-bench.d.ts +10 -0
  11. package/dist/cli/commands/factory-bench.d.ts.map +1 -0
  12. package/dist/cli/commands/factory-bench.js +122 -0
  13. package/dist/cli/commands/factory-bench.js.map +1 -0
  14. package/dist/cli/commands/factory-dashboard.d.ts +14 -0
  15. package/dist/cli/commands/factory-dashboard.d.ts.map +1 -0
  16. package/dist/cli/commands/factory-dashboard.js +51 -0
  17. package/dist/cli/commands/factory-dashboard.js.map +1 -0
  18. package/dist/cli/commands/factory.d.ts.map +1 -1
  19. package/dist/cli/commands/factory.js +10 -2
  20. package/dist/cli/commands/factory.js.map +1 -1
  21. package/dist/copilot-run/__tests__/job.fail-closed.test.d.ts +2 -0
  22. package/dist/copilot-run/__tests__/job.fail-closed.test.d.ts.map +1 -0
  23. package/dist/copilot-run/__tests__/job.fail-closed.test.js +64 -0
  24. package/dist/copilot-run/__tests__/job.fail-closed.test.js.map +1 -0
  25. package/dist/copilot-run/__tests__/job.large-tree.test.d.ts +2 -0
  26. package/dist/copilot-run/__tests__/job.large-tree.test.d.ts.map +1 -0
  27. package/dist/copilot-run/__tests__/job.large-tree.test.js +47 -0
  28. package/dist/copilot-run/__tests__/job.large-tree.test.js.map +1 -0
  29. package/dist/copilot-run/__tests__/sandbox.test.js +125 -1
  30. package/dist/copilot-run/__tests__/sandbox.test.js.map +1 -1
  31. package/dist/copilot-run/job.d.ts.map +1 -1
  32. package/dist/copilot-run/job.js +14 -3
  33. package/dist/copilot-run/job.js.map +1 -1
  34. package/dist/copilot-run/sandbox.d.ts +53 -0
  35. package/dist/copilot-run/sandbox.d.ts.map +1 -1
  36. package/dist/copilot-run/sandbox.js +176 -14
  37. package/dist/copilot-run/sandbox.js.map +1 -1
  38. package/dist/factory/bench/__tests__/bench.fake.test.d.ts +2 -0
  39. package/dist/factory/bench/__tests__/bench.fake.test.d.ts.map +1 -0
  40. package/dist/factory/bench/__tests__/bench.fake.test.js +87 -0
  41. package/dist/factory/bench/__tests__/bench.fake.test.js.map +1 -0
  42. package/dist/factory/bench/__tests__/bench.smoke.test.d.ts +2 -0
  43. package/dist/factory/bench/__tests__/bench.smoke.test.d.ts.map +1 -0
  44. package/dist/factory/bench/__tests__/bench.smoke.test.js +54 -0
  45. package/dist/factory/bench/__tests__/bench.smoke.test.js.map +1 -0
  46. package/dist/factory/bench/__tests__/bench.units.test.d.ts +2 -0
  47. package/dist/factory/bench/__tests__/bench.units.test.d.ts.map +1 -0
  48. package/dist/factory/bench/__tests__/bench.units.test.js +842 -0
  49. package/dist/factory/bench/__tests__/bench.units.test.js.map +1 -0
  50. package/dist/factory/bench/fake-lanes.d.ts +39 -0
  51. package/dist/factory/bench/fake-lanes.d.ts.map +1 -0
  52. package/dist/factory/bench/fake-lanes.js +127 -0
  53. package/dist/factory/bench/fake-lanes.js.map +1 -0
  54. package/dist/factory/bench/fixture.d.ts +55 -0
  55. package/dist/factory/bench/fixture.d.ts.map +1 -0
  56. package/dist/factory/bench/fixture.js +128 -0
  57. package/dist/factory/bench/fixture.js.map +1 -0
  58. package/dist/factory/bench/model-probe.d.ts +37 -0
  59. package/dist/factory/bench/model-probe.d.ts.map +1 -0
  60. package/dist/factory/bench/model-probe.js +148 -0
  61. package/dist/factory/bench/model-probe.js.map +1 -0
  62. package/dist/factory/bench/runner.d.ts +163 -0
  63. package/dist/factory/bench/runner.d.ts.map +1 -0
  64. package/dist/factory/bench/runner.js +687 -0
  65. package/dist/factory/bench/runner.js.map +1 -0
  66. package/dist/factory/bench/score.d.ts +211 -0
  67. package/dist/factory/bench/score.d.ts.map +1 -0
  68. package/dist/factory/bench/score.js +386 -0
  69. package/dist/factory/bench/score.js.map +1 -0
  70. package/dist/factory/bench/seed/issues.d.ts +51 -0
  71. package/dist/factory/bench/seed/issues.d.ts.map +1 -0
  72. package/dist/factory/bench/seed/issues.js +536 -0
  73. package/dist/factory/bench/seed/issues.js.map +1 -0
  74. package/dist/factory/bench/seed/project.d.ts +24 -0
  75. package/dist/factory/bench/seed/project.d.ts.map +1 -0
  76. package/dist/factory/bench/seed/project.js +216 -0
  77. package/dist/factory/bench/seed/project.js.map +1 -0
  78. package/dist/factory/check/__tests__/cli-local.test.js +17 -0
  79. package/dist/factory/check/__tests__/cli-local.test.js.map +1 -1
  80. package/dist/factory/check/cli.d.ts +14 -0
  81. package/dist/factory/check/cli.d.ts.map +1 -1
  82. package/dist/factory/check/cli.js +21 -0
  83. package/dist/factory/check/cli.js.map +1 -1
  84. package/dist/factory/dashboard/__tests__/dashboard.test.d.ts +2 -0
  85. package/dist/factory/dashboard/__tests__/dashboard.test.d.ts.map +1 -0
  86. package/dist/factory/dashboard/__tests__/dashboard.test.js +148 -0
  87. package/dist/factory/dashboard/__tests__/dashboard.test.js.map +1 -0
  88. package/dist/factory/dashboard/collect.d.ts +96 -0
  89. package/dist/factory/dashboard/collect.d.ts.map +1 -0
  90. package/dist/factory/dashboard/collect.js +234 -0
  91. package/dist/factory/dashboard/collect.js.map +1 -0
  92. package/dist/factory/dashboard/render.d.ts +11 -0
  93. package/dist/factory/dashboard/render.d.ts.map +1 -0
  94. package/dist/factory/dashboard/render.js +77 -0
  95. package/dist/factory/dashboard/render.js.map +1 -0
  96. package/dist/factory/poll.d.ts +2 -0
  97. package/dist/factory/poll.d.ts.map +1 -1
  98. package/dist/factory/poll.js +2 -2
  99. package/dist/factory/poll.js.map +1 -1
  100. package/dist/factory/run/__tests__/auto-merge-flaky.test.d.ts +2 -0
  101. package/dist/factory/run/__tests__/auto-merge-flaky.test.d.ts.map +1 -0
  102. package/dist/factory/run/__tests__/auto-merge-flaky.test.js +131 -0
  103. package/dist/factory/run/__tests__/auto-merge-flaky.test.js.map +1 -0
  104. package/dist/factory/run/__tests__/auto-merge.test.d.ts +2 -0
  105. package/dist/factory/run/__tests__/auto-merge.test.d.ts.map +1 -0
  106. package/dist/factory/run/__tests__/auto-merge.test.js +541 -0
  107. package/dist/factory/run/__tests__/auto-merge.test.js.map +1 -0
  108. package/dist/factory/run/__tests__/container-gate.test.d.ts +2 -0
  109. package/dist/factory/run/__tests__/container-gate.test.d.ts.map +1 -0
  110. package/dist/factory/run/__tests__/container-gate.test.js +733 -0
  111. package/dist/factory/run/__tests__/container-gate.test.js.map +1 -0
  112. package/dist/factory/run/__tests__/engine.auto-merge.github.test.d.ts +2 -0
  113. package/dist/factory/run/__tests__/engine.auto-merge.github.test.d.ts.map +1 -0
  114. package/dist/factory/run/__tests__/engine.auto-merge.github.test.js +142 -0
  115. package/dist/factory/run/__tests__/engine.auto-merge.github.test.js.map +1 -0
  116. package/dist/factory/run/__tests__/engine.gates-container.test.d.ts +2 -0
  117. package/dist/factory/run/__tests__/engine.gates-container.test.d.ts.map +1 -0
  118. package/dist/factory/run/__tests__/engine.gates-container.test.js +245 -0
  119. package/dist/factory/run/__tests__/engine.gates-container.test.js.map +1 -0
  120. package/dist/factory/run/__tests__/engine.gates-git-view-fail.test.d.ts +2 -0
  121. package/dist/factory/run/__tests__/engine.gates-git-view-fail.test.d.ts.map +1 -0
  122. package/dist/factory/run/__tests__/engine.gates-git-view-fail.test.js +71 -0
  123. package/dist/factory/run/__tests__/engine.gates-git-view-fail.test.js.map +1 -0
  124. package/dist/factory/run/__tests__/engine.gates-git-view.test.d.ts +2 -0
  125. package/dist/factory/run/__tests__/engine.gates-git-view.test.d.ts.map +1 -0
  126. package/dist/factory/run/__tests__/engine.gates-git-view.test.js +141 -0
  127. package/dist/factory/run/__tests__/engine.gates-git-view.test.js.map +1 -0
  128. package/dist/factory/run/__tests__/engine.gates-workspace.test.d.ts +2 -0
  129. package/dist/factory/run/__tests__/engine.gates-workspace.test.d.ts.map +1 -0
  130. package/dist/factory/run/__tests__/engine.gates-workspace.test.js +130 -0
  131. package/dist/factory/run/__tests__/engine.gates-workspace.test.js.map +1 -0
  132. package/dist/factory/run/__tests__/engine.human-review.test.js +4 -4
  133. package/dist/factory/run/__tests__/engine.human-review.test.js.map +1 -1
  134. package/dist/factory/run/__tests__/engine.local.auto-merge.test.d.ts +2 -0
  135. package/dist/factory/run/__tests__/engine.local.auto-merge.test.d.ts.map +1 -0
  136. package/dist/factory/run/__tests__/engine.local.auto-merge.test.js +196 -0
  137. package/dist/factory/run/__tests__/engine.local.auto-merge.test.js.map +1 -0
  138. package/dist/factory/run/__tests__/engine.private.test.js +17 -0
  139. package/dist/factory/run/__tests__/engine.private.test.js.map +1 -1
  140. package/dist/factory/run/__tests__/fake-lanes.d.ts +2 -0
  141. package/dist/factory/run/__tests__/fake-lanes.d.ts.map +1 -1
  142. package/dist/factory/run/__tests__/fake-lanes.js +6 -1
  143. package/dist/factory/run/__tests__/fake-lanes.js.map +1 -1
  144. package/dist/factory/run/__tests__/git-view.test.d.ts +2 -0
  145. package/dist/factory/run/__tests__/git-view.test.d.ts.map +1 -0
  146. package/dist/factory/run/__tests__/git-view.test.js +120 -0
  147. package/dist/factory/run/__tests__/git-view.test.js.map +1 -0
  148. package/dist/factory/run/__tests__/merge-policy.test.js +10 -0
  149. package/dist/factory/run/__tests__/merge-policy.test.js.map +1 -1
  150. package/dist/factory/run/__tests__/prepare-gates.gates-resume.test.js +2 -0
  151. package/dist/factory/run/__tests__/prepare-gates.gates-resume.test.js.map +1 -1
  152. package/dist/factory/run/__tests__/prepare-gates.moving-base.test.d.ts +2 -0
  153. package/dist/factory/run/__tests__/prepare-gates.moving-base.test.d.ts.map +1 -0
  154. package/dist/factory/run/__tests__/prepare-gates.moving-base.test.js +103 -0
  155. package/dist/factory/run/__tests__/prepare-gates.moving-base.test.js.map +1 -0
  156. package/dist/factory/run/__tests__/private-run.test.js +37 -1
  157. package/dist/factory/run/__tests__/private-run.test.js.map +1 -1
  158. package/dist/factory/run/__tests__/units.test.js +8 -1
  159. package/dist/factory/run/__tests__/units.test.js.map +1 -1
  160. package/dist/factory/run/__tests__/workspace-tree.test.d.ts +2 -0
  161. package/dist/factory/run/__tests__/workspace-tree.test.d.ts.map +1 -0
  162. package/dist/factory/run/__tests__/workspace-tree.test.js +325 -0
  163. package/dist/factory/run/__tests__/workspace-tree.test.js.map +1 -0
  164. package/dist/factory/run/auto-merge.d.ts +254 -0
  165. package/dist/factory/run/auto-merge.d.ts.map +1 -0
  166. package/dist/factory/run/auto-merge.js +785 -0
  167. package/dist/factory/run/auto-merge.js.map +1 -0
  168. package/dist/factory/run/budget.d.ts +14 -0
  169. package/dist/factory/run/budget.d.ts.map +1 -1
  170. package/dist/factory/run/budget.js +24 -0
  171. package/dist/factory/run/budget.js.map +1 -1
  172. package/dist/factory/run/clean.d.ts +3 -0
  173. package/dist/factory/run/clean.d.ts.map +1 -1
  174. package/dist/factory/run/clean.js +34 -0
  175. package/dist/factory/run/clean.js.map +1 -1
  176. package/dist/factory/run/container-gate.d.ts +230 -0
  177. package/dist/factory/run/container-gate.d.ts.map +1 -0
  178. package/dist/factory/run/container-gate.js +1076 -0
  179. package/dist/factory/run/container-gate.js.map +1 -0
  180. package/dist/factory/run/engine.d.ts +5 -1
  181. package/dist/factory/run/engine.d.ts.map +1 -1
  182. package/dist/factory/run/engine.js +582 -40
  183. package/dist/factory/run/engine.js.map +1 -1
  184. package/dist/factory/run/exec.d.ts +5 -0
  185. package/dist/factory/run/exec.d.ts.map +1 -1
  186. package/dist/factory/run/exec.js +17 -3
  187. package/dist/factory/run/exec.js.map +1 -1
  188. package/dist/factory/run/git-view.d.ts +39 -0
  189. package/dist/factory/run/git-view.d.ts.map +1 -0
  190. package/dist/factory/run/git-view.js +77 -0
  191. package/dist/factory/run/git-view.js.map +1 -0
  192. package/dist/factory/run/lane-commit.d.ts +2 -0
  193. package/dist/factory/run/lane-commit.d.ts.map +1 -1
  194. package/dist/factory/run/lane-commit.js +3 -1
  195. package/dist/factory/run/lane-commit.js.map +1 -1
  196. package/dist/factory/run/local-gate.d.ts +1 -0
  197. package/dist/factory/run/local-gate.d.ts.map +1 -1
  198. package/dist/factory/run/local-gate.js +2 -1
  199. package/dist/factory/run/local-gate.js.map +1 -1
  200. package/dist/factory/run/merge-policy.d.ts +24 -6
  201. package/dist/factory/run/merge-policy.d.ts.map +1 -1
  202. package/dist/factory/run/merge-policy.js +29 -7
  203. package/dist/factory/run/merge-policy.js.map +1 -1
  204. package/dist/factory/run/prepare.d.ts +27 -1
  205. package/dist/factory/run/prepare.d.ts.map +1 -1
  206. package/dist/factory/run/prepare.js +241 -28
  207. package/dist/factory/run/prepare.js.map +1 -1
  208. package/dist/factory/run/private-run.d.ts +7 -0
  209. package/dist/factory/run/private-run.d.ts.map +1 -1
  210. package/dist/factory/run/private-run.js +34 -3
  211. package/dist/factory/run/private-run.js.map +1 -1
  212. package/dist/factory/run/private-store.d.ts +2 -0
  213. package/dist/factory/run/private-store.d.ts.map +1 -1
  214. package/dist/factory/run/private-store.js +2 -1
  215. package/dist/factory/run/private-store.js.map +1 -1
  216. package/dist/factory/run/sandbox-exec.d.ts +22 -1
  217. package/dist/factory/run/sandbox-exec.d.ts.map +1 -1
  218. package/dist/factory/run/sandbox-exec.js +9 -0
  219. package/dist/factory/run/sandbox-exec.js.map +1 -1
  220. package/dist/factory/run/workspace-tree.d.ts +75 -0
  221. package/dist/factory/run/workspace-tree.d.ts.map +1 -0
  222. package/dist/factory/run/workspace-tree.js +299 -0
  223. package/dist/factory/run/workspace-tree.js.map +1 -0
  224. package/dist/forge/__tests__/gh-argv-baseline.factory.test.js +7 -5
  225. package/dist/forge/__tests__/gh-argv-baseline.factory.test.js.map +1 -1
  226. package/dist/forge/github/__tests__/required-checks.test.js +22 -1
  227. package/dist/forge/github/__tests__/required-checks.test.js.map +1 -1
  228. package/dist/forge/github/checks.d.ts +9 -0
  229. package/dist/forge/github/checks.d.ts.map +1 -1
  230. package/dist/forge/github/checks.js +26 -0
  231. package/dist/forge/github/checks.js.map +1 -1
  232. package/dist/forge/github/merge.d.ts +27 -0
  233. package/dist/forge/github/merge.d.ts.map +1 -1
  234. package/dist/forge/github/merge.js +44 -0
  235. package/dist/forge/github/merge.js.map +1 -1
  236. package/dist/forge/github/reviews.d.ts +2 -0
  237. package/dist/forge/github/reviews.d.ts.map +1 -1
  238. package/dist/forge/github/reviews.js.map +1 -1
  239. package/dist/smoke/copilot-factory-run-scenario.d.ts.map +1 -1
  240. package/dist/smoke/copilot-factory-run-scenario.js +4 -0
  241. package/dist/smoke/copilot-factory-run-scenario.js.map +1 -1
  242. package/dist/team/git-worktree.d.ts +8 -1
  243. package/dist/team/git-worktree.d.ts.map +1 -1
  244. package/dist/team/git-worktree.js +9 -2
  245. package/dist/team/git-worktree.js.map +1 -1
  246. package/dist/team/merge-coordinator.js +5 -5
  247. package/dist/team/merge-coordinator.js.map +1 -1
  248. package/dist/team/merge-orchestrator.d.ts.map +1 -1
  249. package/dist/team/merge-orchestrator.js +3 -1
  250. package/dist/team/merge-orchestrator.js.map +1 -1
  251. package/dist/team/runtime-v2.d.ts.map +1 -1
  252. package/dist/team/runtime-v2.js +2 -2
  253. package/dist/team/runtime-v2.js.map +1 -1
  254. package/docs/CLAUDE.md +1 -1
  255. package/docs/REFERENCE.md +133 -1
  256. package/package.json +2 -2
  257. package/plugin.json +1 -1
@@ -0,0 +1,785 @@
1
+ /**
2
+ * Opt-in auto-merge by trust tier (night-4 goal 4). Merge stays a human step
3
+ * by default (merge-policy.ts); a repository whose USER config turns on
4
+ * `factory.merge.auto` lets the engine (trusted) merge a low-risk PR itself.
5
+ *
6
+ * Config, user config at its default location only (userConfigLayers
7
+ * `trustedUser`), keyed by repository: the run's repository URL (GitHub; same
8
+ * repoIdentity) or, on the local forge, the repository root path.
9
+ *
10
+ * "factory": { "merge": { "auto": {
11
+ * "https://github.com/o/r": { "enabled": true, "tiers": ["docs", "tests"] },
12
+ * "C:/Code/my-repo": { "enabled": true, "tiers": ["small"], "maxChangedLines": 40, "maxFiles": 3 }
13
+ * } } }
14
+ *
15
+ * A committed `factory.merge` (the base's `.copilot/omg.jsonc`) is ignored with
16
+ * a notice: lanes can write committed config, so it must never widen trust.
17
+ *
18
+ * Everything here is pure (no git, no spawn): the engine reads the diff, the
19
+ * labels and the human review and hands them in; autoMergeVerdict says
20
+ * whether every condition holds and lists each condition's evidence.
21
+ */
22
+ import { normalize, resolve } from 'path';
23
+ import { repoIdentity, sameRepo } from '../../ship/config.js';
24
+ import { PROTECTED_PATHS, protectedChanges } from '../../ship/merge.js';
25
+ import { CI_TREE_PATHS, LANE_PROTECTED_PATHS } from './lane-commit.js';
26
+ import { checkName } from './merge-policy.js';
27
+ export const AUTO_MERGE_TIERS = ['docs', 'tests', 'small'];
28
+ /** A label on the issue or PR that keeps the merge human. */
29
+ export const MANUAL_MERGE_LABEL = 'factory:manual-merge';
30
+ export const DEFAULT_SMALL_MAX_CHANGED_LINES = 80;
31
+ export const DEFAULT_SMALL_MAX_FILES = 10;
32
+ const MAX_CAP = 100_000;
33
+ const GLOB_KEYS = ['docsDenied', 'securityCritical'];
34
+ const MAX_GLOBS = 200;
35
+ /**
36
+ * The repository's `factory.merge.auto` entry from the trusted user config.
37
+ * `config` undefined = off (no entry, or `enabled` false); `error` = a
38
+ * malformed value (auto-merge stays off and the engine says why).
39
+ */
40
+ export function resolveAutoMergeConfig(user, repo) {
41
+ const auto = user?.factory?.merge?.auto;
42
+ if (auto === undefined || auto === null)
43
+ return {};
44
+ if (typeof auto !== 'object' || Array.isArray(auto))
45
+ return { error: 'factory.merge.auto must be an object keyed by repository' };
46
+ const samePath = (a, b) => {
47
+ const norm = (p) => normalize(resolve(p)).replace(/[\\/]+$/, '');
48
+ return process.platform === 'win32' ? norm(a).toLowerCase() === norm(b).toLowerCase() : norm(a) === norm(b);
49
+ };
50
+ const matches = Object.keys(auto).filter((key) => {
51
+ if (repo.local)
52
+ return /^(?:[A-Za-z]:[\\/]|\/)/.test(key) && samePath(key, repo.root);
53
+ return repo.url !== undefined && !repoIdentity(key).startsWith('path:') && sameRepo(key, repo.url);
54
+ });
55
+ if (matches.length === 0)
56
+ return {};
57
+ if (matches.length > 1)
58
+ return { error: `factory.merge.auto has ${matches.length} entries for this repository (${matches.join(', ')}); keep one` };
59
+ const key = matches[0];
60
+ const v = auto[key];
61
+ if (!v || typeof v !== 'object' || Array.isArray(v))
62
+ return { key, error: `factory.merge.auto["${key}"] must be an object` };
63
+ const o = v;
64
+ const unknownKeys = Object.keys(o).filter((k) => !['enabled', 'tiers', 'maxChangedLines', 'maxFiles', ...GLOB_KEYS].includes(k));
65
+ if (unknownKeys.length > 0)
66
+ return { key, error: `factory.merge.auto["${key}"] has unknown keys: ${unknownKeys.join(', ')}` };
67
+ if (typeof o.enabled !== 'boolean')
68
+ return { key, error: `factory.merge.auto["${key}"].enabled must be a boolean` };
69
+ if (!Array.isArray(o.tiers) || o.tiers.length === 0 || !o.tiers.every((t) => AUTO_MERGE_TIERS.includes(t))) {
70
+ return { key, error: `factory.merge.auto["${key}"].tiers must be a non-empty list of ${AUTO_MERGE_TIERS.map((t) => `"${t}"`).join(', ')}` };
71
+ }
72
+ const cap = (name) => {
73
+ const n = o[name];
74
+ if (n === undefined)
75
+ return undefined;
76
+ return typeof n === 'number' && Number.isSafeInteger(n) && n >= 1 && n <= MAX_CAP ? n : `factory.merge.auto["${key}"].${name} must be an integer from 1 to ${MAX_CAP}`;
77
+ };
78
+ const lines = cap('maxChangedLines');
79
+ const files = cap('maxFiles');
80
+ if (typeof lines === 'string')
81
+ return { key, error: lines };
82
+ if (typeof files === 'string')
83
+ return { key, error: files };
84
+ const globs = {};
85
+ for (const name of GLOB_KEYS) {
86
+ const g = o[name];
87
+ if (g === undefined)
88
+ continue;
89
+ if (!Array.isArray(g) || g.length > MAX_GLOBS || !g.every((x) => typeof x === 'string' && x.trim() !== '' && x.length <= 500 && !/[\0\r\n]/.test(x))) {
90
+ return { key, error: `factory.merge.auto["${key}"].${name} must be a list of at most ${MAX_GLOBS} path globs` };
91
+ }
92
+ globs[name] = [...g];
93
+ }
94
+ if (!o.enabled)
95
+ return { key };
96
+ return {
97
+ key,
98
+ config: {
99
+ enabled: true,
100
+ tiers: [...new Set(o.tiers)],
101
+ ...(lines !== undefined ? { maxChangedLines: lines } : {}),
102
+ ...(files !== undefined ? { maxFiles: files } : {}),
103
+ ...globs,
104
+ },
105
+ };
106
+ }
107
+ /** A committed config (the base's `.copilot/omg.jsonc`) that sets `factory.merge`: the engine ignores it and says so. */
108
+ export function committedMergeConfig(base) {
109
+ const merge = base?.factory?.merge;
110
+ return merge !== undefined;
111
+ }
112
+ /**
113
+ * `git diff --raw -z --no-renames --no-abbrev` and `git diff --numstat -z
114
+ * --no-renames` of the same range, joined by path; null when either is
115
+ * malformed or they disagree (the caller fails closed).
116
+ */
117
+ export function parseChangedEntries(rawZ, numstatZ) {
118
+ const raw = rawZ.split('\0');
119
+ const modes = new Map();
120
+ for (let i = 0; i < raw.length; i++) {
121
+ const head = raw[i];
122
+ if (head === '')
123
+ continue;
124
+ const m = /^:([0-7]{6}) ([0-7]{6}) [0-9a-f]{40,64} [0-9a-f]{40,64} ([ADMT])$/.exec(head);
125
+ const path = raw[i + 1];
126
+ if (!m || path === undefined || path === '' || modes.has(path))
127
+ return null;
128
+ modes.set(path, { status: m[3], oldMode: m[1], newMode: m[2] });
129
+ i++;
130
+ }
131
+ const out = [];
132
+ for (const rec of numstatZ.split('\0')) {
133
+ if (rec === '')
134
+ continue;
135
+ const m = /^(-|\d+)\t(-|\d+)\t(.+)$/s.exec(rec);
136
+ if (!m)
137
+ return null;
138
+ const mode = modes.get(m[3]);
139
+ if (!mode || out.some((e) => e.path === m[3]))
140
+ return null;
141
+ out.push({ path: m[3], ...mode, added: m[1] === '-' ? null : Number(m[1]), deleted: m[2] === '-' ? null : Number(m[2]) });
142
+ }
143
+ // A mode-only change has a raw line and a 0/0 numstat line; any raw path missing from numstat is a disagreement.
144
+ return out.length === modes.size ? out : null;
145
+ }
146
+ const fold = (s) => s.normalize('NFKC').replace(/\p{Default_Ignorable_Code_Point}/gu, '').toUpperCase().toLowerCase().normalize('NFKC');
147
+ /** The path's folded segments (trailing dots and spaces dropped, `.` segments dropped), as Windows would open them. */
148
+ const segments = (path) => fold(path.replace(/\\/g, '/').trim()).split('/').map((s) => s.replace(/[. ]+$/, '')).filter((s) => s.length > 0);
149
+ /**
150
+ * Directories whose files steer agents, editors, hooks, CI or the factory:
151
+ * a path with any such segment, anywhere, never auto-merges. The prompt
152
+ * directories (skills, agents, commands, templates, prompts, instructions)
153
+ * and the agent dot-directories hold text that agent sessions run as
154
+ * instructions, so they are code even when they are Markdown.
155
+ */
156
+ const DENIED_DIRS = new Set([
157
+ '.github', '.copilot', '.omg', '.omc', '.claude', '.vscode', '.husky', '.devcontainer', '.circleci', '.buildkite', '.woodpecker',
158
+ '.azure-pipelines', '.azuredevops', '.pipelines', '.gitlab', '.idea', '.cargo', '.yarn', 'node_modules',
159
+ 'skills', 'agents', 'commands', 'templates', 'prompts', 'instructions',
160
+ '.cursor', '.gemini', '.codex', '.agents', '.windsurf', '.roo', '.continue', '.kiro', '.clinerules', '.aider', '.vitepress', '.docusaurus',
161
+ '.githooks', 'githooks', '__mocks__',
162
+ '.omx', '.junie', '.amazonq', '.trae', '.opencode', '.augment', '.zed', 'memory-bank', '.claude-plugin', 'missions',
163
+ ]);
164
+ /**
165
+ * git's hook names (folded; Git for Windows also runs `<name>.exe`): denied at
166
+ * the repository root, where a core.hooksPath of `.` would run them on your
167
+ * next pull (review-498c L-e). A hooksPath directory below the root is denied whole.
168
+ */
169
+ const GIT_HOOK_NAMES = new Set([
170
+ 'applypatch-msg', 'pre-applypatch', 'post-applypatch', 'pre-commit', 'pre-merge-commit', 'prepare-commit-msg', 'commit-msg', 'post-commit',
171
+ 'pre-rebase', 'post-checkout', 'post-merge', 'pre-push', 'pre-receive', 'update', 'proc-receive', 'post-receive', 'post-update',
172
+ 'reference-transaction', 'push-to-checkout', 'pre-auto-gc', 'post-rewrite', 'sendemail-validate', 'fsmonitor-watchman', 'post-index-change',
173
+ 'p4-changelist', 'p4-prepare-changelist', 'p4-post-changelist', 'p4-pre-submit',
174
+ ]);
175
+ /** Root-anchored directories that usually hold git hooks (core.hooksPath); the configured core.hooksPath is added by the engine. */
176
+ const HOOK_DIRS = ['hooks/', 'scripts/hooks/', 'tools/hooks/', 'git-hooks/', '.config/'];
177
+ /** Root-anchored directories of built or shipped code (installed by every user of the package): no tier takes them. */
178
+ const SHIPPED_DIRS = ['bridge/', 'dist/'];
179
+ /** File names (folded) that are package manifests, lockfiles, tool or agent config: denied in every directory. */
180
+ const DENIED_NAMES = new Set([
181
+ 'package.json', 'package-lock.json', 'npm-shrinkwrap.json', 'yarn.lock', 'pnpm-lock.yaml', 'pnpm-workspace.yaml', 'bun.lock', 'bun.lockb',
182
+ '.npmrc', '.yarnrc', '.yarnrc.yml', '.pnpmfile.cjs', '.nvmrc', '.node-version', '.tool-versions',
183
+ 'cargo.toml', 'cargo.lock', 'go.mod', 'go.sum', 'go.work', 'go.work.sum', 'pyproject.toml', 'poetry.lock', 'pipfile', 'pipfile.lock', 'uv.lock',
184
+ 'setup.py', 'setup.cfg', 'tox.ini', 'noxfile.py', 'conftest.py', 'gemfile', 'gemfile.lock', 'composer.json', 'composer.lock', 'pom.xml',
185
+ 'build.gradle', 'build.gradle.kts', 'settings.gradle', 'settings.gradle.kts', 'gradle.properties', 'gradlew', 'gradlew.bat',
186
+ 'directory.packages.props', 'directory.build.props', 'directory.build.targets', 'nuget.config', 'packages.lock.json', 'global.json',
187
+ 'jsconfig.json', '.babelrc', '.editorconfig', '.gitattributes', '.gitmodules', '.gitignore', '.mailmap',
188
+ 'dockerfile', 'compose.yaml', 'compose.yml', 'makefile', 'justfile', 'taskfile.yml', 'codeowners', 'cmakelists.txt', 'constraints.txt',
189
+ 'agents.md', 'agent.md', 'claude.md', 'gemini.md', 'copilot-instructions.md', 'skill.md', 'omg.jsonc',
190
+ 'claude.local.md', 'agents.override.md', 'warp.md', 'conventions.md', 'sandbox.md', 'mission.md', 'omc.jsonc', 'config.jsonc', '.mcp.json',
191
+ '.cursorrules', '.windsurfrules', '.clinerules', '.roorules', '.goosehints', '.aider.conf.yml',
192
+ 'renovate.json', 'dependabot.yml', 'lefthook.yml', '.pre-commit-config.yaml', 'jenkinsfile',
193
+ '.gitlab-ci.yml', '.travis.yml', 'appveyor.yml', '.appveyor.yml', '.drone.yml', 'bitbucket-pipelines.yml', '.woodpecker.yml',
194
+ 'azure-pipelines.yml', 'azure-pipelines.yaml',
195
+ ]);
196
+ /** File-name patterns (folded) of the same kinds: requirements files, project files, tool configs, env files, agent prompt files. */
197
+ const DENIED_NAME_PATTERNS = [
198
+ /^requirements.*\.(?:txt|in)$/, /\.(?:csproj|fsproj|vbproj|sln|props|targets)$/, /^tsconfig.*\.json$/,
199
+ /^\.eslintrc/, /^eslint\.config\./, /^\.prettierrc/, /^prettier\.config\./, /^\.stylelintrc/,
200
+ /(?:^|\.)config\.[cm]?[jt]sx?$/, /^vitest\.(?:workspace|projects)\./, /^\.env(?:\..*)?$/, /^docker-compose.*\.ya?ml$/, /^\.?dockerfile\./,
201
+ /\.(?:prompt|instructions|chatmode|agent)\.md$/, /\.mdc$/,
202
+ ];
203
+ /** A changed-path spelling of a configured path: `/` separators, no leading `./` or `/` (the protected-path rules are root-relative). */
204
+ const rootRelative = (p) => p.replace(/\\/g, '/').trim().replace(/^(?:\.\/|\/)+/, '');
205
+ /**
206
+ * A user glob as a test on a folded path: `**` any depth, `*` and `?` inside
207
+ * one segment, a trailing `/` a whole directory; a glob without `/` matches
208
+ * the file name at any depth. Braces `{a,b}` and classes `[ab]` are not glob
209
+ * syntax here: they match literally (write one glob per alternative).
210
+ */
211
+ export function globMatcher(glob) {
212
+ let g = rootRelative(fold(glob));
213
+ if (g.endsWith('/'))
214
+ g += '**';
215
+ const anyDepth = !g.includes('/');
216
+ const body = g.split('/').map((seg) => (seg === '**' ? '\u0000' : seg.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '[^/]*').replace(/\?/g, '[^/]'))).join('/')
217
+ .replace(/\u0000\//g, '(?:[^/]+/)*').replace(/\/\u0000/g, '(?:/[^/]+)*').replace(/\u0000/g, '.*');
218
+ const re = new RegExp(`^${anyDepth ? '(?:[^/]+/)*' : ''}${body}$`);
219
+ return (path) => re.test(segments(path).join('/'));
220
+ }
221
+ /**
222
+ * The changed paths no tier may auto-merge: the factory's and ship's
223
+ * protected paths, every CI definition, the usual git hook directories,
224
+ * `extra` (the configured protected paths, known-flaky file and core.hooksPath,
225
+ * root-relative), `globs` (the user's securityCritical list), the denied
226
+ * directories anywhere in the path, manifests, lockfiles, config and agent
227
+ * prompt files by name, and any path Windows could resolve elsewhere
228
+ * (protectedChanges' raw `:`/`~`/`..` rule).
229
+ */
230
+ export function deniedPaths(paths, extra = [], globs = []) {
231
+ const anchored = new Set(protectedChanges(paths, [...LANE_PROTECTED_PATHS, ...CI_TREE_PATHS, ...PROTECTED_PATHS, '.omg/', '.omc/', ...HOOK_DIRS, ...SHIPPED_DIRS, ...extra.map(rootRelative).filter(Boolean)]));
232
+ const user = globs.map(globMatcher);
233
+ return paths.filter((p) => {
234
+ if (anchored.has(p))
235
+ return true;
236
+ const segs = segments(p);
237
+ if (segs.length === 0)
238
+ return true;
239
+ if (segs.length === 1 && GIT_HOOK_NAMES.has(segs[0].replace(/\.exe$/, '')))
240
+ return true;
241
+ if (segs.slice(0, -1).some((s) => DENIED_DIRS.has(s)))
242
+ return true;
243
+ if (user.some((m) => m(p)))
244
+ return true;
245
+ const name = segs[segs.length - 1];
246
+ return DENIED_DIRS.has(name) || DENIED_NAMES.has(name) || DENIED_NAME_PATTERNS.some((r) => r.test(name));
247
+ });
248
+ }
249
+ /** The root docs files the docs tier takes: README, CHANGELOG and CONTRIBUTING (any suffix such as `README.de.md`). */
250
+ const ROOT_DOCS = /^(?:readme|changelog|contributing)(?:[._-][^/]*)?\.(?:md|rst|txt)$/;
251
+ const DOCS_EXT = /\.(?:md|rst|txt)$/;
252
+ /**
253
+ * docs: an allowlist (review-498b N2): root README*, CHANGELOG* and
254
+ * CONTRIBUTING* (.md, .rst, .txt) and `.md`, `.rst`, `.txt` files under the
255
+ * root `docs/`. Nothing else is docs: Markdown elsewhere (src/notes.md, a
256
+ * mission contract, an agent's rules file) may be read by tools or agents.
257
+ */
258
+ export function isDocsPath(path) {
259
+ const segs = segments(path);
260
+ if (segs.length === 0)
261
+ return false;
262
+ const name = segs[segs.length - 1];
263
+ if (segs.length === 1)
264
+ return ROOT_DOCS.test(name);
265
+ return segs[0] === 'docs' && DOCS_EXT.test(name);
266
+ }
267
+ /** Files whose text may carry frontmatter that a tool parses as config (skills, commands, agents, mission contracts): their blobs are read. */
268
+ export const FRONTMATTER_CANDIDATE = /\.(?:md|markdown|mdx|rst|mdc)$/i;
269
+ /**
270
+ * Whether the engine reads a changed file's blobs for frontmatter: Markdown-like
271
+ * by its raw name or by its folded name (`README.md.`, `README.md `, fullwidth
272
+ * or zero-width spellings), and every docs-tier path (review-498c L-a).
273
+ */
274
+ export const isFrontmatterCandidate = (path) => FRONTMATTER_CANDIDATE.test(path) || FRONTMATTER_CANDIDATE.test(segments(path).join('/')) || isDocsPath(path);
275
+ /** A path whose every segment is already in its folded-for-Windows form (NFKC, no default-ignorable, no trailing dot or space, no outer blank): the docs tier takes no other spelling. */
276
+ const canonicalSpelling = (path) => path.split('/').every((s) => s === s.normalize('NFKC').replace(/\p{Default_Ignorable_Code_Point}/gu, '').replace(/[. ]+$/, '').trim());
277
+ /** A blob that starts with YAML (`---`) or TOML (`+++`) frontmatter, after an optional BOM and blank space. */
278
+ export const hasFrontmatter = (text) => /^\uFEFF?\s*(?:---|\+\+\+)/.test(text);
279
+ /** package.json lifecycle scripts that run on install or publish (every user of the package runs them). */
280
+ const LIFECYCLE_SCRIPT = /^(?:preinstall|install|postinstall|preprepare|prepare|postprepare|dependencies|prepublish\w*|prepack|postpack)$/;
281
+ const SCRIPT_RUNNER = /^(?:npm|pnpm|yarn|bun)$/;
282
+ /** Runner subcommands that run no repository code of their own. */
283
+ const RUNNER_INSTALL = /^(?:install|i|ci)$/;
284
+ /** Commands whose targets the engine cannot follow: package executors, script orchestrators, native builds. */
285
+ const UNFOLLOWABLE = /^(?:npx|pnpx|bunx|run-s|run-p|npm-run-all2?|concurrently|wireit|turbo|nx|lerna|node-gyp|node-pre-gyp|prebuild-install|cmake-js)$/i;
286
+ /** Interpreters: whatever they run (a file, `.`, a folder, `-e` code) imports code the engine does not follow. */
287
+ const INTERPRETER = /^(?:node|nodejs|tsx|ts-node(?:-esm)?|esno|deno|python[\d.]*|py|sh|bash|zsh|dash|pwsh|powershell|cmd|perl|ruby|php)(?:\.exe)?$/i;
288
+ /** Flags that point a runner at another package or directory (workspaces, prefixes, filters). */
289
+ const ELSEWHERE_FLAG = /^(?:-w|-ws|--workspaces?(?:=.*)?|--prefix(?:=.*)?|-C|--dir(?:=.*)?|--cwd(?:=.*)?|--filter(?:=.*)?|-F|-r|--recursive)$/;
290
+ /**
291
+ * The files the BASE package.json runs for every user of the package
292
+ * (review-498b N3, review-498c L-b): every path-like word of its install and
293
+ * publish lifecycle scripts (and of the scripts they run with `npm run
294
+ * <name>`) and its "bin" targets, all denied in every tier. The small tier
295
+ * also needs a `problem`-free result, and anything the engine cannot follow is
296
+ * a problem: a lifecycle that runs a repository file or an interpreter (what
297
+ * it imports is not followed), a runner with flags or an unknown subcommand,
298
+ * a script orchestrator or package executor, a variable, substitution or
299
+ * glob, "gypfile", "workspaces", and (`rootNames`, the base's root file names)
300
+ * a binding.gyp or pnpm-workspace.yaml. Absent package.json (`text` null):
301
+ * only the root-file problems.
302
+ */
303
+ export function baseInstallFiles(text, rootNames = []) {
304
+ const problems = [];
305
+ const root = new Set(rootNames.map((n) => fold(n)));
306
+ if (root.has('binding.gyp'))
307
+ problems.push('the base has a root binding.gyp, so install runs node-gyp on repository sources');
308
+ if (root.has('pnpm-workspace.yaml'))
309
+ problems.push('the base is a pnpm workspace, so install runs every workspace package\'s scripts, which the engine does not read');
310
+ const done = (paths, problem) => {
311
+ const first = problem ?? problems[0];
312
+ const out = paths.map(rootRelative).filter(Boolean);
313
+ return first ? { paths: out, problem: first } : { paths: out };
314
+ };
315
+ if (text === null)
316
+ return done([]);
317
+ let pkg;
318
+ try {
319
+ pkg = JSON.parse(text);
320
+ }
321
+ catch {
322
+ return done([], 'the base package.json could not be parsed');
323
+ }
324
+ if (!pkg || typeof pkg !== 'object' || Array.isArray(pkg))
325
+ return done([], 'the base package.json is not an object');
326
+ if (pkg.gypfile !== undefined && pkg.gypfile !== false)
327
+ problems.push('the base package.json sets "gypfile", so install runs node-gyp on repository sources');
328
+ if (pkg.workspaces !== undefined)
329
+ problems.push('the base package.json has "workspaces": install runs each workspace package\'s scripts, which the engine does not read');
330
+ const paths = [];
331
+ const scripts = pkg.scripts === undefined ? {} : pkg.scripts;
332
+ if (!scripts || typeof scripts !== 'object' || Array.isArray(scripts))
333
+ return done(paths, 'the base package.json "scripts" is not an object');
334
+ const table = scripts;
335
+ const seen = new Set();
336
+ const visit = (name, depth) => {
337
+ if (seen.has(name))
338
+ return;
339
+ seen.add(name);
340
+ const body = table[name];
341
+ if (body === undefined)
342
+ return;
343
+ const cannot = (what) => problems.push(`the base package.json script "${name}" ${what}, which the engine cannot follow`);
344
+ if (typeof body !== 'string') {
345
+ problems.push(`the base package.json script "${name}" is not a string`);
346
+ return;
347
+ }
348
+ if (/[$`%*?{}[\]]/.test(body)) {
349
+ problems.push(`the base package.json script "${name}" has a variable, substitution or glob, so the files it runs are unknown`);
350
+ return;
351
+ }
352
+ // One command at a time (`a && b; c | d`), so a runner never reads the next command's words.
353
+ for (const command of body.split(/[;&|()<>\r\n]+/)) {
354
+ const words = command.split(/\s+/).map((w) => w.replace(/^['"]+|['"]+$/g, '')).filter(Boolean);
355
+ for (let i = 0; i < words.length; i++) {
356
+ const w = words[i];
357
+ const next = words[i + 1];
358
+ if (ELSEWHERE_FLAG.test(w)) {
359
+ cannot(`passes ${w} (another package or directory)`);
360
+ continue;
361
+ }
362
+ if (SCRIPT_RUNNER.test(w)) {
363
+ // `yarn` alone installs; `npm run x`, `yarn x`, `pnpm x`, `npm test`: follow the script it names; anything else is not followed.
364
+ if (next === undefined)
365
+ continue;
366
+ if (next.startsWith('-')) {
367
+ cannot(`passes ${next} to ${w}`);
368
+ continue;
369
+ }
370
+ const explicit = next === 'run' || next === 'run-script';
371
+ if (explicit || Object.hasOwn(table, next)) {
372
+ const target = explicit ? words[i + 2] : next;
373
+ if (target === undefined || target.startsWith('-') || depth >= 5)
374
+ cannot(`runs another script with ${w}`);
375
+ else
376
+ visit(target, depth + 1);
377
+ i += explicit ? 2 : 1;
378
+ continue;
379
+ }
380
+ if (RUNNER_INSTALL.test(next)) {
381
+ i++;
382
+ continue;
383
+ }
384
+ cannot(`runs ${w} ${next}`);
385
+ i++;
386
+ continue;
387
+ }
388
+ if (UNFOLLOWABLE.test(w)) {
389
+ cannot(`runs ${w}`);
390
+ continue;
391
+ }
392
+ if (INTERPRETER.test(w)) {
393
+ cannot(`runs ${w}${next ? ` ${next}` : ''} (what it runs or imports)`);
394
+ continue;
395
+ }
396
+ if (w.startsWith('-'))
397
+ continue;
398
+ if (w.includes('/') || w.includes('\\') || /\.[A-Za-z0-9]{1,5}$/.test(w)) {
399
+ paths.push(w);
400
+ cannot(`runs the repository file ${w} (what it imports)`);
401
+ }
402
+ }
403
+ }
404
+ };
405
+ for (const name of Object.keys(table).filter((n) => LIFECYCLE_SCRIPT.test(n)))
406
+ visit(name, 0);
407
+ if (pkg.bin !== undefined) {
408
+ const bins = typeof pkg.bin === 'string' ? [pkg.bin] : pkg.bin && typeof pkg.bin === 'object' && !Array.isArray(pkg.bin) ? Object.values(pkg.bin) : [undefined];
409
+ if (!bins.every((b) => typeof b === 'string'))
410
+ return done(paths, 'the base package.json "bin" is not a string or an object of strings');
411
+ paths.push(...bins);
412
+ }
413
+ return done(paths);
414
+ }
415
+ /**
416
+ * Added diff lines (any file) that skip or focus tests, or assert nothing
417
+ * (review-498b N5, review-498c L-c): `.skip` and its bracket spellings,
418
+ * x/f-prefixed tests, a literal `expect(...)`, `if (false)`,
419
+ * `expect.assertions(0)`, an empty `.each([])`, pytest / unittest / go skips.
420
+ * A heuristic: the tests tier is CI-green tests, not proof of their strength.
421
+ */
422
+ const TEST_SKIP = [
423
+ /\.(?:skip|todo|only|skipIf|runIf|fails)\b|\bx(?:it|describe|test)\s*\(|\bf(?:it|describe)\s*\(|pytest\.mark\.(?:skip|xfail)|unittest\.skip|\bt\.Skip(?:Now|f)?\(/,
424
+ /\[\s*['"`](?:skip|todo|only|skipIf|runIf|fails)['"`]\s*\]/,
425
+ /\bskipTest\s*\(|\bpytest\.(?:skip|xfail)\s*\(/,
426
+ /\bif\s*\(\s*(?:false|0|null|undefined|!\s*(?:true|1|0|!\s*0))\s*\)/,
427
+ /\bexpect\.assertions\s*\(\s*0\s*\)/,
428
+ /\.each\s*\(\s*\[\s*\]\s*\)/,
429
+ /\bexpect\(\s*!*\s*(?:true|false|-?\d+(?:\.\d+)?|null|undefined|'[^']*'|"[^"]*"|`[^`$]*`)\s*\)/,
430
+ ];
431
+ /** Added lines in a test file only: an early bare `return`, or an assertion of a value against itself. */
432
+ const TEST_FILE_SKIP = [
433
+ /^\s*return\s*;?\s*(?:\/\/.*)?$/,
434
+ /\bexpect\(\s*([\w$.]+)\s*\)\s*\.\s*(?:toBe|toEqual|toStrictEqual)\s*\(\s*\1\s*\)/,
435
+ /\bassert\.(?:equal|strictEqual|deepEqual|deepStrictEqual)\s*\(\s*([\w$.]+)\s*,\s*\1\s*\)/,
436
+ ];
437
+ /** A line that asserts: a modified test that loses more of these than it gains is gutted, however it is padded. */
438
+ const ASSERTION = /\b(?:expect|assert\w*|should|self\.assert\w+|t\.(?:Errorf?|Fatalf?|Fail\w*)|require\.\w+)\s*[.(]|^\s*assert\s/;
439
+ /**
440
+ * The added and deleted lines of a plain `git diff` patch, each with its
441
+ * file; null when the text has an ANSI escape (a colour setting: the engine
442
+ * cannot read it, so it fails closed).
443
+ */
444
+ export function patchLines(patch) {
445
+ if (patch.includes('\u001b'))
446
+ return null;
447
+ const out = [];
448
+ let hunk = false;
449
+ let oldPath = '';
450
+ let newPath = '';
451
+ for (const line of patch.split('\n')) {
452
+ if (line.startsWith('diff --git ')) {
453
+ hunk = false;
454
+ oldPath = newPath = line.slice(11);
455
+ }
456
+ else if (!hunk && line.startsWith('--- '))
457
+ oldPath = line.slice(4);
458
+ else if (!hunk && line.startsWith('+++ '))
459
+ newPath = line.slice(4);
460
+ else if (line.startsWith('@@'))
461
+ hunk = true;
462
+ else if (hunk && (line.startsWith('+') || line.startsWith('-'))) {
463
+ out.push({ path: newPath === '/dev/null' ? oldPath : newPath, sign: line[0], text: line.slice(1) });
464
+ }
465
+ }
466
+ return out;
467
+ }
468
+ /** Whether a patch header name is (or may be) a test file: with or without git's `a/`/`b/` prefix; a quoted name is assumed to be one. */
469
+ const patchPathIsTest = (path) => path.startsWith('"') || looksLikeTest(path) || looksLikeTest(path.replace(/^[^/]*\//, ''));
470
+ const TEST_NAME = [/\.(?:test|spec)\.[cm]?[jt]sx?$/, /_test\.go$/, /^test_[^/]+\.py$/, /_test\.py$/, /(?:^|_)(?:test|spec)\.rb$/];
471
+ /** Test directories at the repository root; `__tests__` and `__snapshots__` count at any depth. */
472
+ const ROOT_TEST_DIRS = new Set(['__tests__', '__snapshots__', 'test', 'tests', 'spec']);
473
+ const ANY_DEPTH_TEST_DIRS = new Set(['__tests__', '__snapshots__']);
474
+ const TEST_DIR_FILE = /\.(?:[cm]?[jt]sx?|py|go|rb|snap|json|txt|md)$/;
475
+ /** Test-tier files that run outside the PR's own test run (setup, teardown, benchmarks): the tests tier never takes them. */
476
+ const TEST_RUNNER_CODE = /setup|teardown|bench|env|report|sequenc|serial|resolv|transform|global|runner|preset/;
477
+ /** tests: a test file by name, or a source / snapshot / fixture-data file under a root test directory or any `__tests__`. */
478
+ export function isTestPath(path) {
479
+ const segs = segments(path);
480
+ if (segs.length === 0)
481
+ return false;
482
+ const name = segs[segs.length - 1];
483
+ if (TEST_NAME.some((r) => r.test(name)))
484
+ return true;
485
+ const dirs = segs.slice(0, -1);
486
+ return (ROOT_TEST_DIRS.has(dirs[0] ?? '') || dirs.some((s) => ANY_DEPTH_TEST_DIRS.has(s))) && TEST_DIR_FILE.test(name);
487
+ }
488
+ /** Anything that looks like a test, more widely than isTestPath (a deletion of one needs a human). */
489
+ const looksLikeTest = (path) => isTestPath(path) || segments(path).some((s) => /(?:^|[._-])(?:tests?|specs?)(?:$|[._-])|__tests__/.test(s));
490
+ /** Only a plain, non-executable file may change (added, modified or deleted): no symlink, gitlink or mode flip. */
491
+ const plainMode = (mode) => mode === '100644' || mode === '000000';
492
+ /** Root-anchored source trees the small tier never touches by default: the factory, ship, the Copilot runner and the forge adapters. */
493
+ export const SMALL_TIER_DENIED = ['src/factory/', 'src/ship/', 'src/copilot-run/', 'src/forge/'];
494
+ /** Whether a changed path is one of the base test config's setup files (written with or without an extension). */
495
+ const setupMatcher = (paths) => {
496
+ const want = new Set(paths.map((p) => segments(rootRelative(p.replace(/^<rootdir>\//i, ''))).join('/')).filter(Boolean));
497
+ return (path) => {
498
+ const f = segments(path).join('/');
499
+ return want.has(f) || want.has(f.replace(/\.[^./]+$/, ''));
500
+ };
501
+ };
502
+ /**
503
+ * The first enabled tier (docs, tests, small, in that order) every changed
504
+ * file fits, after the checks every tier shares: at least one change, plain
505
+ * file modes, no binary, no denied path (built-in, configured, the user's
506
+ * securityCritical globs, the base test config's setup files), no deleted
507
+ * test, and the caps.
508
+ */
509
+ export function classifyChanges(entries, config, opts = {}) {
510
+ if (entries === null)
511
+ return { reasons: ['the changed files could not be read (git diff --raw/--numstat base...head); auto-merge fails closed'], evidence: [] };
512
+ if (entries.length === 0)
513
+ return { reasons: ['the PR changes no file'], evidence: [] };
514
+ const reasons = [];
515
+ const list = (ps) => `${ps.slice(0, 5).join(', ')}${ps.length > 5 ? `, and ${ps.length - 5} more` : ''}`;
516
+ const odd = entries.filter((e) => !plainMode(e.oldMode) || !plainMode(e.newMode) || (e.oldMode === '000000' && e.newMode === '000000'));
517
+ if (odd.length > 0)
518
+ reasons.push(`non-plain file modes (symlink, gitlink, executable or mode change): ${list(odd.map((e) => `${e.path} ${e.oldMode}->${e.newMode}`))}`);
519
+ const binary = entries.filter((e) => e.added === null || e.deleted === null);
520
+ if (binary.length > 0)
521
+ reasons.push(`binary changes: ${list(binary.map((e) => e.path))}`);
522
+ const denied = deniedPaths(entries.map((e) => e.path), [...(opts.extraDenied ?? []), ...(opts.installFiles?.paths ?? [])], config.securityCritical ?? []);
523
+ if (denied.length > 0)
524
+ reasons.push(`touches paths that always need a human (CI, config, manifests, lockfiles, hooks, agent prompts, factory or security-critical files): ${list(denied)}`);
525
+ const isSetup = setupMatcher(opts.testSetup?.paths ?? []);
526
+ const setup = entries.filter((e) => isSetup(e.path));
527
+ if (setup.length > 0)
528
+ reasons.push(`touches files the base test config runs around every test run (setupFiles, globalSetup): ${list(setup.map((e) => e.path))}`);
529
+ const deletedTests = entries.filter((e) => e.status === 'D' && looksLikeTest(e.path));
530
+ if (deletedTests.length > 0)
531
+ reasons.push(`deletes test files (a deleted test needs a human): ${list(deletedTests.map((e) => e.path))}`);
532
+ const lines = entries.reduce((n, e) => n + (e.added ?? 0) + (e.deleted ?? 0), 0);
533
+ const files = entries.length;
534
+ const evidence = [`${files} file(s), ${lines} changed line(s), plain file modes, no binary, no denied path, no deleted test`];
535
+ if (reasons.length > 0)
536
+ return { reasons, evidence: [] };
537
+ const docsDenied = (config.docsDenied ?? []).map(globMatcher);
538
+ const frontmatter = new Set((opts.frontmatter?.paths ?? []).map((p) => segments(p).join('/')));
539
+ const withFrontmatter = (e) => frontmatter.has(segments(e.path).join('/'));
540
+ // N5: a modified test that loses more lines than it gains, or an added skip / focus / empty assertion, is a gutted test.
541
+ const gutted = entries.filter((e) => e.status === 'M' && looksLikeTest(e.path) && (e.deleted ?? 0) > (e.added ?? 0)).map((e) => e.path);
542
+ // L-c: line padding does not hide it: a test file that loses more assertion lines than it gains is gutted too.
543
+ const assertions = new Map();
544
+ for (const l of opts.patch ?? []) {
545
+ if (patchPathIsTest(l.path) && ASSERTION.test(l.text))
546
+ assertions.set(l.path, (assertions.get(l.path) ?? 0) + (l.sign === '-' ? 1 : -1));
547
+ }
548
+ gutted.push(...[...assertions].filter(([path, net]) => net > 0 && !gutted.some((g) => path.endsWith(g))).map(([path]) => path));
549
+ const skipLine = opts.patch?.find((l) => l.sign === '+' && (TEST_SKIP.some((r) => r.test(l.text)) || (patchPathIsTest(l.path) && TEST_FILE_SKIP.some((r) => r.test(l.text)))))?.text;
550
+ const misses = [];
551
+ for (const tier of AUTO_MERGE_TIERS) {
552
+ if (!config.tiers.includes(tier))
553
+ continue;
554
+ const maxLines = config.maxChangedLines ?? (tier === 'small' ? DEFAULT_SMALL_MAX_CHANGED_LINES : undefined);
555
+ const maxFiles = config.maxFiles ?? (tier === 'small' ? DEFAULT_SMALL_MAX_FILES : undefined);
556
+ if (tier !== 'docs' && opts.testSetup?.problem) {
557
+ misses.push(`${tier}: ${opts.testSetup.problem}`);
558
+ continue;
559
+ }
560
+ if (tier !== 'tests' && opts.frontmatter?.problem) {
561
+ misses.push(`${tier}: ${opts.frontmatter.problem}`);
562
+ continue;
563
+ }
564
+ if (tier === 'small' && opts.installFiles?.problem) {
565
+ misses.push(`${tier}: ${opts.installFiles.problem}`);
566
+ continue;
567
+ }
568
+ if (tier !== 'docs') {
569
+ if (opts.patch === null) {
570
+ misses.push(`${tier}: the PR's patch could not be read, so a skipped or emptied test cannot be ruled out`);
571
+ continue;
572
+ }
573
+ if (gutted.length > 0) {
574
+ misses.push(`${tier}: ${list(gutted)} lose(s) more lines (or assertion lines) than it gains (a gutted test needs a human)`);
575
+ continue;
576
+ }
577
+ if (skipLine !== undefined) {
578
+ misses.push(`${tier}: an added line skips, focuses or empties a test (${oneLineOf(skipLine)})`);
579
+ continue;
580
+ }
581
+ }
582
+ const outside = tier === 'docs' ? entries.filter((e) => !isDocsPath(e.path) || !canonicalSpelling(e.path) || docsDenied.some((m) => m(e.path)) || withFrontmatter(e))
583
+ : tier === 'tests' ? entries.filter((e) => !isTestPath(e.path) || e.status === 'D' || segments(e.path).some((s) => TEST_RUNNER_CODE.test(s)))
584
+ : entries.filter((e) => protectedChanges([e.path], SMALL_TIER_DENIED).length > 0 || withFrontmatter(e));
585
+ if (outside.length > 0) {
586
+ const fm = outside.filter(withFrontmatter);
587
+ if (fm.length > 0 && tier !== 'tests') {
588
+ misses.push(`${tier}: ${list(fm.map((e) => e.path))} start(s) with frontmatter, which a tool may run as config`);
589
+ continue;
590
+ }
591
+ const what = tier === 'docs' ? 'docs' : tier === 'tests' ? 'test files (setup, teardown, benchmarks and deletions are not)' : `small-tier files (never under ${SMALL_TIER_DENIED.join(', ')})`;
592
+ misses.push(`${tier}: ${list(outside.map((e) => e.path))} ${outside.length === 1 ? 'is' : 'are'} not ${what}`);
593
+ continue;
594
+ }
595
+ if (maxLines !== undefined && lines > maxLines) {
596
+ misses.push(`${tier}: ${lines} changed lines > maxChangedLines ${maxLines}`);
597
+ continue;
598
+ }
599
+ if (maxFiles !== undefined && files > maxFiles) {
600
+ misses.push(`${tier}: ${files} files > maxFiles ${maxFiles}`);
601
+ continue;
602
+ }
603
+ return { tier, reasons: [], evidence: [...evidence, `every file fits tier ${tier}${maxLines !== undefined ? ` (lines ${lines}/${maxLines}` : ''}${maxFiles !== undefined ? `${maxLines !== undefined ? ', ' : ' ('}files ${files}/${maxFiles}` : ''}${maxLines !== undefined || maxFiles !== undefined ? ')' : ''}`] };
604
+ }
605
+ return { reasons: [`no enabled tier fits (${misses.join('; ')})`], evidence: [] };
606
+ }
607
+ const oneLineOf = (s) => { const t = s.trim().replace(/\s+/g, ' '); return t.length > 80 ? `${t.slice(0, 80)}...` : t; };
608
+ /** Root config files whose setupFiles / globalSetup the engine reads at the BASE commit (never the head). */
609
+ export const TEST_CONFIG_NAME = /^(?:(?:vitest|vite|jest)(?:\.[\w-]+)*\.config\.(?:[cm]?[jt]s|json)|vitest\.(?:workspace|projects)\.(?:[cm]?[jt]s|json)|package\.json)$/i;
610
+ /** Config keys whose value names code the test runner loads around the tests (review-498b N4 added the reporter, environment, runner and transform keys). */
611
+ const SETUP_KEY_NAMES = ['setupFiles', 'setupFilesAfterEnv', 'globalSetup', 'globalTeardown', 'reporters', 'environment', 'testEnvironment', 'runner', 'testRunner',
612
+ 'sequencer', 'testSequencer', 'snapshotSerializers', 'resolveSnapshotPath', 'snapshotResolver', 'transform', 'watchPlugins', 'preset',
613
+ 'pool', 'checker', 'customProviderModule'];
614
+ /** Keys that point at more config (vitest projects / workspace, extends, jest projects): the engine does not read it, so any use is a problem (review-498c L-d). */
615
+ const MORE_CONFIG_KEY = /(?<![\w$])["']?(?:projects|workspace)(?![\w$])|(?<![\w$])["']?extends["']?\s*[:,}\]]/;
616
+ /** The only modules a root test config may import: vitest, vite and node builtins (anything else may be repository code). */
617
+ const ALLOWED_IMPORT = /^(?:vitest|vite|vitest\/config|vitest\/node|node:[\w/]+|path|url|fs|os|module)$/;
618
+ /** Every static import / re-export / import() / require() specifier written as a plain string. */
619
+ const IMPORT_SPECIFIER = /\b(?:from|import|require)\s*\(?\s*(['"])([^'"\n]*)\1/g;
620
+ /** An import() or require() call whose argument is not one plain string literal. */
621
+ const DYNAMIC_LOAD = /\b(?:require|import)\s*\((?!\s*(['"])[^'"`$\n]*\1\s*\))/;
622
+ const KEY_ALT = SETUP_KEY_NAMES.join('|');
623
+ const SETUP_KEYS = new RegExp(`(?<![\\w$])["']?(${KEY_ALT})["']?\\s*:\\s*`, 'g');
624
+ /** Any mention of one of those names: one that is not a plain `key: value` (shorthand, computed key, spread) is a problem. */
625
+ const SETUP_KEY_WORD = new RegExp(`(?<![\\w$])(${KEY_ALT})(?![\\w$])`, 'g');
626
+ /** Config text that loads more config the engine does not read: a relative import or require, mergeConfig, a workspace or project definition. */
627
+ const LOADS_MORE = /\b(?:import|require)\s*\(?\s*['"`]\.{1,2}[\/\\]|\bfrom\s*['"`]\.{1,2}[\/\\]|\b(?:mergeConfig|defineWorkspace|defineProject)\b/;
628
+ const STRING = /(['"`])((?:\\.|(?!\1)[^\\\n])*)\1/y;
629
+ /**
630
+ * The setup files the base's root test configs name (vitest / vite / jest
631
+ * configs and package.json's `jest`), read as text: each SETUP_KEY_NAMES
632
+ * value (setup, teardown, reporters, environment, runner, sequencer,
633
+ * serializers, transform...) must be a string literal or an array of them.
634
+ * Anything else (a variable, a call, a template with `${}`, a shorthand or
635
+ * computed key, a relative import or require, mergeConfig, defineWorkspace,
636
+ * defineProject) is a `problem`, and the engine then keeps the tests and
637
+ * small tiers off: it cannot know which file runs.
638
+ */
639
+ export function baseTestSetup(files) {
640
+ const paths = [];
641
+ for (const { path, text } of files) {
642
+ if (/^package\.json$/i.test(path)) {
643
+ let jest;
644
+ try {
645
+ jest = JSON.parse(text).jest;
646
+ }
647
+ catch {
648
+ return { paths, problem: 'the base package.json could not be parsed' };
649
+ }
650
+ if (jest === undefined)
651
+ continue;
652
+ if (!jest || typeof jest !== 'object')
653
+ return { paths, problem: 'the base package.json "jest" is not an object' };
654
+ if (jest.projects !== undefined)
655
+ return { paths, problem: 'the base package.json "jest" has "projects", whose configs the engine does not read' };
656
+ // JSON is exact: every string under these keys (module names and paths, in lists, tuples or transform maps) counts.
657
+ const leaves = (v, depth) => {
658
+ if (typeof v === 'string')
659
+ paths.push(v);
660
+ else if (depth < 6 && v && typeof v === 'object')
661
+ for (const x of Array.isArray(v) ? v : Object.values(v))
662
+ leaves(x, depth + 1);
663
+ };
664
+ for (const k of SETUP_KEY_NAMES)
665
+ leaves(jest[k], 0);
666
+ continue;
667
+ }
668
+ if (LOADS_MORE.test(text))
669
+ return { paths, problem: `${path} imports a relative file, or uses mergeConfig, defineWorkspace or defineProject, so the setup files it runs are unknown` };
670
+ const keyed = new Set([...text.matchAll(SETUP_KEYS)].map((m) => m.index + (/^["']/.test(m[0]) ? 1 : 0)));
671
+ const loose = [...text.matchAll(SETUP_KEY_WORD)].find((m) => !keyed.has(m.index));
672
+ if (loose)
673
+ return { paths, problem: `${path}: ${loose[1]} is not written as a plain key: value (shorthand, computed key or spread), so its files are unknown` };
674
+ for (const m of text.matchAll(SETUP_KEYS)) {
675
+ let i = m.index + m[0].length;
676
+ const literal = () => {
677
+ STRING.lastIndex = i;
678
+ const s = STRING.exec(text);
679
+ if (!s || (s[1] === '`' && s[2].includes('${')))
680
+ return undefined;
681
+ i = STRING.lastIndex;
682
+ return s[2];
683
+ };
684
+ const skip = () => { while (i < text.length && /[\s,]/.test(text[i]))
685
+ i++; };
686
+ if (text[i] === '[') {
687
+ i++;
688
+ for (skip(); text[i] !== ']'; skip()) {
689
+ const s = literal();
690
+ if (s === undefined)
691
+ return { paths, problem: `${path}: ${m[1]} is not a list of string literals, so its files are unknown` };
692
+ paths.push(s);
693
+ }
694
+ }
695
+ else {
696
+ const s = literal();
697
+ if (s === undefined)
698
+ return { paths, problem: `${path}: ${m[1]} is not a string literal, so its file is unknown` };
699
+ paths.push(s);
700
+ }
701
+ }
702
+ // review-498c L-d: more config (projects, workspace, extends), any import but vitest / vite / node builtins, and computed loads are not followed.
703
+ const more = MORE_CONFIG_KEY.exec(text);
704
+ if (more)
705
+ return { paths, problem: `${path} uses ${more[0].replace(/["'\s:,}\]]/g, '')}, which points at config the engine does not read` };
706
+ const foreign = [...text.matchAll(IMPORT_SPECIFIER)].find((m) => !ALLOWED_IMPORT.test(m[2]));
707
+ if (foreign)
708
+ return { paths, problem: `${path} imports "${foreign[2]}" (only vitest, vite and node builtins are read as safe), so the setup files it runs are unknown` };
709
+ if (DYNAMIC_LOAD.test(text))
710
+ return { paths, problem: `${path} has an import() or require() of a computed path, so the setup files it runs are unknown` };
711
+ if (/__dirname|__filename|\bimport\.meta\b/.test(text) && /\b(?:require|import)\s*\(/.test(text))
712
+ return { paths, problem: `${path} loads a file relative to __dirname or import.meta, so the setup files it runs are unknown` };
713
+ }
714
+ return { paths };
715
+ }
716
+ /**
717
+ * The parks a run may have had and still auto-merge: waits and ordinary
718
+ * failures a later round fixed. Any other `awaiting-human:` park in the run's
719
+ * history (tamper, secrets, sandbox, protected paths, a park added later)
720
+ * keeps the merge human: an allowlist, so a new park fails closed.
721
+ */
722
+ export const BENIGN_PARKS = new Set([
723
+ 'merge', 'merge-conflicts', 'human-review', 'budget', 'wall-time', 'needs-plan', 'blocked-by',
724
+ 'ci-failed', 'ci-flaky', 'gates', 'gates-timeout', 'fix-rounds-spent', 'base-changed', 'prepare-checks',
725
+ ]);
726
+ const PARK_NOTE = /^awaiting-human: ([^:\s]+):/;
727
+ /** Every auto-merge condition on the exact head; all must hold. */
728
+ export function autoMergeVerdict(i) {
729
+ const reasons = [];
730
+ const evidence = [];
731
+ const at = i.head.slice(0, 12);
732
+ const check = (ok, good, bad) => (ok ? evidence.push(good) : reasons.push(bad));
733
+ check(i.run.forgeKind !== 'azure-devops', `forge ${i.run.forgeKind}`, 'Azure DevOps PRs always merge by a human (no head-pinned engine merge there)');
734
+ check(!i.run.ciHeal, 'issue run', 'ci-heal runs always merge by a human');
735
+ check(i.decision.ok && i.decision.reasons.length === 0, 'ship\'s merge rule allows this head with no reason', `ship's merge rule has reasons: ${i.decision.reasons.join('; ')}`);
736
+ const v = i.verdict;
737
+ check(!!v && v.verdict === 'approve' && v.sha === i.head, `factory review approved ${at}${v ? ` (${v.reviewer})` : ''}`, `the factory review did not approve this exact head (latest: ${v ? `${v.verdict} at ${v.sha.slice(0, 12)}` : 'none'})`);
738
+ // Only a check that ran and succeeded counts: SKIPPED, NEUTRAL and known-flaky failures pass the gate but never auto-merge.
739
+ // Every non-advisory check must have SUCCEEDED (SKIPPED / NEUTRAL only when required checks are set), whatever the gate verdict:
740
+ // a known-flaky FAILURE, ERROR, CANCELLED, TIMED_OUT, ACTION_REQUIRED, STARTUP_FAILURE or a pending check keeps the merge human.
741
+ const blocking = i.decision.blocking;
742
+ check(blocking !== undefined && blocking.length === 0, 'every check on this head succeeded, skipped or was neutral (advisory checks aside)', blocking === undefined ? 'the check states on this head were not read'
743
+ : `checks did not succeed on this head: ${blocking.slice(0, 8).join(', ')}${blocking.length > 8 ? ', ...' : ''}; a known-flaky or failed check always leaves the merge to a human`);
744
+ const checks = i.decision.checks ?? [];
745
+ const required = i.requiredChecks ?? [];
746
+ const succeeded = required.length > 0 ? checks.filter((c) => required.includes(c)) : checks;
747
+ // N6: without required checks one trivial success (a labeler) is not enough: no check on the head may be SKIPPED or NEUTRAL either.
748
+ const unsettled = required.length > 0 ? [] : (i.decision.unsettled ?? []);
749
+ check(unsettled.length === 0, 'no check skipped or neutral on this head', `checks skipped or neutral on this head (${unsettled.slice(0, 8).map(checkName).join(', ')}${unsettled.length > 8 ? ', ...' : ''}); without required checks every check must succeed (set ship.requiredChecks or branch protection to name the ones that matter)`);
750
+ check(!i.decision.noChecks && succeeded.length > 0, `CI green at ${at}: ${succeeded.slice(0, 8).map(checkName).join(', ')}${succeeded.length > 8 ? ', ...' : ''} succeeded${required.length > 0 ? ' (required)' : ''}`, required.length > 0 ? `no required check (${required.slice(0, 8).map(checkName).join(', ')}) succeeded on this head (skipped or neutral checks do not count)` : 'no CI check succeeded on this head (skipped, neutral or no checks never auto-merge)');
751
+ check(i.human !== undefined, 'human review read: no open thread or change request', 'factory.review.human is "off", so human review threads are not read');
752
+ if (i.human)
753
+ check(i.human.commentOnly === 0, 'no comment-only human review at this head', `${i.human.commentOnly} comment-only human review(s) at this head`);
754
+ check(i.labels !== null && !i.labels.some((l) => l.toLowerCase() === MANUAL_MERGE_LABEL), `no ${MANUAL_MERGE_LABEL} label`, i.labels === null ? 'the issue or PR labels could not be read' : `the issue or PR carries ${MANUAL_MERGE_LABEL}`);
755
+ const flagged = i.run.history.map((h) => PARK_NOTE.exec(h.note)?.[1] ?? (/^awaiting-human:/.test(h.note) ? '(unparsed park)' : undefined)).filter((n) => !!n && !BENIGN_PARKS.has(n));
756
+ const tamper = i.run.history.some((h) => /tamper|quarantin/i.test(h.note));
757
+ const acks = [
758
+ ...(i.run.unsandboxedAck ? ['--allow-unsandboxed-lanes'] : []),
759
+ ...(i.run.unsandboxedGatesAck ? ['--allow-unsandboxed-gates'] : []),
760
+ ...(i.run.gateChangeApproved ? ['--allow-gate-change'] : []),
761
+ ...(i.run.secretAck && i.run.secretAck.length > 0 ? ['--allow-secret-shapes'] : []),
762
+ ...(i.run.history.some((h) => /--allow-[a-z-]+/.test(h.note)) ? ['an --allow-* flag (run history)'] : []),
763
+ ];
764
+ check(flagged.length === 0 && !tamper, 'no secret-scan, tamper or sandbox park in this run', `this run parked at ${[...new Set(flagged)].join(', ') || 'a tamper or quarantine hold'}`);
765
+ check(acks.length === 0, 'no --allow-* acknowledgement in this run', `this run used ${[...new Set(acks)].join(', ')}`);
766
+ if (i.changes.tier)
767
+ evidence.push(...i.changes.evidence);
768
+ else
769
+ reasons.push(...i.changes.reasons);
770
+ return reasons.length === 0 ? { ok: true, tier: i.changes.tier, reasons, evidence } : { ok: false, reasons, evidence };
771
+ }
772
+ /** The PR comment after the engine merged: the tier and every condition's evidence. */
773
+ export function autoMergeComment(label, tier, head, evidence, by) {
774
+ return [
775
+ `Factory run for ${label}: auto-merged by tier ${tier} at ${head.slice(0, 12)} (${by}).`,
776
+ '',
777
+ 'Every auto-merge condition held on this exact head:',
778
+ '',
779
+ ...evidence.map((e) => `- ${e}`),
780
+ '',
781
+ `factory.merge.auto in your user config turns this on per repository; add the ${MANUAL_MERGE_LABEL} label to keep a PR's merge human.`,
782
+ '',
783
+ ].join('\n');
784
+ }
785
+ //# sourceMappingURL=auto-merge.js.map