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,1076 @@
1
+ /**
2
+ * factory.run.sandbox.isolation "container": the PR's own code in prepare's
3
+ * checks, the local gate and their base calibrations runs in a local
4
+ * container (docker or podman) instead of the Copilot OS sandbox, which on
5
+ * Windows cannot deny paths under the user profile. Opt-in, user config
6
+ * only (copilot-run/sandbox.ts resolveGateIsolation).
7
+ *
8
+ * One command is a few containers on one named volume
9
+ * (`omg-gate-<run>-<id>`, label `omg.run=<run>`), every one `--rm`, named
10
+ * `omg-gate-<run>-<id>[-step]`, with `--cap-drop ALL`, `no-new-privileges`,
11
+ * `--pids-limit`, `--memory`, `--cpus`, `--init`, `--pull never`, and its
12
+ * argv under `timeout -s KILL` (the container ends itself even when the
13
+ * runtime's kill does not get through):
14
+ *
15
+ * 0. scan (host, before any container): the checkout may hold no link that
16
+ * resolves outside it (or not at all) and no file with more than one
17
+ * hard link, outside the exact `.git` and `node_modules` names the copy
18
+ * leaves out. So the read-only bind below never presents anything from
19
+ * outside the checkout, however the runtime's file sharing treats links.
20
+ * 1. copy: the checkout, bind-mounted READ-ONLY at /in, is copied with tar
21
+ * into the volume (`.git` and every `node_modules` left out; links stay
22
+ * links), then the engine's one-commit git view (git-view.ts), bound
23
+ * read-only at /in-git, as the copy's `.git`. No network, no PR code
24
+ * runs. The only step with host paths.
25
+ * 2. install (a package.json with a package-lock.json): only npm itself
26
+ * gets network, never the PR's code:
27
+ * a. `npm ci --ignore-scripts` on a per-command bridge network
28
+ * (`omg-gate-<run>-<id>-net`, labelled, inter-container traffic off),
29
+ * no credential: no user profile, no env but the fixed allowlist, no
30
+ * GH_TOKEN, no ssh agent, no runtime socket; read-only root fs,
31
+ * non-root user. The checkout's `.npmrc` is held aside (the copy step
32
+ * moves it, 2b puts it back first) and npm's registry, proxy and TLS
33
+ * settings are forced by env (NPM_FETCH_ENV). The npm cache is a volume per lockfile hash
34
+ * (`omg-gate-cache-<hash>`) only when every locked package comes from
35
+ * the npm registry with an `integrity`; a lockfile with an entry
36
+ * without one uses a fresh cache inside the command's own volume, and
37
+ * one resolved from anywhere else (git, a tarball URL, a file) is
38
+ * unavailable. No code of the PR runs while the shared cache is
39
+ * mounted, so it holds only what npm verified.
40
+ * b. the install scripts (`npm rebuild`, then the root's lifecycle
41
+ * scripts in npm ci's order) with `--network none` and no cache.
42
+ * Node modules themselves are never shared between commands.
43
+ * 3. run: the command with `--network none`, same hardening, in /work/src.
44
+ * Its merged output keeps only a bounded tail; exit codes map as the OS
45
+ * sandbox's: 0 pass, other failure, a timeout kills only this container
46
+ * (status 124, timedOut). The runtime's own error (125) or a signal is
47
+ * no verdict, never a pass. While 2 and 3 run, a watchdog measures the
48
+ * work volume (`du`, from a separate read-only container) and kills the
49
+ * step's container when it holds more than container.diskLimit.
50
+ * 4. copy back (a prepare check that passed): the volume's tree comes back
51
+ * as a tar stream and only regular files are written into the checkout,
52
+ * after every path was checked (applyCopyBack); one problem and nothing
53
+ * is written (no verdict).
54
+ *
55
+ * The step containers, the network and the volume are removed after the
56
+ * command; `omg factory run clean` removes what a killed engine left (by
57
+ * this run's label and name prefix only). A missing runtime, daemon or
58
+ * image, or a project the container cannot install, is `unavailable`: the
59
+ * engine parks at gate-container-unavailable naming the fix, never falls
60
+ * back to the weaker sandbox. Image pulls are announced before they start.
61
+ */
62
+ import { spawn, spawnSync } from 'node:child_process';
63
+ import { createHash, randomBytes } from 'node:crypto';
64
+ import { chmodSync, lstatSync, mkdirSync, readdirSync, readFileSync, readlinkSync, realpathSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
65
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
66
+ import { redactGateOutput, SANDBOX_OUTPUT_TAIL_CHARS } from './sandbox-exec.js';
67
+ import { runSlug } from './state.js';
68
+ /** The park when the container runtime, its daemon or the image is not there, or the project cannot be installed in it. */
69
+ export const GATE_CONTAINER_UNAVAILABLE_GATE = 'gate-container-unavailable';
70
+ /** What the gate-sandbox-incompatible park of a base calibration in the container tells the human to do. */
71
+ export const CONTAINER_INCOMPATIBLE_ADVICE = 'Your gate fails in the gate container on the base: there it runs with no network, a git repository of only the checked commit (git itself must be in the image), as a non-root user on a read-only root (only /tmp, the checkout and HOME writable), with the dependencies npm ci installs from your lockfile and their install scripts run without network. Make the gate work there (or pick another factory.run.sandbox.container.image), or set factory.run.sandbox.isolation "copilot" in your user config';
72
+ /** Prefix of every container, network and volume this module makes; nothing else is ever removed. */
73
+ export const CONTAINER_NAME_PREFIX = 'omg-gate-';
74
+ export const RUN_LABEL = 'omg.run';
75
+ const GATE_LABEL = 'omg.gate';
76
+ const CACHE_LABEL = 'omg.cache';
77
+ /** The fixed environment of the install and run containers: nothing of the engine's env passes. */
78
+ export const CONTAINER_PATH = '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin';
79
+ const CONTAINER_USER = '1000:1000';
80
+ const WORK = '/work';
81
+ const SRC = `${WORK}/src`;
82
+ /** The only registry the install talks to (the checkout's .npmrc is held aside), and the hosts a locked package may come from. */
83
+ const NPM_REGISTRY = 'https://registry.npmjs.org/';
84
+ const REGISTRY_PREFIXES = [NPM_REGISTRY, 'https://registry.yarnpkg.com/'];
85
+ const PROBE_TIMEOUT_MS = 20_000;
86
+ const PULL_TIMEOUT_MS = 15 * 60_000;
87
+ const COPY_TIMEOUT_MS = 10 * 60_000;
88
+ const KILL_TIMEOUT_MS = 30_000;
89
+ /** The in-container `timeout -s KILL` fires this long after the engine's own timer (which kills by name first). */
90
+ const IN_CONTAINER_GRACE_S = 30;
91
+ /** How often the disk watchdog measures the work volume. */
92
+ const DISK_WATCH_MS = 10_000;
93
+ /** The combined output tail kept of any runtime call. */
94
+ const OUTPUT_TAIL_BYTES = 64 * 1024;
95
+ /** Copy back: the largest tar stream, and the most entries, read from the volume. */
96
+ export const COPY_BACK_MAX_BYTES = 256 * 1024 * 1024;
97
+ export const COPY_BACK_MAX_ENTRIES = 100_000;
98
+ /** The scan before the copy: the most entries it walks. */
99
+ const SCAN_MAX_ENTRIES = 200_000;
100
+ const LOCKFILE_MAX_BYTES = 64 * 1024 * 1024;
101
+ export const defaultContainerExec = (bin, args, o) => new Promise((done) => {
102
+ let tail = Buffer.alloc(0);
103
+ const out = [];
104
+ let outBytes = 0;
105
+ let overflow = false;
106
+ let timedOut = false;
107
+ let settled = false;
108
+ const keep = (chunk) => {
109
+ tail = Buffer.concat([tail, chunk]);
110
+ if (tail.length > OUTPUT_TAIL_BYTES)
111
+ tail = tail.subarray(tail.length - OUTPUT_TAIL_BYTES);
112
+ };
113
+ const finish = (r) => {
114
+ if (settled)
115
+ return;
116
+ settled = true;
117
+ clearTimeout(timer);
118
+ clearTimeout(hardKill);
119
+ done({ ...r, tail: tail.toString('utf8'), overflow, timedOut, ...(o.full !== undefined && !overflow ? { stdout: Buffer.concat(out) } : {}) });
120
+ };
121
+ let hardKill;
122
+ let child;
123
+ try {
124
+ child = spawn(bin, [...args], { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true, shell: false });
125
+ }
126
+ catch (error) {
127
+ done({ status: null, tail: '', overflow: false, timedOut: false, spawnError: error instanceof Error ? error.message : String(error) });
128
+ return;
129
+ }
130
+ const timer = setTimeout(() => {
131
+ timedOut = true;
132
+ void Promise.resolve(o.onTimeout?.()).catch(() => undefined).finally(() => {
133
+ hardKill = setTimeout(() => { try {
134
+ child.kill('SIGKILL');
135
+ }
136
+ catch { /* gone */ } }, 10_000);
137
+ });
138
+ }, o.timeoutMs);
139
+ child.stdout.on('data', (chunk) => {
140
+ if (o.full !== undefined) {
141
+ if (!overflow && outBytes + chunk.length <= o.full) {
142
+ out.push(chunk);
143
+ outBytes += chunk.length;
144
+ }
145
+ else {
146
+ overflow = true;
147
+ out.length = 0;
148
+ }
149
+ }
150
+ else
151
+ keep(chunk);
152
+ });
153
+ child.stderr.on('data', (chunk) => keep(chunk));
154
+ child.on('error', (error) => finish({ status: null, spawnError: error.message }));
155
+ child.on('close', (code) => finish({ status: code }));
156
+ });
157
+ export const defaultContainerExecSync = (bin, args) => {
158
+ const r = spawnSync(bin, [...args], { encoding: 'utf8', windowsHide: true, shell: false, timeout: 60_000 });
159
+ return { status: r.error ? null : r.status, stdout: r.stdout ?? '' };
160
+ };
161
+ /** The label value (and name part) of a run: a hash of the checkout path, then the run's slug, `[a-z0-9-]` only. */
162
+ export function containerRunLabel(root, key) {
163
+ const repo = createHash('sha256').update(resolve(root)).digest('hex').slice(0, 10);
164
+ return `${repo}-${runSlug(key).toLowerCase().replace(/[^a-z0-9-]/g, '-').slice(0, 40)}`;
165
+ }
166
+ /** One `--mount` value: CSV fields, each quoted when it holds a comma or a quote (the runtime parses it as CSV). */
167
+ export function mountArg(fields) {
168
+ return fields.map((f) => (/[",\n\r]/.test(f) ? `"${f.replace(/"/g, '""')}"` : f)).join(',');
169
+ }
170
+ /** The options every container of a gate gets. */
171
+ export function hardeningArgs(s) {
172
+ return [
173
+ '--rm', '--init', '--pull', 'never',
174
+ // No container log on the runtime's disk, outside the watched volume (review-499b N1): output comes through the attached CLI only.
175
+ '--log-driver', 'none',
176
+ '--cap-drop', 'ALL', '--security-opt', 'no-new-privileges',
177
+ '--pids-limit', String(s.pidsLimit), '--memory', s.memory, '--cpus', String(s.cpus),
178
+ ];
179
+ }
180
+ /** `-e K=V` for the fixed allowlist; nothing of the engine's own env. */
181
+ export function containerEnvArgs(extra = {}) {
182
+ const env = {
183
+ PATH: CONTAINER_PATH,
184
+ HOME: `${WORK}/home`,
185
+ CI: '1',
186
+ npm_config_update_notifier: 'false',
187
+ npm_config_fund: 'false',
188
+ npm_config_audit: 'false',
189
+ ...extra,
190
+ };
191
+ return Object.entries(env).flatMap(([k, v]) => ['-e', `${k}=${v}`]);
192
+ }
193
+ /** `argv` under coreutils `timeout -s KILL`: the container ends itself `IN_CONTAINER_GRACE_S` after the engine's timer. */
194
+ export function inContainerLimit(timeoutMs, argv) {
195
+ return ['timeout', '-s', 'KILL', `${Math.ceil(timeoutMs / 1000) + IN_CONTAINER_GRACE_S}s`, ...argv];
196
+ }
197
+ /** A size as container.diskLimit gives it ("10g", "800m") in bytes. */
198
+ export function sizeBytes(size) {
199
+ const m = /^(\d+)([mg])$/i.exec(size);
200
+ if (!m)
201
+ throw new Error(`not a size: ${size}`);
202
+ return Number(m[1]) * (m[2].toLowerCase() === 'g' ? 1024 ** 3 : 1024 ** 2);
203
+ }
204
+ /**
205
+ * Whether the lockfile's packages may share the npm cache: every locked
206
+ * package from the npm registry with an `integrity` ('shared'); one without
207
+ * an integrity ('private': a fresh cache in the command's volume); one
208
+ * resolved from anywhere else (git, a tarball URL, a file) refuses (its
209
+ * fetch is not checked by an integrity and git is not in the image).
210
+ */
211
+ export function lockfileCachePolicy(lock) {
212
+ if (!lock || typeof lock !== 'object' || Array.isArray(lock))
213
+ return { refuse: 'the lockfile is not a JSON object' };
214
+ const outside = { refuse: 'the lockfile has a package that does not come from the npm registry (git, a tarball URL or a file); the gate container installs registry packages only' };
215
+ let integrity = true;
216
+ const check = (e, version) => {
217
+ if (typeof e.resolved === 'string' && !REGISTRY_PREFIXES.some((p) => e.resolved.startsWith(p)))
218
+ return false;
219
+ if (typeof version === 'string' && /^[a-z+]+:/i.test(version) && !version.startsWith('npm:'))
220
+ return false;
221
+ if (typeof e.integrity !== 'string' || e.integrity === '')
222
+ integrity = false;
223
+ return true;
224
+ };
225
+ const packages = lock.packages;
226
+ if (packages && typeof packages === 'object' && !Array.isArray(packages)) {
227
+ for (const [key, raw] of Object.entries(packages)) {
228
+ if (key === '' || !raw || typeof raw !== 'object')
229
+ continue;
230
+ const e = raw;
231
+ // A workspace's own folder, a workspace link, a bundled dependency: nothing is fetched for it.
232
+ if (!key.includes('node_modules/') || e.link === true || e.inBundle === true)
233
+ continue;
234
+ if (!check(e))
235
+ return outside;
236
+ }
237
+ return integrity ? 'shared' : 'private';
238
+ }
239
+ // lockfileVersion 1: nested `dependencies`.
240
+ const walk = (deps, depth) => {
241
+ if (!deps || typeof deps !== 'object' || depth > 64)
242
+ return true;
243
+ for (const raw of Object.values(deps)) {
244
+ if (!raw || typeof raw !== 'object')
245
+ continue;
246
+ const e = raw;
247
+ if (e.bundled === true)
248
+ continue;
249
+ if (!check(e, e.version) || !walk(e.dependencies, depth + 1))
250
+ return false;
251
+ }
252
+ return true;
253
+ };
254
+ if (!walk(lock.dependencies, 0))
255
+ return outside;
256
+ return integrity ? 'shared' : 'private';
257
+ }
258
+ /** What the checkout needs installed: read through lstat (a linked manifest or lockfile is not followed on the host). */
259
+ export function installPlan(checkout) {
260
+ const regular = (name) => {
261
+ try {
262
+ return lstatSync(join(checkout, name)).isFile();
263
+ }
264
+ catch {
265
+ return false;
266
+ }
267
+ };
268
+ if (!regular('package.json'))
269
+ return { kind: 'none' };
270
+ for (const lock of ['npm-shrinkwrap.json', 'package-lock.json']) {
271
+ if (!regular(lock))
272
+ continue;
273
+ const path = join(checkout, lock);
274
+ if (lstatSync(path).size > LOCKFILE_MAX_BYTES)
275
+ return { kind: 'unsupported', reason: `${lock} is larger than the gate container reads` };
276
+ const bytes = readFileSync(path);
277
+ let json;
278
+ try {
279
+ json = JSON.parse(bytes.toString('utf8'));
280
+ }
281
+ catch {
282
+ return { kind: 'unsupported', reason: `${lock} is not valid JSON` };
283
+ }
284
+ const policy = lockfileCachePolicy(json);
285
+ if (typeof policy === 'object')
286
+ return { kind: 'unsupported', reason: policy.refuse };
287
+ return { kind: 'npm-ci', lockHash: createHash('sha256').update(bytes).digest('hex').slice(0, 16), sharedCache: policy === 'shared' };
288
+ }
289
+ let pkg = {};
290
+ try {
291
+ pkg = JSON.parse(readFileSync(join(checkout, 'package.json'), 'utf8'));
292
+ }
293
+ catch { /* the container's npm reports it */ }
294
+ const deps = ['dependencies', 'devDependencies', 'optionalDependencies'].some((k) => {
295
+ const v = pkg?.[k];
296
+ return v && typeof v === 'object' && Object.keys(v).length > 0;
297
+ });
298
+ if (!deps)
299
+ return { kind: 'none' };
300
+ const other = ['pnpm-lock.yaml', 'yarn.lock', 'bun.lockb', 'bun.lock'].find(regular);
301
+ return { kind: 'unsupported', reason: other ? `the project uses ${other}; the gate container installs npm projects (package-lock.json or npm-shrinkwrap.json) only` : 'the project has dependencies but no package-lock.json; the gate container installs with npm ci only' };
302
+ }
303
+ const isNodeExe = (p) => /^node(?:\.exe)?$/i.test(basename(p));
304
+ /**
305
+ * The argv in the container: a node script (the built-in checks, the
306
+ * inventory generator, a calibration's adjusted args) as `node <args>`;
307
+ * any other command as configured, its `node` executable named plainly. A
308
+ * word that is a host path inside the checkout is mapped into /work/src.
309
+ */
310
+ export function containerArgv(req) {
311
+ const words = isNodeExe(req.exe) && req.args.length > 0 && !isAbsolute(req.args[0]) ? ['node', ...req.args] : [...req.argv];
312
+ const root = resolve(req.cwd);
313
+ return words.map((w, i) => {
314
+ if (i === 0 && isNodeExe(w))
315
+ return 'node';
316
+ if (!isAbsolute(w))
317
+ return w;
318
+ const rel = relative(root, resolve(w));
319
+ if (rel === '')
320
+ return SRC;
321
+ if (rel.startsWith('..') || isAbsolute(rel))
322
+ return w;
323
+ return `${SRC}/${rel.split(sep).join('/')}`;
324
+ });
325
+ }
326
+ /** Where the engine's git view (SandboxRunRequest.gitView) is bound read-only for the copy step. */
327
+ const GIT_VIEW_MOUNT = '/in-git';
328
+ /** The copy step's script (fixed text: no word of the checkout reaches it); with a git view it becomes `${SRC}/.git`. */
329
+ const copyLines = (gitView) => [
330
+ 'set -e',
331
+ `mkdir -p ${SRC} ${WORK}/home`,
332
+ // Through a file, not a pipe: sh has no pipefail, and a partial copy must fail the step (copy back removes what is missing).
333
+ `tar -C /in --exclude=.git --exclude=node_modules -cf ${WORK}/in.tar .`,
334
+ `tar -C ${SRC} -xf ${WORK}/in.tar`,
335
+ `rm -f ${WORK}/in.tar`,
336
+ ...(gitView ? [`mkdir ${SRC}/.git`, `tar -C ${GIT_VIEW_MOUNT} -cf ${WORK}/git.tar .`, `tar -C ${SRC}/.git -xf ${WORK}/git.tar`, `rm -f ${WORK}/git.tar`] : []),
337
+ `chown -R ${CONTAINER_USER} ${WORK}`,
338
+ 'if [ -d /cache ]; then mkdir -p /cache/npm; [ "$(stat -c %u /cache/npm)" = 1000 ] || chown -R 1000:1000 /cache; fi',
339
+ ];
340
+ /**
341
+ * The checkout's own `.npmrc` (scoped registries, proxies, strict-ssl) steers
342
+ * npm itself, so it is held outside the project while npm ci fetches and put
343
+ * back before any of the PR's code runs (review-499b N2). Fixed text.
344
+ */
345
+ const NPMRC_HELD = `${WORK}/npmrc.held`;
346
+ const HOLD_NPMRC = `if [ -e ${SRC}/.npmrc ] || [ -L ${SRC}/.npmrc ]; then mv ${SRC}/.npmrc ${NPMRC_HELD}; fi`;
347
+ const RESTORE_NPMRC = `if [ -e ${NPMRC_HELD} ] || [ -L ${NPMRC_HELD} ]; then rm -rf ${SRC}/.npmrc; mv ${NPMRC_HELD} ${SRC}/.npmrc; fi`;
348
+ /** The copy step's script for a plan: the npm ci plan also holds the checkout's .npmrc aside; a git view is copied in as `.git`. */
349
+ export function copyScript(npmCi, gitView = false) {
350
+ const copy = copyLines(gitView).join('; ');
351
+ return npmCi ? `${copy}; ${HOLD_NPMRC}` : copy;
352
+ }
353
+ /**
354
+ * npm's own settings in the fetch step, over anything npm would read (no
355
+ * .npmrc is in the project then; these beat the image's global one): the npm
356
+ * registry only, no proxy, TLS checked, and lockfile URLs fetched from it.
357
+ */
358
+ export const NPM_FETCH_ENV = {
359
+ npm_config_registry: NPM_REGISTRY,
360
+ npm_config_proxy: 'null',
361
+ npm_config_https_proxy: 'null',
362
+ npm_config_strict_ssl: 'true',
363
+ npm_config_replace_registry_host: 'npmjs',
364
+ };
365
+ /**
366
+ * The install scripts npm ci would have run, without network (fixed text):
367
+ * the dependencies' (npm rebuild), then the root's lifecycle scripts in npm
368
+ * ci's order, each alone (`--ignore-scripts` keeps npm run from adding the
369
+ * pre/post scripts a second time).
370
+ */
371
+ const SCRIPTS_SCRIPT = [
372
+ 'set -e',
373
+ RESTORE_NPMRC,
374
+ 'npm rebuild --foreground-scripts',
375
+ 'for s in preinstall install postinstall prepublish preprepare prepare postprepare; do npm run --if-present --ignore-scripts "$s"; done',
376
+ ].join('; ');
377
+ /**
378
+ * The scan before the copy (fixed-text problem, never a name: the names are
379
+ * the PR's): a link that resolves outside the checkout or not at all, or a
380
+ * file with more than one hard link, outside the exact `.git` and
381
+ * `node_modules` names tar leaves out. Null when the checkout may be bound.
382
+ */
383
+ export function checkoutCopyProblem(checkout) {
384
+ let root;
385
+ try {
386
+ root = realpathSync.native(checkout);
387
+ }
388
+ catch {
389
+ return 'the checkout could not be resolved';
390
+ }
391
+ let seen = 0;
392
+ const inside = (p) => samePathOrUnder(p, root);
393
+ const walk = (dir) => {
394
+ for (const name of readdirSync(dir)) {
395
+ if (name === '.git' || name === 'node_modules')
396
+ continue;
397
+ if (++seen > SCAN_MAX_ENTRIES)
398
+ return 'the checkout has more files than the gate container copies';
399
+ const path = join(dir, name);
400
+ const st = lstatSync(path);
401
+ if (st.isSymbolicLink()) {
402
+ const lexical = linkTargetProblem(readlinkSync(path), relative(root, dir).split(sep).filter(Boolean).length);
403
+ if (lexical)
404
+ return lexical;
405
+ let target;
406
+ try {
407
+ target = realpathSync.native(path);
408
+ }
409
+ catch {
410
+ return 'the checkout has a link whose target does not exist';
411
+ }
412
+ if (!inside(target))
413
+ return 'the checkout has a link (a symbolic link or junction) that points outside it';
414
+ continue;
415
+ }
416
+ if (st.isDirectory()) {
417
+ const p = walk(path);
418
+ if (p)
419
+ return p;
420
+ }
421
+ else if (st.isFile() && st.nlink > 1)
422
+ return 'the checkout has a file with more than one hard link';
423
+ }
424
+ return null;
425
+ };
426
+ try {
427
+ return walk(root);
428
+ }
429
+ catch {
430
+ return 'the checkout could not be listed';
431
+ }
432
+ }
433
+ /**
434
+ * A link target as the container's Linux kernel will follow it, checked
435
+ * without the host (review-499b N5): no absolute target (POSIX or Windows
436
+ * form, a junction's included), and `..` only as a leading run that stays
437
+ * inside the checkout from the link's own directory (`depth` names below the
438
+ * root). Once a name was walked, a later `..` would step back through what
439
+ * may be another link, which the host resolved by its own rules. Both `/` and
440
+ * `\` split, so neither side's reading slips through. A problem, or null.
441
+ */
442
+ export function linkTargetProblem(target, depth) {
443
+ if (target === '' || target.startsWith('/') || target.startsWith('\\') || /^[A-Za-z]:/.test(target))
444
+ return 'the checkout has a link with an absolute target';
445
+ let up = 0;
446
+ let walked = false;
447
+ for (const part of target.split(/[\\/]+/)) {
448
+ if (part === '' || part === '.')
449
+ continue;
450
+ if (part !== '..') {
451
+ walked = true;
452
+ continue;
453
+ }
454
+ if (walked)
455
+ return 'the checkout has a link whose target steps back (..) after a name';
456
+ if (++up > depth)
457
+ return 'the checkout has a link (a symbolic link or junction) that points outside it';
458
+ }
459
+ return null;
460
+ }
461
+ /** `p` is `root` or under it (case-insensitively on win32, where realpath can differ in case only). */
462
+ function samePathOrUnder(p, root) {
463
+ const norm = (x) => (process.platform === 'win32' ? x.toLowerCase() : x);
464
+ const a = norm(p);
465
+ const b = norm(root);
466
+ return a === b || a.startsWith(b.endsWith(sep) ? b : b + sep);
467
+ }
468
+ /**
469
+ * Run one request in a container. Never throws. `unavailable`: nothing of the
470
+ * PR ran and the container path cannot run it (no runtime, daemon or image,
471
+ * an unsupported project); the engine parks at gate-container-unavailable.
472
+ */
473
+ export async function runContainerGate(req, s, runLabel, deps) {
474
+ const unavailable = (reason) => ({ ran: false, reason, unavailable: true });
475
+ const noVerdict = (reason) => ({ ran: false, reason, started: true });
476
+ const log = deps.log ?? ((line) => { process.stderr.write(`${line}\n`); });
477
+ const bin = s.runtime;
478
+ const switchBack = 'or set factory.run.sandbox.isolation "copilot" in your user config';
479
+ if (req.purpose === 'install') {
480
+ // The container installs per command into its own volume; the host checkout needs no node_modules.
481
+ return { ran: true, status: 0, output: 'gate container: dependencies are installed in the container per command', timedOut: false };
482
+ }
483
+ if (!/^[a-z0-9-]{1,60}$/.test(runLabel))
484
+ return unavailable(`the run label ${JSON.stringify(runLabel)} is not [a-z0-9-]`);
485
+ let diskLimit;
486
+ try {
487
+ diskLimit = sizeBytes(s.diskLimit);
488
+ }
489
+ catch {
490
+ return unavailable(`factory.run.sandbox.container.diskLimit ${JSON.stringify(s.diskLimit)} is not a size`);
491
+ }
492
+ const probe = await deps.exec(bin, ['version', '--format', '{{.Server.Version}}'], { timeoutMs: PROBE_TIMEOUT_MS });
493
+ if (probe.spawnError !== undefined)
494
+ return unavailable(`the container runtime ${bin} is not installed or not on PATH (${probe.spawnError}); install it, ${switchBack}`);
495
+ if (probe.status !== 0)
496
+ return unavailable(`the container runtime ${bin} does not answer (${firstLine(probe.tail) || `exit ${probe.status}`}); start ${bin === 'docker' ? 'Docker Desktop or the docker daemon' : 'the podman machine or service'}, ${switchBack}`);
497
+ const inspectImage = () => deps.exec(bin, ['image', 'inspect', '--format', '{{.Id}}', s.image], { timeoutMs: PROBE_TIMEOUT_MS });
498
+ let image = await inspectImage();
499
+ if (image.status !== 0) {
500
+ log(`omg factory run: pulling the gate image ${s.image} with ${bin} (factory.run.sandbox.container.image); pin a digest there to fix what runs`);
501
+ const pulled = await deps.exec(bin, ['pull', s.image], { timeoutMs: PULL_TIMEOUT_MS });
502
+ if (pulled.status !== 0)
503
+ return unavailable(`the gate image ${s.image} is not present and ${bin} pull failed (${firstLine(lastLines(pulled.tail)) || `exit ${pulled.status}`}); pull it yourself, set factory.run.sandbox.container.image, ${switchBack}`);
504
+ image = await inspectImage();
505
+ }
506
+ const imageId = /^(sha256:[0-9a-f]{64})$/m.exec(image.tail.trim())?.[1];
507
+ // No id, no run: a tag could name another image by the time a container starts (review-499c).
508
+ if (!imageId)
509
+ return unavailable(`could not read the image id of ${s.image} from ${bin} image inspect (${firstLine(image.tail) || `exit ${image.status}`}); pull the image again or pin a digest in factory.run.sandbox.container.image, ${switchBack}`);
510
+ // Every container runs the exact image inspected above, never what the tag names later (review-499b N4).
511
+ const ref = imageId;
512
+ const plan = installPlan(req.cwd);
513
+ if (plan.kind === 'unsupported')
514
+ return unavailable(`${plan.reason}; ${switchBack}`);
515
+ const scan = checkoutCopyProblem(req.cwd);
516
+ if (scan)
517
+ return noVerdict(`${scan}, so it is not copied into the gate container; nothing is counted`);
518
+ const id = (deps.id ?? (() => randomBytes(4).toString('hex')))();
519
+ const name = `${CONTAINER_NAME_PREFIX}${runLabel}-${id}`;
520
+ const volume = name;
521
+ const network = `${name}-net`;
522
+ const cache = plan.kind === 'npm-ci' && plan.sharedCache ? `${CONTAINER_NAME_PREFIX}cache-${plan.lockHash}` : undefined;
523
+ const labels = ['--label', `${RUN_LABEL}=${runLabel}`, '--label', `${GATE_LABEL}=1`];
524
+ const harden = hardeningArgs(s);
525
+ const work = ['--mount', mountArg(['type=volume', `source=${volume}`, `target=${WORK}`])];
526
+ const workRo = ['--mount', mountArg(['type=volume', `source=${volume}`, `target=${WORK}`, 'readonly'])];
527
+ const started = [];
528
+ let volumeMade = false;
529
+ let networkMade = false;
530
+ const ran = (o) => ({ ran: true, ...o, imageId });
531
+ const removeNetwork = async () => {
532
+ if (!networkMade)
533
+ return;
534
+ const rm = await deps.exec(bin, ['network', 'rm', network], { timeoutMs: PROBE_TIMEOUT_MS }).catch(() => null);
535
+ if (rm?.status === 0)
536
+ networkMade = false;
537
+ };
538
+ /** One step container: its argv under the in-container limit, killed by name at the engine's timeout. */
539
+ const step = (container, opts, argv, timeoutMs, full) => {
540
+ started.push(container);
541
+ return deps.exec(bin, ['run', '--name', container, ...opts, ref, ...inContainerLimit(timeoutMs, argv)], {
542
+ timeoutMs,
543
+ ...(full !== undefined ? { full } : {}),
544
+ onTimeout: async () => {
545
+ await deps.exec(bin, ['kill', container], { timeoutMs: KILL_TIMEOUT_MS }).catch(() => null);
546
+ await deps.exec(bin, ['rm', '-f', container], { timeoutMs: KILL_TIMEOUT_MS }).catch(() => null);
547
+ },
548
+ });
549
+ };
550
+ /**
551
+ * The disk watchdog around one step: `du` of the work volume from a
552
+ * read-only container; over the limit kills only `container`. Fail-closed
553
+ * (review-499b N1): du's total counts even when du exits 1 (entries that
554
+ * vanished mid-walk), and two checks in a row without a total kill too.
555
+ */
556
+ let duCount = 0;
557
+ const watched = async (container, run) => {
558
+ let stopped = false;
559
+ let over;
560
+ let misses = 0;
561
+ let timer;
562
+ let inflight = Promise.resolve();
563
+ const tick = () => {
564
+ inflight = (async () => {
565
+ if (stopped)
566
+ return;
567
+ // A fresh name per check: a leftover du container never blocks the next one.
568
+ const duName = `${container}-du-${++duCount}`;
569
+ started.push(duName);
570
+ const du = await deps.exec(bin, [
571
+ 'run', '--name', duName, ...labels, ...harden, '--network', 'none',
572
+ // root without DAC override: only DAC_READ_SEARCH, so a dir the PR made unreadable is still counted.
573
+ '--user', '0:0', '--cap-add', 'DAC_READ_SEARCH', '--read-only', ...workRo,
574
+ ref, ...inContainerLimit(PROBE_TIMEOUT_MS, ['du', '-sxk', WORK]),
575
+ ], { timeoutMs: PROBE_TIMEOUT_MS + 2 * IN_CONTAINER_GRACE_S * 1000 }).catch(() => null);
576
+ // --rm removed a du that ended normally (0, or 1 with a total); any other end is removed by name now.
577
+ if (du !== null && (du.status === 0 || du.status === 1) && !du.timedOut)
578
+ started.splice(started.indexOf(duName), 1);
579
+ else
580
+ await deps.exec(bin, ['rm', '-f', duName], { timeoutMs: KILL_TIMEOUT_MS }).catch(() => null);
581
+ const m = du ? /^(\d+)\s+\/work\s*$/m.exec(du.tail) : null;
582
+ const kb = m ? Number(m[1]) : NaN;
583
+ if (stopped)
584
+ return;
585
+ const measured = Number.isFinite(kb);
586
+ misses = measured ? 0 : misses + 1;
587
+ if ((measured && kb * 1024 > diskLimit) || misses >= 2) {
588
+ over = measured ? 'over' : 'unmeasured';
589
+ await deps.exec(bin, ['kill', container], { timeoutMs: KILL_TIMEOUT_MS }).catch(() => null);
590
+ await deps.exec(bin, ['rm', '-f', container], { timeoutMs: KILL_TIMEOUT_MS }).catch(() => null);
591
+ return;
592
+ }
593
+ if (!stopped)
594
+ timer = setTimeout(tick, deps.diskWatchMs ?? DISK_WATCH_MS);
595
+ })();
596
+ };
597
+ timer = setTimeout(tick, deps.diskWatchMs ?? DISK_WATCH_MS);
598
+ try {
599
+ const r = await run();
600
+ return over ? { ...r, overDisk: over } : r;
601
+ }
602
+ finally {
603
+ stopped = true;
604
+ clearTimeout(timer);
605
+ await inflight;
606
+ }
607
+ };
608
+ const overDisk = (what, r) => ran({
609
+ status: 1,
610
+ output: tail(`${r.tail.trim()}\n${what} in the gate container ${r.overDisk === 'unmeasured' ? `was stopped: its disk use could not be measured twice in a row, so factory.run.sandbox.container.diskLimit (${s.diskLimit}) could not be checked` : `used more than factory.run.sandbox.container.diskLimit (${s.diskLimit}) and was stopped`}`),
611
+ timedOut: false,
612
+ });
613
+ try {
614
+ const made = await deps.exec(bin, ['volume', 'create', ...labels, volume], { timeoutMs: PROBE_TIMEOUT_MS });
615
+ if (made.status !== 0)
616
+ return unavailable(`${bin} could not create the gate volume (${firstLine(made.tail) || `exit ${made.status}`}); check the runtime's disk, ${switchBack}`);
617
+ volumeMade = true;
618
+ if (cache) {
619
+ const problem = await ensureCacheVolume(deps.exec, bin, cache);
620
+ if (problem)
621
+ return unavailable(`${problem}; ${switchBack}`);
622
+ }
623
+ const cacheMount = cache ? ['--mount', mountArg(['type=volume', `source=${cache}`, `target=/cache`])] : [];
624
+ // 1. copy: root only for tar's chown; the checkout read-only; no network; no PR code runs.
625
+ const copy = await step(`${name}-copy`, [
626
+ ...labels, ...harden, '--network', 'none',
627
+ '--user', '0:0', '--cap-add', 'CHOWN', '--cap-add', 'DAC_OVERRIDE', '--cap-add', 'FOWNER',
628
+ '--read-only', '--mount', mountArg(['type=bind', `source=${resolve(req.cwd)}`, 'target=/in', 'readonly']), ...work, ...cacheMount,
629
+ ...(req.gitView ? ['--mount', mountArg(['type=bind', `source=${resolve(req.gitView)}`, `target=${GIT_VIEW_MOUNT}`, 'readonly'])] : []),
630
+ ], ['sh', '-c', copyScript(plan.kind === 'npm-ci', req.gitView !== undefined)], COPY_TIMEOUT_MS);
631
+ if (copy.status !== 0)
632
+ return noVerdict(`copying the checkout into the gate container failed (exit ${copy.status ?? 'none'}${copy.timedOut ? ', timed out' : ''}); nothing is counted`);
633
+ const runBase = [...labels, ...harden, '--user', CONTAINER_USER, '--read-only', '--tmpfs', '/tmp:rw,exec,nosuid,nodev,size=1g', ...work, '-w', SRC];
634
+ const ownCache = { npm_config_cache: `${WORK}/home/.npm` };
635
+ if (plan.kind === 'npm-ci') {
636
+ const timeoutMs = s.installTimeoutMinutes * 60_000;
637
+ // 2a. npm itself, with network on our own bridge (no other container on it, inter-container traffic off); no PR code runs.
638
+ const net = await deps.exec(bin, ['network', 'create', ...labels, ...(bin === 'docker' ? ['--driver', 'bridge', '-o', 'com.docker.network.bridge.enable_icc=false'] : ['-o', 'isolate=true']), network], { timeoutMs: PROBE_TIMEOUT_MS });
639
+ if (net.status !== 0)
640
+ return unavailable(`${bin} could not create the gate install network (${firstLine(net.tail) || `exit ${net.status}`}); ${switchBack}`);
641
+ networkMade = true;
642
+ const fetchName = `${name}-install`;
643
+ const inst = await watched(fetchName, () => step(fetchName, [
644
+ ...runBase, '--network', network, ...cacheMount,
645
+ ...containerEnvArgs({ ...(cache ? { npm_config_cache: '/cache/npm' } : ownCache), ...NPM_FETCH_ENV }),
646
+ ], ['npm', 'ci', '--ignore-scripts'], timeoutMs));
647
+ await removeNetwork();
648
+ if (inst.overDisk)
649
+ return overDisk('the dependency install (npm ci)', inst);
650
+ if (inst.timedOut)
651
+ return ran({ status: 124, output: tail(`${inst.tail.trim()}\nthe dependency install (npm ci) in the gate container timed out after ${s.installTimeoutMinutes} min`), timedOut: true });
652
+ if (inst.status === null || inst.status === 125)
653
+ return noVerdict(`the container runtime failed while the dependency install ran (exit ${inst.status ?? 'none'}); nothing is counted`);
654
+ if (inst.status !== 0)
655
+ return ran({ status: inst.status, output: tail(`${inst.tail.trim()}\nthe dependency install (npm ci) in the gate container failed (exit ${inst.status})`), timedOut: false });
656
+ // 2b. the install scripts (the PR's code and its dependencies'): no network, no shared cache; the .npmrc is back first.
657
+ const scriptsName = `${name}-scripts`;
658
+ const scripts = await watched(scriptsName, () => step(scriptsName, [...runBase, '--network', 'none', ...containerEnvArgs(ownCache)], ['sh', '-c', SCRIPTS_SCRIPT], timeoutMs));
659
+ if (scripts.overDisk)
660
+ return overDisk('the install scripts', scripts);
661
+ if (scripts.timedOut)
662
+ return ran({ status: 124, output: tail(`${scripts.tail.trim()}\nthe install scripts in the gate container timed out after ${s.installTimeoutMinutes} min`), timedOut: true });
663
+ if (scripts.status === null || scripts.status === 125)
664
+ return noVerdict(`the container runtime failed while the install scripts ran (exit ${scripts.status ?? 'none'}); nothing is counted`);
665
+ if (scripts.status !== 0)
666
+ return ran({ status: scripts.status, output: tail(`${scripts.tail.trim()}\nthe install scripts (npm rebuild and the root's install scripts, no network) in the gate container failed (exit ${scripts.status})`), timedOut: false });
667
+ }
668
+ // 3. run: no network.
669
+ const argv = containerArgv(req);
670
+ const r = await watched(name, () => step(name, [...runBase, '--network', 'none', ...containerEnvArgs(ownCache)], argv, req.timeoutMs));
671
+ if (r.overDisk)
672
+ return overDisk('the command', r);
673
+ if (r.timedOut)
674
+ return ran({ status: 124, output: tail(`${r.tail.trim()}\ntimed out after ${req.timeoutMs} ms`), timedOut: true });
675
+ if (r.spawnError !== undefined || r.status === null || r.status === 125)
676
+ return noVerdict(`the container runtime failed while the command ran (exit ${r.status ?? 'none'}); nothing is counted`);
677
+ const result = ran({ status: r.status, output: tail(r.tail.trim()), timedOut: false });
678
+ if (req.purpose !== 'prepare' || r.status !== 0)
679
+ return result;
680
+ // 4. copy back what a passing prepare check wrote.
681
+ const back = await step(`${name}-export`, [
682
+ ...labels, ...harden, '--network', 'none', '--user', CONTAINER_USER, '--read-only', ...workRo,
683
+ ], ['tar', '-C', SRC, '--exclude=.git', '--exclude=node_modules', '--format=posix', '-cf', '-', '.'], COPY_TIMEOUT_MS, COPY_BACK_MAX_BYTES);
684
+ if (back.status !== 0 || !back.stdout)
685
+ return noVerdict(`reading the prepare check's changes back from the gate container failed (${back.overflow ? 'over the size bound' : `exit ${back.status ?? 'none'}`}); nothing is counted`);
686
+ const problem = applyCopyBack(req.cwd, back.stdout, deps.platform ?? process.platform);
687
+ if (problem)
688
+ return noVerdict(`the prepare check's changes cannot be copied back safely (${problem}); nothing is counted`);
689
+ return result;
690
+ }
691
+ catch {
692
+ return noVerdict('the gate container failed unexpectedly; nothing is counted');
693
+ }
694
+ finally {
695
+ // Every step container by its own name (normally gone already: --rm), then the network and the volume.
696
+ for (const c of started)
697
+ await deps.exec(bin, ['rm', '-f', c], { timeoutMs: KILL_TIMEOUT_MS }).catch(() => null);
698
+ await removeNetwork();
699
+ if (volumeMade) {
700
+ for (let i = 0; i < 3; i++) {
701
+ const rm = await deps.exec(bin, ['volume', 'rm', '-f', volume], { timeoutMs: PROBE_TIMEOUT_MS }).catch(() => null);
702
+ if (rm?.status === 0)
703
+ break;
704
+ await new Promise((r) => setTimeout(r, 500));
705
+ }
706
+ }
707
+ }
708
+ }
709
+ /**
710
+ * The shared npm cache volume: made here, or one that already carries our
711
+ * labels on the local driver with no options (never a volume someone else
712
+ * made under that name, never one that binds a host dir). A problem, or null.
713
+ */
714
+ async function ensureCacheVolume(exec, bin, cache) {
715
+ const inspect = await exec(bin, ['volume', 'inspect', '--format', '{{.Driver}}|{{json .Labels}}|{{json .Options}}', cache], { timeoutMs: PROBE_TIMEOUT_MS });
716
+ if (inspect.status === 0) {
717
+ const [driver, labelsJson, optionsJson] = inspect.tail.trim().split('\n')[0].split('|');
718
+ let labels;
719
+ let options;
720
+ try {
721
+ labels = JSON.parse(labelsJson ?? '');
722
+ options = JSON.parse(optionsJson ?? '');
723
+ }
724
+ catch {
725
+ return `the npm cache volume ${cache} cannot be inspected; remove it (${bin} volume rm ${cache})`;
726
+ }
727
+ const l = (labels ?? {});
728
+ const noOptions = options === null || (typeof options === 'object' && Object.keys(options).length === 0);
729
+ if (driver !== 'local' || l[CACHE_LABEL] !== 'npm' || l[GATE_LABEL] !== '1' || !noOptions)
730
+ return `a volume named ${cache} exists that the factory did not make (driver, labels or options differ); remove or rename it`;
731
+ return null;
732
+ }
733
+ const c = await exec(bin, ['volume', 'create', '--label', `${GATE_LABEL}=1`, '--label', `${CACHE_LABEL}=npm`, cache], { timeoutMs: PROBE_TIMEOUT_MS });
734
+ return c.status === 0 ? null : `${bin} could not create the npm cache volume (${firstLine(c.tail) || `exit ${c.status}`})`;
735
+ }
736
+ const tail = (text) => {
737
+ const clean = redactGateOutput(text);
738
+ return clean.length > SANDBOX_OUTPUT_TAIL_CHARS ? clean.slice(-SANDBOX_OUTPUT_TAIL_CHARS) : clean;
739
+ };
740
+ const firstLine = (text) => text.trim().split('\n')[0]?.trim().slice(0, 300) ?? '';
741
+ const lastLines = (text) => text.trim().split('\n').slice(-1).join('\n');
742
+ /** A minimal POSIX/ustar tar reader (pax `x` path/linkpath/size records, GNU long names). Throws on a malformed stream. */
743
+ export function readTar(buf, maxEntries = COPY_BACK_MAX_ENTRIES) {
744
+ const entries = [];
745
+ let off = 0;
746
+ let pax = {};
747
+ let longName;
748
+ let longLink;
749
+ const str = (b) => { const z = b.indexOf(0); return (z === -1 ? b : b.subarray(0, z)).toString('utf8'); };
750
+ const octal = (b) => {
751
+ if (b[0] & 0x80)
752
+ throw new Error('base-256 size');
753
+ const t = str(b).trim();
754
+ if (t === '')
755
+ return 0;
756
+ if (!/^[0-7]+$/.test(t))
757
+ throw new Error('bad octal field');
758
+ return parseInt(t, 8);
759
+ };
760
+ while (off + 512 <= buf.length) {
761
+ const h = buf.subarray(off, off + 512);
762
+ if (h.every((x) => x === 0))
763
+ return entries;
764
+ const sum = octal(h.subarray(148, 156));
765
+ let calc = 0;
766
+ for (let i = 0; i < 512; i++)
767
+ calc += i >= 148 && i < 156 ? 32 : h[i];
768
+ if (calc !== sum)
769
+ throw new Error('bad header checksum');
770
+ const flag = String.fromCharCode(h[156] || 48);
771
+ let size = octal(h.subarray(124, 136));
772
+ if (pax.size !== undefined)
773
+ size = Number(pax.size);
774
+ if (!Number.isSafeInteger(size) || size < 0)
775
+ throw new Error('bad size');
776
+ const start = off + 512;
777
+ const end = start + size;
778
+ if (end > buf.length)
779
+ throw new Error('truncated');
780
+ const data = buf.subarray(start, end);
781
+ off = start + Math.ceil(size / 512) * 512;
782
+ if (flag === 'x') {
783
+ pax = { ...pax, ...parsePax(data) };
784
+ continue;
785
+ }
786
+ if (flag === 'g')
787
+ continue;
788
+ if (flag === 'L') {
789
+ longName = str(data);
790
+ continue;
791
+ }
792
+ if (flag === 'K') {
793
+ longLink = str(data);
794
+ continue;
795
+ }
796
+ const prefix = str(h.subarray(345, 500));
797
+ const path = pax.path ?? longName ?? (prefix ? `${prefix}/${str(h.subarray(0, 100))}` : str(h.subarray(0, 100)));
798
+ const linkTarget = pax.linkpath ?? longLink ?? str(h.subarray(157, 257));
799
+ const type = flag === '0' || flag === '7' ? 'file' : flag === '5' ? 'dir' : flag === '2' ? 'symlink' : flag === '1' ? 'hardlink' : 'other';
800
+ entries.push({ path, type, mode: octal(h.subarray(100, 108)), ...(type === 'file' ? { data: Buffer.from(data) } : {}), ...(type === 'symlink' || type === 'hardlink' ? { linkTarget } : {}) });
801
+ if (entries.length > maxEntries)
802
+ throw new Error('too many entries');
803
+ pax = {};
804
+ longName = undefined;
805
+ longLink = undefined;
806
+ }
807
+ throw new Error('no end-of-archive marker');
808
+ }
809
+ function parsePax(data) {
810
+ const out = {};
811
+ let i = 0;
812
+ while (i < data.length) {
813
+ const space = data.indexOf(0x20, i);
814
+ if (space === -1)
815
+ throw new Error('bad pax record');
816
+ const len = Number(data.subarray(i, space).toString('ascii'));
817
+ if (!Number.isSafeInteger(len) || len <= space - i || i + len > data.length)
818
+ throw new Error('bad pax record');
819
+ const rec = data.subarray(space + 1, i + len - 1).toString('utf8');
820
+ const eq = rec.indexOf('=');
821
+ if (eq > 0)
822
+ out[rec.slice(0, eq)] = rec.slice(eq + 1);
823
+ i += len;
824
+ }
825
+ return out;
826
+ }
827
+ /** Code points macOS (HFS+) ignores in names: dropped before names are compared there. */
828
+ const IGNORABLE = [[0xad, 0xad], [0x200b, 0x200f], [0x202a, 0x202e], [0x2060, 0x2064], [0xfeff, 0xfeff]];
829
+ const dropIgnorable = (s) => [...s].filter((ch) => { const c = ch.codePointAt(0); return !IGNORABLE.some(([a, b]) => c >= a && c <= b); }).join('');
830
+ /** Whether this host's file system may treat names that differ in case (or Unicode form) as one: win32 and darwin. */
831
+ const foldsCase = (platform) => platform === 'win32' || platform === 'darwin';
832
+ /** A path as this host compares it: lowercased and NFC-normalised where names fold (win32, darwin). */
833
+ export function foldPath(p, platform) {
834
+ return foldsCase(platform) ? dropIgnorable(p.normalize('NFC')).toLowerCase() : p;
835
+ }
836
+ /** One name component is `name` (`.git`, `node_modules`) as this host would resolve it. */
837
+ function isName(component, name, platform) {
838
+ if (!foldsCase(platform))
839
+ return component === name;
840
+ const c = dropIgnorable(component.normalize('NFC'));
841
+ return c.toLowerCase() === name || c.toUpperCase() === name.toUpperCase() || c.normalize('NFKC').toLowerCase() === name;
842
+ }
843
+ /** A relative POSIX path from the tar, normalised (`./` dropped), or null when it may not be written on this host. */
844
+ export function safeRelPath(raw, platform) {
845
+ const p = raw.replace(/^(?:\.\/)+/, '').replace(/\/+$/, '');
846
+ if (p === '' || p === '.')
847
+ return '';
848
+ if (p.startsWith('/') || p.includes('\0') || p.includes('\\'))
849
+ return null;
850
+ const parts = p.split('/');
851
+ if (parts.some((s) => s === '' || s === '.' || s === '..'))
852
+ return null;
853
+ if (parts.some((s) => isName(s, '.git', platform) || isName(s, 'node_modules', platform)))
854
+ return null;
855
+ // win32: reserved characters and device names, a trailing dot or space, and any 8.3 short-name shape (`NODE_M~1`).
856
+ if (platform === 'win32' && parts.some((s) => /[<>:"|?*\x00-\x1f]/.test(s) || /[. ]$/.test(s) || /~\d/.test(s) || /^(?:con|prn|aux|nul|com[\d¹²³]|lpt[\d¹²³]|conin\$|conout\$)(?:\..*)?$/i.test(s)))
857
+ return null;
858
+ return p;
859
+ }
860
+ /**
861
+ * The host checkout's entries outside `.git` and `node_modules` (any case
862
+ * where names fold), keyed by folded relative POSIX path (lstat: links are
863
+ * not followed). A regular file with more than one hard link is 'other'.
864
+ */
865
+ function hostTree(root, platform) {
866
+ const out = new Map();
867
+ const walk = (dir, rel) => {
868
+ for (const name of readdirSync(dir)) {
869
+ if (isName(name, '.git', platform) || isName(name, 'node_modules', platform))
870
+ continue;
871
+ const r = rel ? `${rel}/${name}` : name;
872
+ const st = lstatSync(join(dir, name));
873
+ const kind = st.isSymbolicLink() ? 'symlink' : st.isDirectory() ? 'dir' : st.isFile() && st.nlink === 1 ? 'file' : 'other';
874
+ out.set(foldPath(r, platform), { rel: r, kind });
875
+ if (kind === 'dir')
876
+ walk(join(dir, name), r);
877
+ }
878
+ };
879
+ walk(root, '');
880
+ return out;
881
+ }
882
+ /**
883
+ * Every existing component of `rel` under the checkout, read from the file
884
+ * system itself (whatever case or short name resolves it): each parent a
885
+ * real directory (never a link or junction), the leaf absent or a regular
886
+ * file with one link, and the deepest existing parent's real path inside the
887
+ * checkout's. A problem, or null.
888
+ */
889
+ function onDiskProblem(checkout, realRoot, rel, leaf) {
890
+ const parts = rel.split('/');
891
+ let deepest = checkout;
892
+ for (let i = 0; i < parts.length; i++) {
893
+ const path = join(checkout, ...parts.slice(0, i + 1));
894
+ let st;
895
+ try {
896
+ st = lstatSync(path);
897
+ }
898
+ catch (error) {
899
+ // Only a missing component ends the walk (the rest is made); any other error is unchecked, never fine (review-499b N6).
900
+ if (error.code === 'ENOENT')
901
+ break;
902
+ return 'a path could not be checked';
903
+ }
904
+ if (st.isSymbolicLink())
905
+ return 'a file would be written through a host link';
906
+ if (i < parts.length - 1 || leaf === 'dir') {
907
+ if (!st.isDirectory())
908
+ return 'a file would be written under a non-directory';
909
+ deepest = path;
910
+ }
911
+ else if (!st.isFile() || st.nlink !== 1)
912
+ return 'a file replaces a host directory, link or hard-linked file';
913
+ }
914
+ let real;
915
+ try {
916
+ real = realpathSync.native(deepest);
917
+ }
918
+ catch {
919
+ return 'a parent directory could not be resolved';
920
+ }
921
+ return samePathOrUnder(real, realRoot) ? null : 'a file would be written outside the checkout';
922
+ }
923
+ /**
924
+ * Write the container's tree back into the checkout: regular files that
925
+ * differ are written, host files the container removed are removed. Checked
926
+ * whole before anything is written; returns a fixed-text problem (never a
927
+ * path: the names are the PR's) and writes nothing when a check fails.
928
+ * Names are compared as this host resolves them (case and Unicode form on
929
+ * win32/darwin; 8.3 short names refused), and every write is checked on the
930
+ * disk itself: no parent may be a link or junction, and the real path stays
931
+ * in the checkout. Each file is replaced atomically (a temp file in its dir,
932
+ * then a rename, so a hard link to it is never written through); a write
933
+ * that fails part-way leaves the files before it written and returns a
934
+ * problem (the engine gives no verdict).
935
+ */
936
+ export function applyCopyBack(checkout, tar, platform) {
937
+ let entries;
938
+ try {
939
+ entries = readTar(tar);
940
+ }
941
+ catch {
942
+ return 'the tar stream is malformed or too large';
943
+ }
944
+ let host;
945
+ let realRoot;
946
+ try {
947
+ host = hostTree(checkout, platform);
948
+ realRoot = realpathSync.native(checkout);
949
+ }
950
+ catch {
951
+ return 'the checkout could not be listed';
952
+ }
953
+ const want = new Map();
954
+ for (const e of entries) {
955
+ const rel = safeRelPath(e.path, platform);
956
+ if (rel === null)
957
+ return 'an entry has a path that cannot be written here';
958
+ if (rel === '')
959
+ continue;
960
+ const key = foldPath(rel, platform);
961
+ if (want.has(key))
962
+ return 'two entries name the same file on this host';
963
+ want.set(key, { rel, e });
964
+ }
965
+ const writes = [];
966
+ for (const [key, { rel, e }] of want) {
967
+ const kind = host.get(key)?.kind;
968
+ if (e.type === 'dir') {
969
+ if (kind !== undefined && kind !== 'dir')
970
+ return 'a directory replaces a host file or link';
971
+ continue;
972
+ }
973
+ if (e.type === 'symlink') {
974
+ // An unchanged link (copied in, copied back) is fine; a new or changed one is never made on the host.
975
+ if (kind !== 'symlink')
976
+ return 'the check created a symbolic link';
977
+ continue;
978
+ }
979
+ if (e.type !== 'file')
980
+ return 'the check created a hardlink, device or other special file';
981
+ if (kind !== undefined && kind !== 'file')
982
+ return 'a file replaces a host directory, link or hard-linked file';
983
+ const parts = rel.split('/');
984
+ for (let i = 1; i < parts.length; i++) {
985
+ const pkey = foldPath(parts.slice(0, i).join('/'), platform);
986
+ const parent = host.get(pkey)?.kind;
987
+ if (parent !== undefined && parent !== 'dir')
988
+ return 'a file would be written through a host link';
989
+ const w = want.get(pkey);
990
+ if (parent === undefined && w && w.e.type !== 'dir')
991
+ return 'a file would be written under a non-directory';
992
+ }
993
+ const disk = onDiskProblem(checkout, realRoot, rel, 'file');
994
+ if (disk)
995
+ return disk;
996
+ if (kind === 'file') {
997
+ const cur = readFileSync(join(checkout, ...parts));
998
+ if (cur.equals(e.data))
999
+ continue;
1000
+ }
1001
+ writes.push({ rel, data: e.data, mode: e.mode });
1002
+ }
1003
+ const removals = [...host].filter(([key, h]) => (h.kind === 'file' || h.kind === 'symlink') && !want.has(key)).map(([, h]) => h.rel);
1004
+ for (const rel of removals) {
1005
+ const parent = rel.split('/').slice(0, -1).join('/');
1006
+ if (parent && onDiskProblem(checkout, realRoot, parent, 'dir'))
1007
+ return 'a file to remove lies under a host link';
1008
+ }
1009
+ for (const { rel, data, mode } of writes) {
1010
+ const path = join(checkout, ...rel.split('/'));
1011
+ const dir = dirname(path);
1012
+ let tmp;
1013
+ try {
1014
+ mkdirSync(dir, { recursive: true });
1015
+ // Re-checked after the directories exist: the real dir is still inside the checkout.
1016
+ if (!samePathOrUnder(realpathSync.native(dir), realRoot))
1017
+ return 'a file would be written outside the checkout; files before it were written';
1018
+ tmp = join(dir, `.omg-copy-back-${randomBytes(6).toString('hex')}`);
1019
+ writeFileSync(tmp, data, { flag: 'wx' });
1020
+ if (platform !== 'win32')
1021
+ chmodSync(tmp, mode & 0o111 ? 0o755 : 0o644);
1022
+ renameSync(tmp, path);
1023
+ tmp = undefined;
1024
+ }
1025
+ catch {
1026
+ if (tmp)
1027
+ try {
1028
+ unlinkSync(tmp);
1029
+ }
1030
+ catch { /* gone */ }
1031
+ return 'writing a file back failed part-way; files before it were written';
1032
+ }
1033
+ }
1034
+ // unlink removes a link itself, never its target.
1035
+ try {
1036
+ for (const rel of removals)
1037
+ unlinkSync(join(checkout, ...rel.split('/')));
1038
+ }
1039
+ catch {
1040
+ return 'removing a file the check deleted failed part-way';
1041
+ }
1042
+ return null;
1043
+ }
1044
+ /** The runtime's version for `omg factory check` (null when it does not answer). */
1045
+ export function probeContainerRuntime(s, execSync = defaultContainerExecSync) {
1046
+ const v = execSync(s.runtime, ['version', '--format', '{{.Server.Version}}']);
1047
+ const version = v.status === 0 ? v.stdout.trim().split('\n')[0] || 'unknown' : null;
1048
+ const image = version !== null && execSync(s.runtime, ['image', 'inspect', '--format', '{{.Id}}', s.image]).status === 0;
1049
+ return { version, image };
1050
+ }
1051
+ /**
1052
+ * `omg factory run clean`: this run's leftover containers (a killed engine),
1053
+ * networks and volumes, found by its label AND the name prefix; nothing
1054
+ * else. A runtime that does not answer removes nothing (and says so).
1055
+ */
1056
+ export function cleanRunContainers(runtime, runLabel, execSync = defaultContainerExecSync) {
1057
+ const filter = ['--filter', `label=${RUN_LABEL}=${runLabel}`];
1058
+ const ours = (out) => out.split(/\r?\n/).map((l) => l.trim()).filter((n) => n.startsWith(`${CONTAINER_NAME_PREFIX}${runLabel}-`) && /^[a-z0-9-]+$/.test(n));
1059
+ const ps = execSync(runtime, ['ps', '-a', '--format', '{{.Names}}', ...filter]);
1060
+ if (ps.status !== 0)
1061
+ return { removed: [], problem: `${runtime} did not answer; this run's gate containers, networks and volumes (label ${RUN_LABEL}=${runLabel}) were not checked` };
1062
+ const removed = [];
1063
+ for (const n of ours(ps.stdout))
1064
+ if (execSync(runtime, ['rm', '-f', n]).status === 0)
1065
+ removed.push(n);
1066
+ const nets = execSync(runtime, ['network', 'ls', '--format', '{{.Name}}', ...filter]);
1067
+ for (const n of nets.status === 0 ? ours(nets.stdout) : [])
1068
+ if (execSync(runtime, ['network', 'rm', n]).status === 0)
1069
+ removed.push(n);
1070
+ const vols = execSync(runtime, ['volume', 'ls', '--format', '{{.Name}}', ...filter]);
1071
+ for (const n of vols.status === 0 ? ours(vols.stdout) : [])
1072
+ if (execSync(runtime, ['volume', 'rm', '-f', n]).status === 0)
1073
+ removed.push(n);
1074
+ return { removed };
1075
+ }
1076
+ //# sourceMappingURL=container-gate.js.map