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
@@ -55,21 +55,25 @@
55
55
  import { createHash } from 'crypto';
56
56
  import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'fs';
57
57
  import { tmpdir } from 'os';
58
- import { basename, dirname, isAbsolute, join, relative, resolve } from 'path';
58
+ import { basename, dirname, isAbsolute, join, posix, relative, resolve } from 'path';
59
59
  import { BASE_CONFIG_PATH, configuredProtectedPaths, DEFAULT_SHIP_CONFIG, isPlainBranchName, isRepoPath, loadBaseKnownFlaky, loadTrustedShipConfig, omgRepositoryFallback, readBaseFile, remoteRepoMismatch, resolveTrustedBases, userConfigLayers } from '../../ship/config.js';
60
- import { TRUSTED_READ_ENV } from '../../ship/exec.js';
60
+ import { scrubShipEnv, TRUSTED_READ_ENV } from '../../ship/exec.js';
61
61
  import { listChangedFiles, protectedChanges } from '../../ship/merge.js';
62
62
  import { ESLINT_SCRIPT, PREPARE_CONFIG_STEP, PREPARE_DETECT_STEP, PREPARE_SANDBOX_STEP, runPrepareAsync, VITEST_SCRIPT } from '../../ship/prepare.js';
63
63
  import { parseJsonc } from '../../utils/jsonc.js';
64
- import { nodeModulesTreeProblem, resolveGatesSandboxMode, resolveRequireDeniedPaths } from '../../copilot-run/sandbox.js';
64
+ import { nodeModulesTreeProblem, resolveGateIsolation, resolveGatesSandboxMode, resolveRequireDeniedPaths } from '../../copilot-run/sandbox.js';
65
+ import { CONTAINER_INCOMPATIBLE_ADVICE, containerRunLabel, GATE_CONTAINER_UNAVAILABLE_GATE } from './container-gate.js';
65
66
  import { CREDENTIAL_FILES_READABLE_NOTE, redactGateOutput, sandboxCommandTooLong, sandboxJobRoot, splitFileListArgs } from './sandbox-exec.js';
66
- import { forgetWorktreeGitLinks, readWorktreeGitLinks, recordedWorktreeGitLinks, recordWorktreeGitLinks, removeStaleWorktreeEntry, removeWorkerWorktree, runHostGit, worktreeGitDirArgs, worktreeGitLinksIntact } from '../../team/git-worktree.js';
67
+ import { forgetWorktreeGitLinks, readWorktreeGitLinks, recordedWorktreeGitLinks, recordWorktreeGitLinks, removeStaleWorktreeEntry, removeWorkerWorktree, runHostGit, runHostGitBuffer, worktreeGitDirArgs, worktreeGitLinksIntact } from '../../team/git-worktree.js';
68
+ import { buildGitView, GIT_VIEW_MAX_BYTES, GIT_VIEW_MAX_OBJECTS } from './git-view.js';
67
69
  import { driveGates } from './gates-driver.js';
68
70
  import { missingCheckHint, NO_CI_CHECKS_NOTE, noHeadChecksText } from '../../ship/gates.js';
69
- import { ghCheckRunApps, ghCheckSuites, ghCommitCheckNames, ghRequiredCheckRules } from '../../forge/github/checks.js';
71
+ import { ghBranchTip, ghCheckRunApps, ghCheckSuites, ghCommitCheckNames, ghRequiredCheckRules } from '../../forge/github/checks.js';
70
72
  import { ciFixPrompt, conflictFixPrompt, fenceFor, fenced, fixPrompt, implementPrompt, oneLine, reviewPrompt } from './prompts.js';
71
73
  import { decisionsViolation, loadTeamContext, pathsInDiff, pathsInText } from '../team/context.js';
72
74
  import { mergeComment, mergeDecision } from './merge-policy.js';
75
+ import { autoMergeComment, autoMergeVerdict, baseInstallFiles, baseTestSetup as baseTestSetupOf, classifyChanges, committedMergeConfig, hasFrontmatter, isFrontmatterCandidate, parseChangedEntries, patchLines, resolveAutoMergeConfig, TEST_CONFIG_NAME } from './auto-merge.js';
76
+ import { githubAutoMergeArgs, githubCommitReadArgs } from '../../forge/github/merge.js';
73
77
  import { resolveAzEntry } from '../../forge/ado/az-binary.js';
74
78
  import { adoGuardContext, defaultAzBinaryDeps } from '../../forge/ado/index.js';
75
79
  import { adoBuildUrl } from '../../forge/ado/checks.js';
@@ -82,7 +86,8 @@ import { ghCommentPr, ghCreateDraftPr, ghFindOpenPr, ghMarkReady, ghMergeView, g
82
86
  import { ghDependsOn, ghIssueComment, ghIssueJson, ghIssueView, ghViewItem, githubTracker } from '../../forge/github/tracker.js';
83
87
  import { isSatisfied } from '../check/score.js';
84
88
  import { outcomePosts, postedBefore } from './outcome.js';
85
- import { checkoutBranch, checkoutPath, checkoutWorker, defaultGateConfigLoader, FACTORY_CHECKOUT_TEAM, GATE_CACHE_DIRS, GATE_TREE_MARKER, gateTreeHasLinks, linkNodeModules, unlinkNodeModules } from './prepare.js';
89
+ import { checkoutBranch, checkoutPath, checkoutWorker, defaultGateConfigLoader, FACTORY_CHECKOUT_TEAM, GATE_CACHE_DIRS, GATE_TREE_MARKER, gateTreeHasLinks, linkNodeModules, trustedNestedRels, unlinkNodeModules } from './prepare.js';
90
+ import { baseWorkspacePatterns } from './workspace-tree.js';
86
91
  import { canTransition, createShipState, transition, latestVerdict, parseShipState, recordVerdict, shipStatePath, updateShipState, verifyShipIntegrity, } from '../../ship/state.js';
87
92
  import { ghReviewFeedback } from '../../forge/github/reviews.js';
88
93
  import { ReviewHeadMovedError, visibleLine } from '../../forge/review-feedback.js';
@@ -108,7 +113,7 @@ import { createFactoryProgress } from './progress.js';
108
113
  import { acquireFactoryClaim, claimBusyMessage, factoryClaimHolder, factoryClaimRepo, isShallowClaimRepo, localFactoryClaimRepo, shallowClaimWarning, settleFactoryClaim, trustedFactoryClaimRepo, trustedLocalFactoryClaimRepo } from './claims.js';
109
114
  import { compareSnapshots, replaceObjectsProblem, samePath, snapshotRepo, verifyReviewWorktree } from './review-guard.js';
110
115
  import { GATE_INSTALL_GATE, IMPORT_REFUSED_GATE, LAYOUT_UNSUPPORTED_GATE, PRIVATE_STORE_GATE, PrivateRun, REPO_GUARD_GATE, resolveGateInstall, resolveRunLayout } from './private-run.js';
111
- import { lockfileUnchanged, PrivateRepoTampered, PrivateStoreError, userRepoGuardSnapshot } from './private-store.js';
116
+ import { lockfileUnchanged, PRIVATE_GIT_TIMEOUT_MS, PrivateRepoTampered, PrivateStoreError, userRepoGuardSnapshot } from './private-store.js';
112
117
  import { parseReviewOutput, reviewComment, verdictNotes } from './review-output.js';
113
118
  import { findPlanLink, hasAcceptanceCriteria, issueAuthorTrusted } from './plan-rules.js';
114
119
  import { acquireFactoryOwner, acquireFactoryRepoOwner, createFactoryState, defaultOwnerDeps, EXIT_BUSY, factoryCancelRequested, forgeResumeProblem, factoryOwnerPath, factoryRepoOwnerPath, factoryStateDir, factoryStatePath, HEAL_APPROVE_GATE, HEAL_DIAGNOSIS_GATE, healRunKey, moveTo, overwriteFactoryState, ownerHolding, parseFactoryState, readFactoryState, reviewerName, runLabel, runSlug, setGate, GATE_DETAIL_MAX_CHARS, shipVerdictHash, TERMINAL_FACTORY_PHASES, factoryBranch, trackerStageOf, updateFactoryState, runRemote, verifyFactoryIntegrity, unreadableOwnerMessage, describeOwner, FactoryBusyError, FactoryTamperHoldError, ownerRecord, acquireRunSlot, claimOwner, factorySlotPath, withRepoImportLock, withRepoImportLockAsync, } from './state.js';
@@ -243,7 +248,7 @@ function hostGitStatus(cwd, args) {
243
248
  * copy record is followed by its original path as a record of its own,
244
249
  * without the two status letters.
245
250
  */
246
- function checkoutChanges(root, checkout, raw) {
251
+ function checkoutChanges(root, checkout, raw, nested) {
247
252
  let ownLink = false;
248
253
  let ownTree = false;
249
254
  try {
@@ -260,7 +265,10 @@ function checkoutChanges(root, checkout, raw) {
260
265
  catch { /* no link */ }
261
266
  // Of the tree only untracked entries are dropped: a tracked file under node_modules the PR's code changed still counts.
262
267
  const untracked = ownTree ? new Set(raw.split('\0').filter((r) => r.startsWith('?? ')).map((r) => r.slice(3))) : new Set();
263
- return parseStatusPaths(raw).filter((p) => p && !(ownLink && (p === 'node_modules' || p === 'node_modules/')) && !(untracked.has(p) && p.startsWith('node_modules/')));
268
+ // The nested workspace trees too (`packages/a/node_modules/`), only those of the engine's list (trustedNestedRels):
269
+ // the marker alone is PR-writable (review-501 L2).
270
+ const trees = ['node_modules/', ...(ownTree ? nested.map((rel) => `${rel}/node_modules/`) : [])];
271
+ return parseStatusPaths(raw).filter((p) => p && !(ownLink && (p === 'node_modules' || p === 'node_modules/')) && !(untracked.has(p) && trees.some((t) => p.startsWith(t))));
264
272
  }
265
273
  /** The paths of `git status --porcelain=v1 -z` records (an R/C record's original path included). */
266
274
  function parseStatusPaths(raw) {
@@ -319,8 +327,14 @@ export function nodeModulesWriteDenied(tail) {
319
327
  }
320
328
  return undefined;
321
329
  }
330
+ /** The advice when the base's gate runs git's own transport, which cannot run in the Copilot sandbox on Windows. */
331
+ export const GIT_TRANSPORT_SANDBOX_ADVICE = 'Your gate runs git clone, fetch or push (also to a local path or a temp repository), which cannot run in the OS sandbox on Windows: git starts that transport through Git for Windows\' sh.exe, and no MSYS2 program starts in the sandbox; the sandbox has no network either. Read-only git (rev-parse, ls-files, log) and git init, add and commit work. Make those tests skip the transport, run them outside prepare, or set factory.run.sandbox.isolation "container" (with an image that has git) in your user config';
322
332
  /** What the gate-sandbox-incompatible park of a failing base calibration tells the human to do. */
323
- export function sandboxIncompatibleAdvice(tail) {
333
+ export function sandboxIncompatibleAdvice(tail, platform = process.platform) {
334
+ // git clone, fetch and push to a local path start git-upload-pack / git-receive-pack through Git for Windows' sh.exe,
335
+ // and no MSYS2 program starts in the Copilot sandbox on Windows (exit 0xC0000142, live 2026-11-12); no network either.
336
+ if (platform === 'win32' && tail?.includes('Could not read from remote repository'))
337
+ return GIT_TRANSPORT_SANDBOX_ADVICE;
324
338
  const denied = tail ? nodeModulesWriteDenied(tail) : undefined;
325
339
  // A per-run dir is writable in the tree already: a denial there is not this case.
326
340
  if (!denied || GATE_CACHE_DIRS.includes(denied.slice('node_modules/'.length)))
@@ -561,6 +575,8 @@ class FactoryEngine {
561
575
  mergeCmd;
562
576
  /** Ship's gate config of this invocation, by the base sha it was loaded at. */
563
577
  gateCfg;
578
+ /** The base's workspace globs of this invocation (baseWorkspaces), by the base sha they were read at. */
579
+ wsGlobs;
564
580
  /** The Azure DevOps forge; undefined = GitHub through the gh calls. */
565
581
  forge;
566
582
  /** The forge, for messages. */
@@ -592,8 +608,11 @@ class FactoryEngine {
592
608
  gatesAllowed;
593
609
  /** factory.run.sandbox.gates, resolved once per trusted base commit. */
594
610
  gatesModeCache;
611
+ /** The gate image's id (`sha256:...`) the last container run reported: base calibrations are keyed on it, not on the tag (L2, review-499). */
612
+ containerImageId;
595
613
  /** The one-per-run warning that the sandbox on this host cannot deny paths was given. */
596
614
  warnedCredentialFilesReadable = false;
615
+ warnedCommittedMerge = false;
597
616
  /** Calibrations re-run in this invocation (a failing one is retried once per invocation). */
598
617
  recalibrated = new Set();
599
618
  /** The prepare checkout's git dir, named explicitly to engine git there once the PR's code ran in it (pinCheckoutGit). */
@@ -1020,7 +1039,89 @@ class FactoryEngine {
1020
1039
  */
1021
1040
  sandboxRun(req) {
1022
1041
  const p = this.privateRun();
1023
- return this.o.gateSandbox({ ...req, nodeModulesTarget: join(this.o.root, 'node_modules'), ...(p ? { mainRoot: this.o.root, jobRoot: this.gateJobRoot() } : {}) });
1042
+ // The nested workspace trees' targets the engine vouches for (review-501 M1): the PR-writable marker alone grants nothing.
1043
+ const nested = trustedNestedRels(this.o.root, req.cwd, this.baseWorkspaces()).map((rel) => join(this.o.root, ...rel.split('/'), 'node_modules'));
1044
+ // isolation "container" (gatesSandbox, user config): the runner uses the container, labelled with this run.
1045
+ const container = this.gatesModeCache?.container;
1046
+ // review-499b N3: never the OS sandbox because gatesSandbox() was not resolved yet in this process.
1047
+ if (!container && this.containerIsolated())
1048
+ return Promise.reject(new FactoryStepError('factory.run.sandbox.isolation "container" is set in your user config, but the gate settings were not resolved before a gate command; nothing ran'));
1049
+ const r = this.o.gateSandbox({ ...req, nodeModulesTarget: join(this.o.root, 'node_modules'), ...(nested.length > 0 ? { nestedNodeModulesTargets: nested } : {}), ...(p ? { mainRoot: this.o.root, jobRoot: this.gateJobRoot() } : {}), ...(container ? { container, runLabel: containerRunLabel(this.o.root, this.key) } : {}) });
1050
+ if (!container)
1051
+ return r;
1052
+ return r.then((out) => {
1053
+ if (out.ran && out.imageId)
1054
+ this.containerImageId = out.imageId;
1055
+ return out;
1056
+ });
1057
+ }
1058
+ /** git-view.ts's source in your repository (the base, a shared-layout checkout's commits): hardened host git, GIT_* scrubbed. */
1059
+ hostViewSource() {
1060
+ const env = scrubShipEnv(process.env);
1061
+ return (args, input) => runHostGitBuffer(this.o.root, args, PRIVATE_GIT_TIMEOUT_MS, env, input);
1062
+ }
1063
+ /** buildGitView with timed host git on the new view; a failure removes what was made and throws. */
1064
+ buildViewOrClean(dir, sha, source) {
1065
+ const env = scrubShipEnv(process.env);
1066
+ try {
1067
+ return buildGitView(dir, sha, source, (cwd, args, input) => runHostGit(cwd, args, PRIVATE_GIT_TIMEOUT_MS, env, input));
1068
+ }
1069
+ catch (error) {
1070
+ try {
1071
+ rmSync(join(dir, '.git'), { recursive: true, force: true });
1072
+ }
1073
+ catch { /* best effort */ }
1074
+ throw error;
1075
+ }
1076
+ }
1077
+ /**
1078
+ * A one-commit git view of `sha` at `<dir>/.git` (git-view.ts), or none:
1079
+ * a failure only warns and removes what was made, and the command runs
1080
+ * without git as before (a check that needs git then fails on its own).
1081
+ * The base calibration only; a container gate gets no verdict instead.
1082
+ */
1083
+ makeGitView(dir, sha, source, what) {
1084
+ try {
1085
+ return this.buildViewOrClean(dir, sha, source);
1086
+ }
1087
+ catch (error) {
1088
+ this.o.warn?.(`omg factory run: ${what} at ${sha.slice(0, 12)} runs without a git view (${oneLine(errText(error), 300)}); a check there that runs git fails`);
1089
+ return undefined;
1090
+ }
1091
+ }
1092
+ /**
1093
+ * isolation "container": `run` with a one-commit git view of the commit
1094
+ * `sha()` reads (engine git, before the container starts), made in a fresh
1095
+ * dir under the gate job root and removed after; the checkout's own `.git`
1096
+ * names a host git dir the container never sees. A view that cannot be
1097
+ * built runs nothing: no verdict (gate-no-verdict), never a run without
1098
+ * git. The OS sandbox: `run` as it is (the prepare checkout's link to its
1099
+ * git dir works there, read-only).
1100
+ */
1101
+ async withGitView(sha, what, run) {
1102
+ if (!this.gatesModeCache?.container)
1103
+ return run({});
1104
+ const jobRoot = this.gateJobRoot();
1105
+ mkdirSync(jobRoot, { recursive: true });
1106
+ const dir = mkdtempSync(join(jobRoot, 'gitview-'));
1107
+ try {
1108
+ let gitView;
1109
+ try {
1110
+ const at = sha().trim();
1111
+ const priv = this.privateRun();
1112
+ gitView = this.buildViewOrClean(dir, at, priv ? priv.viewSource() : this.hostViewSource());
1113
+ }
1114
+ catch (error) {
1115
+ return { ran: false, started: true, reason: `${GIT_VIEW_UNBUILT}${what} could not be built (${oneLine(errText(error), 300)}); nothing ran` };
1116
+ }
1117
+ return await run({ gitView });
1118
+ }
1119
+ finally {
1120
+ try {
1121
+ rmSync(dir, { recursive: true, force: true });
1122
+ }
1123
+ catch { /* best effort */ }
1124
+ }
1024
1125
  }
1025
1126
  /**
1026
1127
  * Why `<checkout>/node_modules` must not be granted: a link in the
@@ -1031,6 +1132,48 @@ class FactoryEngine {
1031
1132
  nodeModulesRepointed(checkout) {
1032
1133
  return nodeModulesTreeProblem(checkout, join(this.o.root, 'node_modules')).problem;
1033
1134
  }
1135
+ /**
1136
+ * The workspace globs (workspace-tree.ts) of the TRUSTED BASE at `baseSha`
1137
+ * (root package.json, pnpm-workspace.yaml), never the PR head's; none when
1138
+ * there is no full base sha or the files are absent. Without a sha: the
1139
+ * last base read in this invocation, else the run's recorded base.
1140
+ */
1141
+ baseWorkspaces(baseSha) {
1142
+ const sha = baseSha ?? this.wsGlobs?.baseSha ?? this.state.baseSha;
1143
+ if (!sha || !HEX40.test(sha))
1144
+ return [];
1145
+ if (this.wsGlobs?.baseSha === sha)
1146
+ return this.wsGlobs.globs;
1147
+ const read = (file) => { try {
1148
+ return runHostGit(this.o.root, ['cat-file', 'blob', `${sha}:${file}`]);
1149
+ }
1150
+ catch {
1151
+ return null;
1152
+ } };
1153
+ this.wsGlobs = { baseSha: sha, globs: baseWorkspacePatterns(read) };
1154
+ return this.wsGlobs.globs;
1155
+ }
1156
+ /** linkNodeModules with the base's workspaces; a layout it does not support is a warning here (the base calibration parks on it). */
1157
+ linkGateTree(path, baseSha) {
1158
+ const problem = linkNodeModules(this.o.root, path, this.o.warn, this.baseWorkspaces(baseSha));
1159
+ if (problem)
1160
+ this.o.warn?.(`omg factory run: ${problem}; a gate that fails in the sandbox parks at ${GATE_SANDBOX_INCOMPATIBLE_GATE}`);
1161
+ }
1162
+ /**
1163
+ * A checkout kept after a failed discard gets its node_modules tree back
1164
+ * (the local gate runs in it). A failure only warns: the discard's own
1165
+ * error is the one reported (review-501b INFO).
1166
+ */
1167
+ relinkKeptCheckout(path) {
1168
+ if (this.containerIsolated())
1169
+ return;
1170
+ try {
1171
+ this.linkGateTree(path);
1172
+ }
1173
+ catch (error) {
1174
+ this.o.warn?.(`omg factory run: could not link the node_modules tree of the kept prepare checkout ${path} again (${oneLine(errText(error), 300)})`);
1175
+ }
1176
+ }
1034
1177
  /** The engine's prepare and local-gate checkout: `<run>/w/prep` in the private layout. */
1035
1178
  checkoutDir() {
1036
1179
  const p = this.privateRun();
@@ -1202,9 +1345,12 @@ class FactoryEngine {
1202
1345
  * sandbox with the registry reachable. Null when the checkout is ready.
1203
1346
  */
1204
1347
  async privateNodeModules(p, path, baseSha, head, loaded) {
1348
+ // isolation "container": every command installs into its own container volume; the checkout needs no node_modules.
1349
+ if (this.gatesSandbox(loaded).container)
1350
+ return null;
1205
1351
  const rule = lockfileUnchanged(p.repo, baseSha, head, p.ctx);
1206
1352
  if (rule.policy === 'junction') {
1207
- linkNodeModules(this.o.root, path, this.o.warn);
1353
+ this.linkGateTree(path, baseSha);
1208
1354
  return null;
1209
1355
  }
1210
1356
  const what = rule.lockfiles.length === 0 ? 'the base has no lockfile' : `the PR changes ${rule.changed.join(', ')}`;
@@ -2718,7 +2864,7 @@ class FactoryEngine {
2718
2864
  }
2719
2865
  prView(pr) {
2720
2866
  if (!this.forge)
2721
- return this.gh((exec, cwd) => ghMergeView(exec, pr, cwd));
2867
+ return this.liveBase(this.gh((exec, cwd) => ghMergeView(exec, pr, cwd)));
2722
2868
  // The local forge: the human merged on the local base, so sync it to the mirror first (fast-forward only); the PR then reads MERGED.
2723
2869
  if (this.forge.kind !== 'local') {
2724
2870
  const v = this.forge.reviews.viewPr(pr);
@@ -2743,6 +2889,21 @@ class FactoryEngine {
2743
2889
  throw new MirrorBaseMovedError(`the local forge mirror's ${this.state.base} moved to ${v.baseRefOid.slice(0, 12)} while the PR was read; the engine synced ${sealed.slice(0, 12)}. Check what wrote the mirror ${this.o.forge.config.repo.url}, then rerun ${this.resume}`);
2744
2890
  return { number: v.number, state: v.state, isDraft: v.isDraft, baseRefName: v.baseRefName, baseRefOid: sealed, headRefOid: v.headRefOid };
2745
2891
  }
2892
+ /**
2893
+ * GitHub: an open PR's base sha is its base branch's live tip (ghBranchTip), not the PR's baseRefOid, which
2894
+ * stays at the base of the PR's last update after another merge into the base. Prepare merges this tip, the
2895
+ * trusted config is read at it after the fetched ref is checked against it, and the merge rule's diffs and
2896
+ * housekeeping checks see the base the head contains. A failed read fails closed; a closed, merged or
2897
+ * retargeted PR keeps its view (prGone stops or parks before any base is used).
2898
+ */
2899
+ liveBase(view) {
2900
+ if (view.state !== 'OPEN' || view.baseRefName !== this.state.base)
2901
+ return view;
2902
+ const repo = this.githubReadContext()?.repo;
2903
+ if (!repo)
2904
+ throw new FactoryStepError(`the run's GitHub repository is not known, so the live tip of ${this.state.base} cannot be read for PR #${view.number}; refusing (fail closed)`);
2905
+ return { ...view, recordedBaseRefOid: view.baseRefOid, baseRefOid: this.gh((exec, cwd) => ghBranchTip(exec, repo, view.baseRefName, cwd)) };
2906
+ }
2746
2907
  /** The PR is not open, or targets another base: true when the run moved (merged) or parked. */
2747
2908
  prGone(view) {
2748
2909
  if (view.state === 'MERGED') {
@@ -2760,7 +2921,7 @@ class FactoryEngine {
2760
2921
  return false;
2761
2922
  }
2762
2923
  /**
2763
- * Ship's gate config at GitHub's base sha, loaded once per base sha. When
2924
+ * Ship's gate config at the view's base sha (on GitHub the base branch's live tip, liveBase), loaded once per base sha. When
2764
2925
  * its fetch moved origin/<base>, the recheck baseline follows.
2765
2926
  */
2766
2927
  gateConfig(view) {
@@ -2874,8 +3035,8 @@ class FactoryEngine {
2874
3035
  forgetWorktreeGitLinks(path);
2875
3036
  }
2876
3037
  catch (error) {
2877
- // A kept checkout keeps its tooling (the local gate runs in it).
2878
- linkNodeModules(this.o.root, path, this.o.warn);
3038
+ // A kept checkout keeps its tooling (the local gate runs in it); with isolation "container" it never had the link.
3039
+ this.relinkKeptCheckout(path);
2879
3040
  throw new FactoryStepError(`could not discard the engine's prepare checkout ${path}: ${errText(error)}`);
2880
3041
  }
2881
3042
  this.save((x) => {
@@ -2927,7 +3088,7 @@ class FactoryEngine {
2927
3088
  removeWorkerWorktree(FACTORY_CHECKOUT_TEAM, checkoutWorker(this.key), this.o.root, { contained: [...new Set(contained)] });
2928
3089
  }
2929
3090
  catch (error) {
2930
- linkNodeModules(this.o.root, path, this.o.warn);
3091
+ this.relinkKeptCheckout(path);
2931
3092
  throw new FactoryStepError(`could not discard the engine's prepare checkout ${path}, which an older release made: ${errText(error)}. ${this.freshCheckoutRecovery()}`);
2932
3093
  }
2933
3094
  this.save((x) => {
@@ -3109,8 +3270,10 @@ class FactoryEngine {
3109
3270
  return;
3110
3271
  }
3111
3272
  }
3112
- else
3113
- linkNodeModules(this.o.root, path, this.o.warn);
3273
+ else if (!this.gatesSandbox(this.gateConfig(view)).container) {
3274
+ // isolation "container" (C1, review-499): no link to your node_modules in a checkout the container's writes come back to.
3275
+ this.linkGateTree(path, view.baseRefOid);
3276
+ }
3114
3277
  // The checkout's gitfile before any PR code ran: compared after each check, and its git dir named to engine git from then on.
3115
3278
  const gitLink = checkoutGitLink(path);
3116
3279
  if (!gitLink.gitDir)
@@ -3148,7 +3311,7 @@ class FactoryEngine {
3148
3311
  this.checkoutGitPin = undefined;
3149
3312
  }
3150
3313
  const fetched = result.steps.some((st) => st.name === 'fetch' && st.status === 'ok');
3151
- // From here the PR's diff (review, protected paths) is against the base GitHub reports.
3314
+ // From here the PR's diff (review, protected paths) is against the base prepare merged (on GitHub its live tip, liveBase).
3152
3315
  const sandboxNote = ran.modes.size > 0 ? [{ at: this.iso(), from: s.phase, to: s.phase, note: `prepare checks on ${head.slice(0, 12)} ran ${[...ran.modes].map((m) => (m === 'enforced' ? 'in the OS sandbox' : m === 'enforced-readable' ? `in the OS sandbox (${CREDENTIAL_FILES_READABLE_NOTE})` : `unsandboxed (${m})`)).join(' and ')}` }] : [];
3153
3316
  const sandboxed = ran.modes.has('enforced') || ran.modes.has('enforced-readable');
3154
3317
  this.save((x) => ({ ...x, checkoutHead, ...(sandboxed ? { sandboxedPrepareHead: checkoutHead } : {}), ...(fetched ? { baseSha: view.baseRefOid } : {}), history: [...x.history, ...sandboxNote] }));
@@ -3212,7 +3375,15 @@ class FactoryEngine {
3212
3375
  try {
3213
3376
  const text = commit ? readBaseFile(this.exec, this.o.root, commit, BASE_CONFIG_PATH) : null;
3214
3377
  const base = text && text.trim() ? parseJsonc(text) : undefined;
3215
- resolved = { ...resolveGatesSandboxMode({ user, base, env: process.env }), requireDeniedPaths: resolveRequireDeniedPaths({ user, base }).require };
3378
+ // factory.run.sandbox.isolation / .container: the user config only; a committed value is ignored with a notice.
3379
+ const isolation = resolveGateIsolation({ user, base });
3380
+ if (isolation.ignoredBase.length > 0)
3381
+ this.o.warn?.(`omg factory run: ignoring ${isolation.ignoredBase.join(' and ')} in the base .copilot/omg.jsonc: where the PR's code runs is set in your user config only`);
3382
+ resolved = { ...resolveGatesSandboxMode({ user, base, env: process.env }), requireDeniedPaths: resolveRequireDeniedPaths({ user, base }).require, ...(isolation.container ? { container: isolation.container } : {}) };
3383
+ // L3 (review-499): "ack" (or the kill switch) means the OS sandbox is not used; with the container the PR's code
3384
+ // still runs there, never plainly on your host after an ack.
3385
+ if (resolved.container && resolved.mode === 'ack')
3386
+ resolved = { ...resolved, mode: 'enforced', source: `${resolved.source}; isolation "container" runs it in the gate container` };
3216
3387
  }
3217
3388
  catch (error) {
3218
3389
  throw new FactoryStepError(`factory.run.sandbox: ${errText(error)}`);
@@ -3220,6 +3391,31 @@ class FactoryEngine {
3220
3391
  this.gatesModeCache = { commit, ...resolved };
3221
3392
  return this.gatesModeCache;
3222
3393
  }
3394
+ /**
3395
+ * Whether isolation "container" is in force, before or without a base read:
3396
+ * it comes from the user config alone (review-499b N3). A user config that
3397
+ * cannot be read or resolved counts as container, so the engine never
3398
+ * links your node_modules into a checkout or runs on the OS sandbox by default.
3399
+ */
3400
+ containerIsolated() {
3401
+ if (this.gatesModeCache)
3402
+ return this.gatesModeCache.container !== undefined;
3403
+ let user = this.o.gateSandboxUserConfig;
3404
+ if (user === undefined) {
3405
+ try {
3406
+ user = userConfigLayers().trustedUser;
3407
+ }
3408
+ catch {
3409
+ return true;
3410
+ }
3411
+ }
3412
+ try {
3413
+ return resolveGateIsolation({ user, base: undefined }).container !== undefined;
3414
+ }
3415
+ catch {
3416
+ return true;
3417
+ }
3418
+ }
3223
3419
  /**
3224
3420
  * A sandboxed command ran on a host without denied_paths (the Copilot
3225
3421
  * sandbox on Windows): one warning per run and one PR note per head.
@@ -3255,9 +3451,21 @@ class FactoryEngine {
3255
3451
  const at = head.slice(0, 12);
3256
3452
  return `${what} on ${at} could not start in the OS sandbox (${why}) after the PR's code of this head already ran in it (an earlier prepare check), so the PR's code may be the cause. The head is not judged: no pass, no FAILURE, no ci-fix lane, and --allow-unsandboxed-gates does not apply here. Rerun ${this.resume} to try again; if it parks here again, review the PR's diff and fix the cause`;
3257
3453
  }
3454
+ /** The park when isolation "container" cannot run `what` (container-gate.ts): nothing ran, no ack offer, no fallback. */
3455
+ gateContainerUnavailableReason(head, what, why) {
3456
+ return `${what} on ${head.slice(0, 12)} did not run: factory.run.sandbox.isolation is "container" and the gate container is not available (${why}). The head is not judged: no pass, no FAILURE, no ci-fix lane, and it never falls back to the Copilot sandbox. Fix that, then rerun ${this.resume}`;
3457
+ }
3458
+ /** Where a sandboxed command runs, for parks and notes: the gate container (isolation "container") or the OS sandbox. */
3459
+ sandboxName() {
3460
+ return this.gatesModeCache?.container ? `the gate container (${this.gatesModeCache.container.runtime} ${this.gatesModeCache.container.image})` : 'the OS sandbox';
3461
+ }
3258
3462
  /** The park after the command ran in the sandbox without a verdict: no ack offer, no pass, no failure. `why` is fixed text (sandbox-exec.ts). */
3259
3463
  gateNoVerdictReason(head, what, why) {
3260
3464
  const at = head.slice(0, 12);
3465
+ // withGitView's own failure: nothing ran, so the PR's code had no exit code to hide.
3466
+ if (why.startsWith(GIT_VIEW_UNBUILT)) {
3467
+ return `${what} on ${at} did not run: ${why}. The head is not judged: no pass, no FAILURE, no ci-fix lane, and the check never runs without git. Rerun ${this.resume} to try again; if it parks here again, check free disk space and the size of the head (a git view holds at most ${GIT_VIEW_MAX_OBJECTS} objects and ${GIT_VIEW_MAX_BYTES / (1024 * 1024)} MB), or set factory.run.sandbox.isolation back to "copilot" in your user config`;
3468
+ }
3261
3469
  return `${what} on ${at} ran in the OS sandbox but gave no verdict (${why}). The head is not judged: no pass, no FAILURE, no ci-fix lane, and --allow-unsandboxed-gates does not apply here. Rerun ${this.resume} to try again; if it parks here again, review the PR's diff: the PR's code can hide its own exit code (a second or missing exit marker, a killed shell, a hang)`;
3262
3470
  }
3263
3471
  /** What a prepare check is called in parks, notes and warnings: a configured argv (trusted config), never a built-in's file list (the PR's file names). */
@@ -3356,8 +3564,11 @@ class FactoryEngine {
3356
3564
  // H1: the problem names a link target the PR's code chose: local detail only.
3357
3565
  if (repointed)
3358
3566
  return stop({ name: 'lane-tampered', reason: `${label} on ${head.slice(0, 12)} did not run: ${join(path, 'node_modules')} (or a link in it) is not as the engine made it, so the PR's code changed it${localDetailNote(this.key, 'which link')}; nothing of this prepare is trusted and nothing is pushed; inspect and remove ${path} by hand`, detail: oneLine(visibleLine(repointed), PARK_TAIL_CHARS) });
3567
+ // Still inside checkoutGitPin: engine git reads the checkout's HEAD (prepare's merge or inventory commit) through its recorded git dir.
3568
+ const priv = this.privateRun();
3569
+ const checkedOut = () => (priv ? priv.gitOk(['rev-parse', 'HEAD'], 'reading the prepare checkout', path) : this.run(['rev-parse', 'HEAD'], 'git', undefined, path));
3359
3570
  const r = this.o.gateSandbox
3360
- ? await this.sandboxRun({ purpose: 'prepare', argv: c.argv, exe: c.exe, args: c.args, cwd: path, commonGitDir: at.commonGitDir, timeoutMs: PREPARE_CHECK_TIMEOUT_MS, ...(at.gates.requireDeniedPaths ? { requireDeniedPaths: true } : {}) })
3571
+ ? await this.withGitView(checkedOut, label, (view) => this.sandboxRun({ purpose: 'prepare', argv: c.argv, exe: c.exe, args: c.args, cwd: path, commonGitDir: at.commonGitDir, timeoutMs: PREPARE_CHECK_TIMEOUT_MS, ...(at.gates.requireDeniedPaths ? { requireDeniedPaths: true } : {}), ...view }))
3361
3572
  : { ran: false, reason: 'no OS sandbox runner was given to the engine' };
3362
3573
  const t = tampered();
3363
3574
  if (t)
@@ -3379,6 +3590,9 @@ class FactoryEngine {
3379
3590
  }
3380
3591
  if (r.started)
3381
3592
  return stop({ name: GATE_NO_VERDICT_GATE, reason: this.gateNoVerdictReason(head, label, r.reason) });
3593
+ // isolation "container" without a usable runtime: its own park, never the weaker sandbox and never the ack offer.
3594
+ if (r.unavailable)
3595
+ return stop({ name: GATE_CONTAINER_UNAVAILABLE_GATE, reason: this.gateContainerUnavailableReason(head, label, r.reason) });
3382
3596
  // An earlier check of this head already ran the PR's code in the sandbox: a start failure now may be its doing.
3383
3597
  // Only a configured command (trusted config) refused for its own shape or length keeps the ack offer; a
3384
3598
  // built-in's argv holds the PR's file names, so its refusal parks here too.
@@ -3404,22 +3618,25 @@ class FactoryEngine {
3404
3618
  * on the base itself, or its calibration could not run.
3405
3619
  */
3406
3620
  async calibrateGate(c, baseSha, commonGitDir, timeoutMs, what, head) {
3407
- const key = createHash('sha256').update(`${baseSha}\0${JSON.stringify(c.argv)}`).digest('hex');
3621
+ // A calibration holds for the isolation it ran in: the gate container's (and its image, by id once a run reported it)
3622
+ // is keyed apart from the OS sandbox's.
3623
+ const container = this.gatesModeCache?.container;
3624
+ const key = createHash('sha256').update(`${baseSha}\0${JSON.stringify(c.argv)}${container ? `\0container\0${container.runtime}\0${this.containerImageId ?? container.image}` : ''}`).digest('hex');
3408
3625
  let cal = this.state.gateCalibration?.[key];
3409
3626
  if (!cal || (!cal.ok && !this.recalibrated.has(key))) {
3410
3627
  this.recalibrated.add(key);
3411
3628
  const out = await this.runOnBase(c, baseSha, commonGitDir, timeoutMs);
3412
3629
  if ('notStarted' in out) {
3413
- return { name: GATE_SANDBOX_INCOMPATIBLE_GATE, reason: `${what} failed in the OS sandbox on ${head.slice(0, 12)}, and its calibration on the base ${baseSha.slice(0, 12)} could not run (${out.notStarted}); the failure is not counted (no ci-fix lane). Fix the cause, then rerun ${this.resume}. ${ACK_WARNING}` };
3630
+ return { name: GATE_SANDBOX_INCOMPATIBLE_GATE, reason: `${what} failed in ${this.sandboxName()} on ${head.slice(0, 12)}, and its calibration on the base ${baseSha.slice(0, 12)} could not run (${out.notStarted}); the failure is not counted (no ci-fix lane). Fix the cause, then rerun ${this.resume}. ${ACK_WARNING}` };
3414
3631
  }
3415
3632
  cal = out;
3416
- this.save((x) => ({ ...x, gateCalibration: { ...(x.gateCalibration ?? {}), [key]: out }, history: [...x.history, { at: this.iso(), from: x.phase, to: x.phase, note: `calibrated ${what.slice(0, 120)} in the OS sandbox on the base ${baseSha.slice(0, 12)}: ${out.ok ? 'passes' : 'fails'}` }] }));
3633
+ this.save((x) => ({ ...x, gateCalibration: { ...(x.gateCalibration ?? {}), [key]: out }, history: [...x.history, { at: this.iso(), from: x.phase, to: x.phase, note: `calibrated ${what.slice(0, 120)} in ${this.sandboxName()} on the base ${baseSha.slice(0, 12)}: ${out.ok ? 'passes' : 'fails'}` }] }));
3417
3634
  }
3418
3635
  if (cal.ok)
3419
3636
  return null;
3420
3637
  return {
3421
3638
  name: GATE_SANDBOX_INCOMPATIBLE_GATE,
3422
- reason: `${what} fails in the OS sandbox on the base ${baseSha.slice(0, 12)} itself, so its failure on ${head.slice(0, 12)} is not counted (no ci-fix lane). ${sandboxIncompatibleAdvice(cal.tail)}, then rerun ${this.resume}. ${ACK_WARNING}${cal.tail ? `; base output tail: ${cal.tail.slice(-1_500)}` : ''}`,
3639
+ reason: `${what} fails in ${this.sandboxName()} on the base ${baseSha.slice(0, 12)} itself, so its failure on ${head.slice(0, 12)} is not counted (no ci-fix lane). ${this.gatesModeCache?.container ? CONTAINER_INCOMPATIBLE_ADVICE : sandboxIncompatibleAdvice(cal.tail)}, then rerun ${this.resume}. ${ACK_WARNING}${cal.tail ? `; base output tail: ${cal.tail.slice(-1_500)}` : ''}`,
3423
3640
  };
3424
3641
  }
3425
3642
  /**
@@ -3441,8 +3658,16 @@ class FactoryEngine {
3441
3658
  const env = { ...process.env, GIT_INDEX_FILE: index, GIT_NO_REPLACE_OBJECTS: '1' };
3442
3659
  runHostGit(this.o.root, ['read-tree', baseSha], undefined, env);
3443
3660
  runHostGit(this.o.root, ['checkout-index', '-a', '-f', `--prefix=${dir.replace(/\\/g, '/')}/`], undefined, env);
3444
- linkNodeModules(this.o.root, dir, this.o.warn);
3445
- const r = await this.sandboxRun({ purpose: 'calibrate', argv: c.argv, exe: c.exe, args: calibrationArgs(c, dir), cwd: dir, commonGitDir, timeoutMs, ...(this.gatesModeCache?.requireDeniedPaths ? { requireDeniedPaths: true } : {}) });
3661
+ // The export has no git: a one-commit view of the base at <dir>/.git, removed with the dir (git-view.ts).
3662
+ const gitView = this.makeGitView(dir, baseSha, this.hostViewSource(), 'the base calibration');
3663
+ // isolation "container": the container installs its own; your node_modules is never linked in (C1, review-499).
3664
+ if (!this.gatesModeCache?.container) {
3665
+ // A workspace layout the gate does not support (Yarn PnP, a nested git repository, over the bounds) parks here, named.
3666
+ const layout = linkNodeModules(this.o.root, dir, this.o.warn, this.baseWorkspaces(baseSha));
3667
+ if (layout)
3668
+ return { notStarted: visibleLine(layout) };
3669
+ }
3670
+ const r = await this.sandboxRun({ purpose: 'calibrate', argv: c.argv, exe: c.exe, args: calibrationArgs(c, dir), cwd: dir, commonGitDir, timeoutMs, ...(this.gatesModeCache?.requireDeniedPaths ? { requireDeniedPaths: true } : {}), ...(gitView ? { gitView } : {}) });
3446
3671
  if (!r.ran)
3447
3672
  return { notStarted: r.reason };
3448
3673
  const tail = r.output.trim().slice(-2_000);
@@ -3730,7 +3955,7 @@ class FactoryEngine {
3730
3955
  const fresh = { ...process.env, GIT_INDEX_FILE: join(indexDir, 'index') };
3731
3956
  runHostGit(checkout, [...gitArgs, 'read-tree', at], undefined, fresh);
3732
3957
  const status = [...gitArgs, '-c', 'core.untrackedCache=false', 'status', '--porcelain=v1', '-z', '--untracked-files=all'];
3733
- dirty = checkoutChanges(this.o.root, checkout, runHostGit(checkout, status, undefined, fresh));
3958
+ dirty = checkoutChanges(this.o.root, checkout, runHostGit(checkout, status, undefined, fresh), trustedNestedRels(this.o.root, checkout, this.baseWorkspaces()));
3734
3959
  }
3735
3960
  catch (error) {
3736
3961
  problem = errText(error);
@@ -3821,7 +4046,7 @@ class FactoryEngine {
3821
4046
  return false;
3822
4047
  }
3823
4048
  out = this.o.gateSandbox
3824
- ? await runLocalGate({ ...input, mode: 'enforced', sandbox: { run: (req) => this.sandboxRun(req), commonGitDir: common, requireDeniedPaths: gates.requireDeniedPaths } })
4049
+ ? await runLocalGate({ ...input, mode: 'enforced', sandbox: { run: (req) => this.withGitView(() => head, 'the local gate', (view) => this.sandboxRun({ ...req, ...view })), commonGitDir: common, requireDeniedPaths: gates.requireDeniedPaths } })
3825
4050
  : { started: false, reason: 'no OS sandbox runner was given to the engine', sandbox: true };
3826
4051
  // The gate handed the PR's code of this head to the sandbox (a verdict or not): a later start failure on a
3827
4052
  // rerun of the gate for this head may be that code's doing.
@@ -3834,6 +4059,10 @@ class FactoryEngine {
3834
4059
  this.gate(GATE_NO_VERDICT_GATE, this.gateNoVerdictReason(head, `the local gate \`${gate.join(' ')}\``, out.reason));
3835
4060
  return false;
3836
4061
  }
4062
+ if (!out.started && out.unavailable) {
4063
+ this.gate(GATE_CONTAINER_UNAVAILABLE_GATE, this.gateContainerUnavailableReason(head, `the local gate \`${gate.join(' ')}\``, out.reason));
4064
+ return false;
4065
+ }
3837
4066
  unavailable = !out.started && out.sandbox === true;
3838
4067
  // Prepare, or an earlier run of this gate, already ran the PR's code of this head in the sandbox: a start
3839
4068
  // failure now may be its doing.
@@ -4005,7 +4234,7 @@ class FactoryEngine {
4005
4234
  this.gate('no-workflows', `${out.report.noHeadChecks ? `${noHeadChecksText(out.report.noHeadChecks)} (head ${at})` : `no checks and no workflow runs exist for ${at}`}; push the branch with a token that triggers workflows (or enable Actions), or close and reopen PR #${pr}${out.report.noHeadChecks ? `; to stop instead: ${cancelCommand(this.key)}` : ''}`);
4006
4235
  return;
4007
4236
  case 'timeout':
4008
- this.gate('gates-timeout', `gates did not settle within factory.run.gatesTimeoutMinutes ${Math.round(this.o.limits.gatesTimeoutMs / 60_000)} at ${at}${out.report ? ` (pending: ${out.report.pending.join(', ') || 'none'})` : ''}`);
4237
+ this.gate('gates-timeout', `gates did not settle within factory.run.gatesTimeoutMinutes ${Math.round(this.o.limits.gatesTimeoutMs / 60_000)} at ${at}${out.report ? ` (pending: ${out.report.pending.join(', ') || 'none'})` : ''}; rerun ${this.resume} to wait again, or ${cancelCommand(this.key)}`);
4009
4238
  return;
4010
4239
  case 'head-moved':
4011
4240
  this.gate('head-moved-externally', `PR #${pr} head is ${out.headRefOid.slice(0, 12)}, the engine pushed ${at}`);
@@ -4056,21 +4285,25 @@ class FactoryEngine {
4056
4285
  this.save((x) => moveTo(x, 'gates', `gates no longer green: ${decision.reasons.join('; ')}`, this.iso()));
4057
4286
  return;
4058
4287
  }
4288
+ // Opt-in (factory.merge.auto, user config only): true = the engine merged and the run finished; a string = why it did not.
4289
+ const auto = decision.ok ? await this.autoMerge(pr, head, view, ship, decision, config) : undefined;
4290
+ if (auto === true)
4291
+ return;
4059
4292
  const cmd = decision.command.join(' ');
4060
4293
  this.mergeCmd = decision.ok ? cmd : undefined;
4061
4294
  this.commentOnce('pr', `merge@${head.slice(0, 12)}`, 'merge', `${mergeComment(this.key, decision, this.resume)}${decision.ok ? this.humanComment ?? '' : ''}`);
4062
4295
  if (decision.ok)
4063
- this.gate('merge', `merge is a human step; review approved and gates green at ${head.slice(0, 12)}${decision.noChecks ? ` (${NO_CI_CHECKS_NOTE}: no CI ran on this head, check the change yourself)` : ''}${this.humanNote ?? ''}: run ${cmd}, then ${this.resume}`);
4296
+ this.gate('merge', `merge is a human step; review approved and gates green at ${head.slice(0, 12)}${decision.noChecks ? ` (${NO_CI_CHECKS_NOTE}: no CI ran on this head, check the change yourself)` : ''}${this.humanNote ?? ''}${auto ? `; auto-merge (factory.merge.auto) not taken: ${auto}` : ''}: run ${cmd}, then ${this.resume}`);
4064
4297
  else
4065
4298
  this.gate('merge-refused', `ship's merge rule refuses ${head.slice(0, 12)}: ${decision.reasons.join('; ')}`);
4066
4299
  }
4067
- /** The human merged the PR: ship and factory record it; the run is done. */
4068
- finishMerged(pr) {
4300
+ /** The human merged the PR (or the opt-in auto-merge did, `by` and the base it moved to): ship and factory record it; the run is done. */
4301
+ finishMerged(pr, by = 'a human', mergedBase) {
4069
4302
  // The local forge's MERGED is a PR store file the PR's code could write (its mergedHead too): it counts only when
4070
4303
  // your base (as the engine synced it in this invocation, else refs/heads/<base>) contains the head the engine pushed.
4071
4304
  if (this.forge?.kind === 'local') {
4072
4305
  const head = this.state.head ?? '';
4073
- const base = this.basePushSha ?? this.exec('git', ['rev-parse', '--verify', `refs/heads/${this.state.base}`], { cwd: this.o.root, env: TRUSTED_READ_ENV }).stdout.trim();
4306
+ const base = mergedBase ?? this.basePushSha ?? this.exec('git', ['rev-parse', '--verify', `refs/heads/${this.state.base}`], { cwd: this.o.root, env: TRUSTED_READ_ENV }).stdout.trim();
4074
4307
  if (!HEX40.test(base) || !this.isAncestor(head, base)) {
4075
4308
  this.gate('lane-tampered', `the local forge reports PR #${pr} merged, but your ${this.state.base} ${base.slice(0, 12) || '(unreadable)'} does not contain the head the engine pushed ${head.slice(0, 12) || '(none)'}; something else wrote the PR store. Check what did (a prepare check or gate is the PR's own code), then rerun ${this.resume}`);
4076
4309
  return;
@@ -4079,11 +4312,309 @@ class FactoryEngine {
4079
4312
  this.writeShip(pr, (cur) => {
4080
4313
  if (!cur)
4081
4314
  throw new FactoryStepError(`no ship state for PR #${pr}`);
4082
- return canTransition(cur.phase, 'merged') ? transition(cur, 'merged', `merged on ${this.forgeName} by a human`, this.iso()) : cur;
4315
+ return canTransition(cur.phase, 'merged') ? transition(cur, 'merged', `merged on ${this.forgeName} by ${by}`, this.iso()) : cur;
4083
4316
  });
4084
- this.save((x) => moveTo(x, 'merged', `PR #${pr} merged on ${this.forgeName}`, this.iso()));
4317
+ this.save((x) => moveTo(x, 'merged', `PR #${pr} merged on ${this.forgeName}${by === 'a human' ? '' : ` by ${by}`}`, this.iso()));
4085
4318
  this.progress.emit('merged', 'done', `PR #${pr} merged`, this.fields());
4086
4319
  }
4320
+ /**
4321
+ * Opt-in auto-merge (auto-merge.ts), after ship's merge rule allowed the
4322
+ * head: undefined when factory.merge.auto is off for this repository, a
4323
+ * short reason when a condition fails or the merge did not go through (the
4324
+ * human park follows, unchanged), true when the engine merged and finished
4325
+ * the run. Every input is read here by the engine (trusted), on the exact
4326
+ * head: the user config, the diff's modes and line counts, the labels, the
4327
+ * human review read of this merge step. The PR is read again right before
4328
+ * the merge, which is pinned to the head (GitHub REST `sha`; the local
4329
+ * forge merges only a head that already contains your clean, checked-out base).
4330
+ */
4331
+ async autoMerge(pr, head, view, ship, decision, config) {
4332
+ const local = this.forge?.kind === 'local';
4333
+ let user = this.o.autoMergeUserConfig;
4334
+ if (user === undefined) {
4335
+ try {
4336
+ user = userConfigLayers().trustedUser;
4337
+ }
4338
+ catch {
4339
+ user = null;
4340
+ }
4341
+ }
4342
+ const commit = config.trustedBaseCommit;
4343
+ if (commit && !this.warnedCommittedMerge) {
4344
+ try {
4345
+ const text = readBaseFile(this.exec, this.o.root, commit, BASE_CONFIG_PATH);
4346
+ if (text && text.trim() && committedMergeConfig(parseJsonc(text))) {
4347
+ this.warnedCommittedMerge = true;
4348
+ this.o.warn?.(`omg factory run: factory.merge in the committed ${BASE_CONFIG_PATH} is ignored: auto-merge is set in your user config only (factory.merge.auto), because a PR can change committed config`);
4349
+ }
4350
+ }
4351
+ catch { /* an unreadable committed config sets nothing */ }
4352
+ }
4353
+ const resolved = resolveAutoMergeConfig(user, { url: this.state.repoUrl || undefined, root: this.o.root, local });
4354
+ if (resolved.error) {
4355
+ this.o.warn?.(`omg factory run: ${resolved.error}; auto-merge stays off`);
4356
+ return undefined;
4357
+ }
4358
+ if (!resolved.config)
4359
+ return undefined;
4360
+ // Labels: the issue's and (GitHub) the PR's; unreadable = null, which keeps the merge human.
4361
+ let labels;
4362
+ try {
4363
+ const issue = this.state.kind === 'ci-heal' || !this.o.issue ? [] : (this.forge ? this.forge.tracker.viewItem(this.o.issue) : ghViewItem(this.exec, this.o.issue, this.o.root)).labels;
4364
+ const prLabels = this.forge ? [] : (JSON.parse(ghRun(this.exec, ['pr', 'view', String(pr), '--json', 'labels'], this.o.root)).labels ?? []).map((l) => String(l.name));
4365
+ labels = [...issue, ...prLabels];
4366
+ }
4367
+ catch {
4368
+ labels = null;
4369
+ }
4370
+ const diff = (flag) => this.exec('git', ['diff', '--no-ext-diff', '--no-textconv', flag, '-z', '--no-renames', '--no-abbrev', `${view.baseRefOid}...${head}`], { cwd: this.o.root, env: TRUSTED_READ_ENV });
4371
+ const raw = diff('--raw');
4372
+ const num = diff('--numstat');
4373
+ const entries = raw.status === 0 && num.status === 0 ? parseChangedEntries(raw.stdout, num.stdout) : null;
4374
+ const extra = [config.knownFlakyFile];
4375
+ let protectedProblem;
4376
+ extra.push(...configuredProtectedPaths(this.o.root, (source, error) => { protectedProblem = `${source}: ${error}`; }));
4377
+ // Your core.hooksPath (repository, global or system config; the engine's own command-line pin is skipped): a PR never changes the hooks you run.
4378
+ const hooks = this.exec('git', ['config', '--show-scope', '--get-all', 'core.hooksPath'], { cwd: this.o.root, env: TRUSTED_READ_ENV });
4379
+ if (hooks.status > 1)
4380
+ protectedProblem ??= `git config core.hooksPath could not be read (exit ${hooks.status})`;
4381
+ else {
4382
+ for (const line of hooks.stdout.split('\n')) {
4383
+ const [scope, ...rest] = line.split('\t');
4384
+ const value = rest.join('\t').trim();
4385
+ if (!value || scope === 'command')
4386
+ continue;
4387
+ // Normalised first: `scripts/../h2` is h2 (review-498b INFO). `.` (the root) is covered by deniedPaths' root hook names (review-498c L-e).
4388
+ const rel = posix.normalize((isAbsolute(value) ? relative(this.o.root, value) : value).replace(/\\/g, '/'));
4389
+ if (rel && rel !== '.' && !rel.startsWith('..') && !isAbsolute(rel))
4390
+ extra.push(`${rel.replace(/\/+$/, '')}/`);
4391
+ }
4392
+ }
4393
+ const tiers = resolved.config.tiers;
4394
+ const testSetup = tiers.some((t) => t !== 'docs') ? this.baseTestSetup(view.baseRefOid) : undefined;
4395
+ const frontmatter = tiers.some((t) => t !== 'tests') && entries ? this.frontmatterPaths(entries, view.baseRefOid, head) : undefined;
4396
+ let installFiles;
4397
+ // The base's root names (binding.gyp, pnpm-workspace.yaml make install run code the engine does not read: review-498c L-b).
4398
+ const rootList = this.exec('git', ['ls-tree', '-z', '--name-only', view.baseRefOid], { cwd: this.o.root, env: TRUSTED_READ_ENV });
4399
+ try {
4400
+ if (rootList.status !== 0)
4401
+ throw new Error(`the base's root files could not be listed (exit ${rootList.status})`);
4402
+ installFiles = baseInstallFiles(readBaseFile(this.exec, this.o.root, view.baseRefOid, 'package.json'), rootList.stdout.split('\0').filter(Boolean));
4403
+ }
4404
+ catch (error) {
4405
+ // Unreadable: nothing extra is denied, so the small tier is off; docs and tests cannot touch a script anyway.
4406
+ installFiles = { paths: [], problem: `the base package.json could not be read (${oneLine(error instanceof Error ? error.message : String(error), 120)})` };
4407
+ }
4408
+ let patch;
4409
+ if (tiers.some((t) => t !== 'docs')) {
4410
+ const diffText = this.exec('git', ['diff', '--no-ext-diff', '--no-textconv', `${view.baseRefOid}...${head}`], { cwd: this.o.root, env: TRUSTED_READ_ENV });
4411
+ patch = diffText.status === 0 ? patchLines(diffText.stdout) : null;
4412
+ }
4413
+ const changes = protectedProblem ? { reasons: [`the configured protected paths could not be read (${protectedProblem})`], evidence: [] } : classifyChanges(entries, resolved.config, {
4414
+ extraDenied: extra, installFiles, ...(testSetup ? { testSetup } : {}), ...(frontmatter ? { frontmatter } : {}), ...(patch !== undefined ? { patch } : {}),
4415
+ });
4416
+ const pending = this.state.pendingCommit;
4417
+ const verdict = autoMergeVerdict({
4418
+ head,
4419
+ config: resolved.config,
4420
+ run: {
4421
+ ciHeal: this.state.kind === 'ci-heal',
4422
+ forgeKind: this.forge?.kind ?? 'github',
4423
+ history: this.state.history,
4424
+ ...(this.state.unsandboxedAck ? { unsandboxedAck: this.state.unsandboxedAck } : {}),
4425
+ ...(this.state.unsandboxedGatesAck ? { unsandboxedGatesAck: this.state.unsandboxedGatesAck } : {}),
4426
+ ...(this.state.gateChangeApproved ? { gateChangeApproved: this.state.gateChangeApproved } : {}),
4427
+ ...(pending?.secretAck ? { secretAck: pending.secretAck } : {}),
4428
+ },
4429
+ decision,
4430
+ requiredChecks: config.requiredChecks,
4431
+ ...(latestVerdict(ship) ? { verdict: latestVerdict(ship) } : {}),
4432
+ ...(this.humanClear?.head === head ? { human: { commentOnly: this.humanClear.commentOnly } } : {}),
4433
+ labels,
4434
+ changes,
4435
+ });
4436
+ const short = (reasons) => `${reasons.slice(0, 3).join('; ')}${reasons.length > 3 ? `; and ${reasons.length - 3} more` : ''}`;
4437
+ if (!verdict.ok || !verdict.tier)
4438
+ return short(verdict.reasons);
4439
+ // TOCTOU: read the PR again right before the merge; any move keeps the merge human.
4440
+ const again = await this.prViewReady(pr);
4441
+ if (again.state !== 'OPEN' || again.isDraft || again.headRefOid !== head || again.baseRefOid !== view.baseRefOid || again.baseRefName !== view.baseRefName) {
4442
+ return `the PR changed between the check and the merge (now ${again.state.toLowerCase()}, head ${String(again.headRefOid).slice(0, 12)}, base ${String(again.baseRefOid).slice(0, 12)})`;
4443
+ }
4444
+ const added = (entries ?? []).filter((e) => e.status === 'A').map((e) => e.path);
4445
+ const merged = local ? this.localAutoMerge(head, view.baseRefOid, added) : this.githubAutoMerge(pr, head, view.baseRefOid);
4446
+ if (typeof merged === 'string')
4447
+ return merged;
4448
+ const by = `the factory (auto-merge tier ${verdict.tier})`;
4449
+ this.save((x) => ({ ...x, history: [...x.history, { at: this.iso(), from: x.phase, to: x.phase, note: `auto-merged by tier ${verdict.tier} at ${head.slice(0, 12)}: ${verdict.evidence.join('; ')}` }] }));
4450
+ this.commentOnce('pr', `auto-merge@${head.slice(0, 12)}`, 'merge', autoMergeComment(runLabel(this.key), verdict.tier, head, verdict.evidence, by));
4451
+ // GitHub pins only the head: a base that moved between the re-read and the PUT is merged into unchecked. Say so loudly.
4452
+ if (!local) {
4453
+ const moved = this.githubMergeBaseProblem(merged.mergeSha, view.baseRefOid);
4454
+ if (moved) {
4455
+ const text = `WARNING: auto-merge of ${head.slice(0, 12)}: ${moved}. The merged result was not checked by the gates; check ${this.state.base} now. Turn on "Require branches to be up to date before merging" in branch protection to prevent this.`;
4456
+ this.save((x) => ({ ...x, history: [...x.history, { at: this.iso(), from: x.phase, to: x.phase, note: text }] }));
4457
+ this.commentOnce('pr', `auto-merge-base@${head.slice(0, 12)}`, 'merge', `Factory run for ${runLabel(this.key)}: ${text}\n`);
4458
+ this.o.warn?.(`omg factory run: ${text}`);
4459
+ }
4460
+ }
4461
+ this.finishMerged(pr, by, merged.base);
4462
+ return true;
4463
+ }
4464
+ /**
4465
+ * GitHub: the head-pinned REST merge (GitHub refuses a moved head with 409), admitted by the guard for this step only.
4466
+ * The head must already contain `base`, the live tip (liveBase), as localAutoMerge requires (review-518 L2): a base that
4467
+ * moved after prepare would be merged with a tree the gates never checked. A tip missing from the object store = not contained.
4468
+ */
4469
+ githubAutoMerge(pr, head, base) {
4470
+ if (!this.isAncestor(base, head))
4471
+ return `${this.state.base} moved after prepare (head ${head.slice(0, 12)} does not contain ${this.state.base} ${base.slice(0, 12)}); rerun ${this.resume} to merge the new base`;
4472
+ const repo = this.githubReadContext()?.repo;
4473
+ const args = repo ? githubAutoMergeArgs({ repo, pr, head }) : undefined;
4474
+ if (!args)
4475
+ return 'the run\'s GitHub repository is not known, so there is no head-pinned merge to run';
4476
+ this.autoMergeStep = { pr, head };
4477
+ try {
4478
+ const res = this.exec('gh', args, { cwd: this.o.root });
4479
+ if (res.status !== 0)
4480
+ return `GitHub refused the head-pinned merge: ${oneLine(res.stderr || res.stdout, 200)}`;
4481
+ let out;
4482
+ try {
4483
+ out = JSON.parse(res.stdout);
4484
+ }
4485
+ catch {
4486
+ out = {};
4487
+ }
4488
+ if (out.merged !== true)
4489
+ return `GitHub did not confirm the merge: ${oneLine(res.stdout, 200)}`;
4490
+ return typeof out.sha === 'string' && HEX40.test(out.sha) ? { mergeSha: out.sha } : {};
4491
+ }
4492
+ finally {
4493
+ this.autoMergeStep = undefined;
4494
+ }
4495
+ }
4496
+ /** After the GitHub merge: why its merge commit's first parent is not the base the gates checked (undefined = it is). */
4497
+ githubMergeBaseProblem(mergeSha, baseSha) {
4498
+ const repo = this.githubReadContext()?.repo;
4499
+ const args = repo && mergeSha ? githubCommitReadArgs(repo, mergeSha) : undefined;
4500
+ if (!args)
4501
+ return `GitHub did not return the merge commit, so its first parent could not be checked against ${this.state.base} ${baseSha.slice(0, 12)}`;
4502
+ let parents;
4503
+ try {
4504
+ const res = this.exec('gh', args, { cwd: this.o.root });
4505
+ parents = res.status === 0 ? JSON.parse(res.stdout).parents : undefined;
4506
+ }
4507
+ catch {
4508
+ parents = undefined;
4509
+ }
4510
+ const first = Array.isArray(parents) ? parents[0]?.sha : undefined;
4511
+ if (typeof first !== 'string')
4512
+ return `the merge commit ${mergeSha.slice(0, 12)} could not be read, so its first parent could not be checked against ${this.state.base} ${baseSha.slice(0, 12)}`;
4513
+ return first === baseSha ? undefined : `GitHub merged into ${this.state.base} ${first.slice(0, 12)}, not ${baseSha.slice(0, 12)} the gates checked (the base moved before the merge)`;
4514
+ }
4515
+ /**
4516
+ * The Markdown-like changed files (isFrontmatterCandidate) whose BASE blob
4517
+ * (not added) or HEAD blob (not deleted) starts with frontmatter (review-498b
4518
+ * N1): a skill, command, agent or mission contract a tool parses. Read with
4519
+ * ship's exact `git show <sha>:<path>`; a read that fails (or a path that
4520
+ * shape refuses) or more than 200 such files is a problem, which keeps the
4521
+ * docs and small tiers off.
4522
+ */
4523
+ frontmatterPaths(entries, baseSha, head) {
4524
+ const candidates = entries.filter((e) => isFrontmatterCandidate(e.path));
4525
+ if (candidates.length > 200)
4526
+ return { paths: [], problem: `${candidates.length} Markdown-like files changed; the engine reads at most 200 for frontmatter` };
4527
+ const paths = [];
4528
+ for (const e of candidates) {
4529
+ const shas = [...(e.status !== 'A' ? [baseSha] : []), ...(e.status !== 'D' ? [head] : [])];
4530
+ for (const sha of shas) {
4531
+ let text;
4532
+ try {
4533
+ text = readBaseFile(this.exec, this.o.root, sha, e.path);
4534
+ }
4535
+ catch (error) {
4536
+ return { paths, problem: `${e.path} could not be read at ${sha.slice(0, 12)} to check for frontmatter (${oneLine(error instanceof Error ? error.message : String(error), 120)})` };
4537
+ }
4538
+ if (text !== null && hasFrontmatter(text)) {
4539
+ paths.push(e.path);
4540
+ break;
4541
+ }
4542
+ }
4543
+ }
4544
+ return { paths };
4545
+ }
4546
+ /**
4547
+ * The setup files of the BASE commit's root test configs (baseTestSetup),
4548
+ * never the head's: the PR cannot hide its own setup file. A listing or
4549
+ * read that fails is a problem, which keeps the tests and small tiers off.
4550
+ */
4551
+ baseTestSetup(baseSha) {
4552
+ const list = this.exec('git', ['ls-tree', '-z', '--name-only', baseSha], { cwd: this.o.root, env: TRUSTED_READ_ENV });
4553
+ if (list.status !== 0)
4554
+ return { paths: [], problem: `the base's root files could not be listed (exit ${list.status})` };
4555
+ const files = [];
4556
+ for (const name of list.stdout.split('\0').filter((n) => TEST_CONFIG_NAME.test(n))) {
4557
+ try {
4558
+ const text = readBaseFile(this.exec, this.o.root, baseSha, name);
4559
+ if (text !== null)
4560
+ files.push({ path: name, text });
4561
+ }
4562
+ catch (error) {
4563
+ return { paths: [], problem: `the base test config ${name} could not be read (${oneLine(error instanceof Error ? error.message : String(error), 120)})` };
4564
+ }
4565
+ }
4566
+ return baseTestSetupOf(files);
4567
+ }
4568
+ /**
4569
+ * The local forge: `git merge --no-ff --no-edit --no-verify <head>` in your
4570
+ * repository, only with your base checked out there, no tracked change, the
4571
+ * base still at the commit the run synced, and the head already containing
4572
+ * it (so the merge takes the head's tree as is: no merge driver runs), and
4573
+ * no path the PR adds already in your checkout. Like every engine git
4574
+ * command it runs under hardenedGitExec: core.hooksPath is the engine's
4575
+ * empty dir (no post-merge from .git/hooks or a tracked hooks dir) and
4576
+ * merge.renormalize is off. A failed merge is aborted. Returns the base's new commit.
4577
+ */
4578
+ localAutoMerge(head, baseSha, added) {
4579
+ const git = (args) => this.exec('git', args, { cwd: this.o.root, env: TRUSTED_READ_ENV });
4580
+ // git overwrites an ignored or untracked file in the way without asking: a path the PR adds must not exist in your checkout yet.
4581
+ // review-498b L1: every parent too: an ignored FILE `a` (or a link) where the PR adds `a/b.md` is replaced by git.
4582
+ const inTheWay = added.filter((p) => {
4583
+ const parts = p.split('/');
4584
+ return parts.some((_, n) => {
4585
+ try {
4586
+ const st = lstatSync(join(this.o.root, ...parts.slice(0, n + 1)));
4587
+ return n === parts.length - 1 || !st.isDirectory();
4588
+ }
4589
+ catch {
4590
+ return false;
4591
+ }
4592
+ });
4593
+ });
4594
+ if (inTheWay.length > 0)
4595
+ return `the PR adds ${inTheWay.slice(0, 3).join(', ')}${inTheWay.length > 3 ? ` and ${inTheWay.length - 3} more` : ''}, which already exist in your checkout, or under a file or link there (an ignored or untracked file the merge would overwrite)`;
4596
+ const branch = git(['rev-parse', '--symbolic-full-name', 'HEAD']);
4597
+ if (branch.status !== 0 || branch.stdout.trim() !== `refs/heads/${this.state.base}`)
4598
+ return `your repository does not have ${this.state.base} checked out (the local merge runs there)`;
4599
+ const dirty = git(['status', '--porcelain', '--untracked-files=no']);
4600
+ if (dirty.status !== 0 || dirty.stdout.trim() !== '')
4601
+ return `your repository has uncommitted changes to tracked files`;
4602
+ const at = git(['rev-parse', '--verify', `refs/heads/${this.state.base}`]).stdout.trim();
4603
+ if (at !== baseSha)
4604
+ return `your ${this.state.base} is at ${at.slice(0, 12) || '(unreadable)'}, not ${baseSha.slice(0, 12)} the gates checked against`;
4605
+ if (git(['merge-base', '--is-ancestor', baseSha, head]).status !== 0)
4606
+ return `head ${head.slice(0, 12)} does not contain ${this.state.base} ${baseSha.slice(0, 12)}; a merge would combine trees the gates never checked`;
4607
+ const res = git(['merge', '--no-ff', '--no-edit', '--no-verify', head]);
4608
+ if (res.status !== 0) {
4609
+ if (git(['rev-parse', '-q', '--verify', 'MERGE_HEAD']).status === 0)
4610
+ git(['merge', '--abort']);
4611
+ return `git merge of ${head.slice(0, 12)} failed: ${oneLine(res.stderr || res.stdout, 200)}`;
4612
+ }
4613
+ const after = git(['rev-parse', '--verify', `refs/heads/${this.state.base}`]).stdout.trim();
4614
+ if (!HEX40.test(after) || git(['merge-base', '--is-ancestor', head, after]).status !== 0)
4615
+ return `after the merge your ${this.state.base} does not contain ${head.slice(0, 12)}; check your repository`;
4616
+ return { base: after };
4617
+ }
4087
4618
  // --- Shared git state around lanes -------------------------------------------------------------
4088
4619
  /**
4089
4620
  * A remote-tracking ref of the run's remote at exactly the sha that remote
@@ -4890,6 +5421,8 @@ class FactoryEngine {
4890
5421
  // merge then treat like any lane's. The agent's PR gets a link comment and is closed after publish (D5).
4891
5422
  /** The coding agent write context, set ONLY around the assign and around the agent PR's link comment and close; cleared in finally. */
4892
5423
  agentStep;
5424
+ /** Set only around the opt-in auto-merge's GitHub REST merge (the guard admits that one call for this PR and head). */
5425
+ autoMergeStep;
4893
5426
  /** Whether this invocation's run uses the coding agent, and its keys (resolved once; its warning printed once). */
4894
5427
  agentChoice;
4895
5428
  /** The repository-only GitHub read context (the coding agent's status read): the run's repository as intake recorded it. */
@@ -4897,13 +5430,16 @@ class FactoryEngine {
4897
5430
  * The gates' GitHub reads (GateHeadReads) on a GitHub run, through the run
4898
5431
  * guard's exact shapes on the run's repository: the base commit's checks
4899
5432
  * (read once per base sha), the head's check suites and check-run apps.
4900
- * None on the local forge and Azure DevOps.
5433
+ * None on the local forge and Azure DevOps. The base is the PR's RECORDED
5434
+ * baseRefOid (review-518 L1), not liveBase's tip: a tip that just landed
5435
+ * has no settled CI yet, so "the base reported no check" and "this app is
5436
+ * idle on the base" would hold for it while its runs are still queued.
4901
5437
  */
4902
5438
  gateReads(view) {
4903
5439
  const repo = this.githubReadContext()?.repo;
4904
5440
  if (!repo || this.forge?.kind === 'local' || this.forge?.kind === 'azure-devops')
4905
5441
  return undefined;
4906
- const base = view.baseRefOid;
5442
+ const base = view.recordedBaseRefOid ?? view.baseRefOid;
4907
5443
  let baseChecks;
4908
5444
  let ciDefinitions;
4909
5445
  let baseSuites;
@@ -4944,7 +5480,7 @@ class FactoryEngine {
4944
5480
  }
4945
5481
  githubReadContext() {
4946
5482
  const repo = this.state?.repoUrl ? codingAgentRepoOf(this.state.repoUrl) : undefined;
4947
- return repo ? { repo: ghRepoArg(repo) } : undefined;
5483
+ return repo ? { repo: ghRepoArg(repo), ...(this.autoMergeStep ? { autoMerge: this.autoMergeStep } : {}) } : undefined;
4948
5484
  }
4949
5485
  withAgentStep(ctx, call) {
4950
5486
  this.agentStep = ctx;
@@ -5392,6 +5928,8 @@ class FactoryEngine {
5392
5928
  humanNote;
5393
5929
  /** The same read for the merge comment on the PR. */
5394
5930
  humanComment;
5931
+ /** The same read as auto-merge needs it: clean at this head, and its comment-only reviews (undefined = not read). */
5932
+ humanClear;
5395
5933
  /** factory.review.human from the trusted layers; absent (no forge config included) = "fix". */
5396
5934
  humanMode() {
5397
5935
  return this.o.forge?.config.review?.human ?? 'fix';
@@ -5498,6 +6036,7 @@ class FactoryEngine {
5498
6036
  humanReviewParked(pr, head, ship) {
5499
6037
  this.humanNote = undefined;
5500
6038
  this.humanComment = undefined;
6039
+ this.humanClear = undefined;
5501
6040
  const mode = this.humanMode();
5502
6041
  if (mode === 'off')
5503
6042
  return false;
@@ -5573,6 +6112,7 @@ class FactoryEngine {
5573
6112
  const read = `${none}${approved.length > 0 ? `, approved at this head by ${this.names(approved)}` : ''}${commented}${also}${ignored}${gone}${sandbox}`;
5574
6113
  this.humanNote = `; human review: ${read}; ${rerun}`;
5575
6114
  this.humanComment = `\nHuman review at this head: ${read}.\n\nIf the PR gets new review comments before you merge, rerun \`${this.resume}\` first.\n`;
6115
+ this.humanClear = { head, commentOnly: commentOnly.length };
5576
6116
  return false;
5577
6117
  }
5578
6118
  /**
@@ -5688,6 +6228,8 @@ export const GATE_SANDBOX_INCOMPATIBLE_GATE = 'gate-sandbox-incompatible';
5688
6228
  * contradiction, no attestation, a timeout with no answer): never a pass or a FAILURE, and no --allow-unsandboxed-gates.
5689
6229
  */
5690
6230
  export const GATE_NO_VERDICT_GATE = 'gate-no-verdict';
6231
+ /** How withGitView's own no-verdict reason starts: gateNoVerdictReason gives it its own sentence (nothing ran). */
6232
+ const GIT_VIEW_UNBUILT = 'the git view of ';
5691
6233
  /** What the gate-sandbox-incompatible park says about "ack": never a fix for a PR nobody reviewed. */
5692
6234
  const ACK_WARNING = 'Do not switch factory.run.sandbox.gates to "ack" for a PR whose whole diff you have not reviewed: "ack" runs its code as you, with your credentials';
5693
6235
  /** How long one prepare check may run (the sandbox needs a bound; ship's own prepare has none). */