@tangle-network/agent-bench 0.3.6 → 0.3.8

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 (265) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/HARNESS.md +43 -0
  3. package/dist/adapters.js +24 -24
  4. package/dist/benchmarks/_harness.d.ts +1 -1
  5. package/dist/benchmarks/_harness.js +1 -1
  6. package/dist/benchmarks/aec-bench.js +2 -2
  7. package/dist/benchmarks/agentbench.js +2 -2
  8. package/dist/benchmarks/appworld.js +2 -2
  9. package/dist/benchmarks/bfcl.js +2 -2
  10. package/dist/benchmarks/commit0.js +2 -2
  11. package/dist/benchmarks/crag.js +2 -2
  12. package/dist/benchmarks/dabstep.js +2 -2
  13. package/dist/benchmarks/enterpriseops-gym.js +2 -2
  14. package/dist/benchmarks/finresearchbench.js +2 -2
  15. package/dist/benchmarks/humaneval.d.ts +10 -1
  16. package/dist/benchmarks/humaneval.js +5 -3
  17. package/dist/benchmarks/nomiracl.js +2 -2
  18. package/dist/benchmarks/open-rag-bench.js +2 -2
  19. package/dist/benchmarks/programbench.js +2 -2
  20. package/dist/benchmarks/ragbench.js +2 -2
  21. package/dist/benchmarks/swe-bench.js +2 -2
  22. package/dist/benchmarks/t2-ragbench.js +2 -2
  23. package/dist/benchmarks/tau-bench-shared.js +2 -2
  24. package/dist/benchmarks/tau2-bench.js +3 -3
  25. package/dist/benchmarks/tau3-banking.js +3 -3
  26. package/dist/benchmarks/terminal-bench.js +2 -2
  27. package/dist/benchmarks/toollm.js +2 -2
  28. package/dist/benchmarks/webarena-verified.js +2 -2
  29. package/dist/{chunk-CKUVRZ2T.js → chunk-3U5TXJZS.js} +2 -2
  30. package/dist/{chunk-PPYSEKFM.js → chunk-5H5XV76F.js} +73 -15
  31. package/dist/chunk-5H5XV76F.js.map +1 -0
  32. package/dist/{chunk-YCGY7UIZ.js → chunk-7GRVHU22.js} +2 -2
  33. package/dist/{chunk-Z7ML6L77.js → chunk-HWST3SED.js} +2 -2
  34. package/dist/{chunk-SYDW647C.js → chunk-IA2FBTWC.js} +2 -2
  35. package/dist/{chunk-R67DFVLO.js → chunk-IFVINJ4B.js} +2 -2
  36. package/dist/{chunk-R36V2VP7.js → chunk-IZ5M6OAC.js} +2 -2
  37. package/dist/{chunk-ODT47UAY.js → chunk-K3BQGZCT.js} +2 -2
  38. package/dist/{chunk-IFAV6KEM.js → chunk-KP5KD6EN.js} +2 -2
  39. package/dist/{chunk-ZEWMTR5M.js → chunk-MQMRLGOG.js} +2 -2
  40. package/dist/{chunk-TSWPNOYM.js → chunk-NQG5XDSB.js} +2 -2
  41. package/dist/{chunk-7WSD27QQ.js → chunk-PB64GYIG.js} +2 -2
  42. package/dist/{chunk-HBSWHQNJ.js → chunk-RCYQEFNX.js} +3 -3
  43. package/dist/{chunk-J3KDJNX2.js → chunk-RH5F53JT.js} +2 -2
  44. package/dist/{chunk-UAIOHCUK.js → chunk-SFLA7OH3.js} +3 -3
  45. package/dist/{chunk-Y6O2OCUO.js → chunk-SHM6MRRF.js} +2 -2
  46. package/dist/{chunk-KDIKRJGB.js → chunk-SHYIRB7I.js} +2 -2
  47. package/dist/{chunk-HHXFIHXC.js → chunk-SVR2LKYI.js} +2 -2
  48. package/dist/{chunk-5SBJCB6W.js → chunk-V7AEBY6U.js} +22 -22
  49. package/dist/{chunk-LRRD7NAG.js → chunk-WSKWVEQB.js} +18 -2
  50. package/dist/chunk-WSKWVEQB.js.map +1 -0
  51. package/dist/{chunk-2PVVP7GN.js → chunk-XKEFIFIC.js} +2 -2
  52. package/dist/{chunk-JRWWGMK7.js → chunk-XYA4XSNU.js} +2 -2
  53. package/dist/{chunk-X5YKXC6V.js → chunk-YSMEKBTD.js} +2 -2
  54. package/dist/{chunk-2XU6OGEN.js → chunk-Z4TZ76N7.js} +2 -2
  55. package/dist/index.js +24 -24
  56. package/package.json +6 -5
  57. package/scripts/run-package-tests.mjs +30 -8
  58. package/scripts/verify-packed-consumer.mjs +1 -1
  59. package/scripts/verify-pier-agent.mts +1 -0
  60. package/src/benchmarks/_harness.ts +20 -2
  61. package/src/benchmarks/humaneval.test.mts +122 -0
  62. package/src/benchmarks/humaneval.ts +100 -27
  63. package/src/david-attribution.mts +78 -0
  64. package/src/david-goliath.mts +149 -0
  65. package/src/hev-improve.mts +25 -6
  66. package/src/humaneval-object-ablation.mts +201 -0
  67. package/src/live-improve-campaign-mbpp.mts +641 -0
  68. package/src/live-improve-campaign.mts +500 -0
  69. package/src/mbpp-structural.mts +12 -7
  70. package/src/quant-arena/README.md +144 -0
  71. package/src/quant-arena/backtest.test.mts +135 -0
  72. package/src/quant-arena/backtest.ts +218 -0
  73. package/src/quant-arena/data.test.mts +44 -0
  74. package/src/quant-arena/data.ts +141 -0
  75. package/src/quant-arena/driver.test.mts +253 -0
  76. package/src/quant-arena/driver.ts +219 -0
  77. package/src/quant-arena/fixtures/data/PROVENANCE.md +26 -0
  78. package/src/quant-arena/fixtures/data/holdout/IDX.csv +523 -0
  79. package/src/quant-arena/fixtures/data/holdout/S01.csv +523 -0
  80. package/src/quant-arena/fixtures/data/holdout/S02.csv +523 -0
  81. package/src/quant-arena/fixtures/data/holdout/S03.csv +523 -0
  82. package/src/quant-arena/fixtures/data/holdout/S04.csv +523 -0
  83. package/src/quant-arena/fixtures/data/holdout/S05.csv +523 -0
  84. package/src/quant-arena/fixtures/data/holdout/S06.csv +523 -0
  85. package/src/quant-arena/fixtures/data/holdout/S07.csv +523 -0
  86. package/src/quant-arena/fixtures/data/holdout/S08.csv +523 -0
  87. package/src/quant-arena/fixtures/data/holdout/S09.csv +523 -0
  88. package/src/quant-arena/fixtures/data/holdout/S10.csv +523 -0
  89. package/src/quant-arena/fixtures/data/insample/IDX.csv +2087 -0
  90. package/src/quant-arena/fixtures/data/insample/S01.csv +2087 -0
  91. package/src/quant-arena/fixtures/data/insample/S02.csv +2087 -0
  92. package/src/quant-arena/fixtures/data/insample/S03.csv +2087 -0
  93. package/src/quant-arena/fixtures/data/insample/S04.csv +2087 -0
  94. package/src/quant-arena/fixtures/data/insample/S05.csv +2087 -0
  95. package/src/quant-arena/fixtures/data/insample/S06.csv +2087 -0
  96. package/src/quant-arena/fixtures/data/insample/S07.csv +2087 -0
  97. package/src/quant-arena/fixtures/data/insample/S08.csv +2087 -0
  98. package/src/quant-arena/fixtures/data/insample/S09.csv +2087 -0
  99. package/src/quant-arena/fixtures/data/insample/S10.csv +2087 -0
  100. package/src/quant-arena/fixtures/demo-campaign/cost-ledger.jsonl +16 -0
  101. package/src/quant-arena/fixtures/demo-campaign/notebook.jsonl +5 -0
  102. package/src/quant-arena/fixtures/demo-campaign/rollout-manifest.json +171 -0
  103. package/src/quant-arena/fixtures/demo-campaign/strategies/cand-001-default-author/strategy.ts +119 -0
  104. package/src/quant-arena/fixtures/demo-campaign/strategies/cand-002-default-author/strategy.ts +119 -0
  105. package/src/quant-arena/fixtures/demo-campaign/strategies/cand-003-quant-researcher/strategy.ts +105 -0
  106. package/src/quant-arena/fixtures/demo-campaign/strategies/cand-004-quant-researcher/strategy.ts +102 -0
  107. package/src/quant-arena/fixtures/demo-campaign-v2/cost-ledger.jsonl +4 -0
  108. package/src/quant-arena/fixtures/demo-campaign-v2/notebook.jsonl +2 -0
  109. package/src/quant-arena/fixtures/demo-campaign-v2/rollout-manifest.json +84 -0
  110. package/src/quant-arena/fixtures/demo-campaign-v2/strategies/cand-001-quant-researcher/strategy.ts +117 -0
  111. package/src/quant-arena/holdout-certify.mts +206 -0
  112. package/src/quant-arena/holdout-certify.test.mts +82 -0
  113. package/src/quant-arena/leak-audit.test.mts +79 -0
  114. package/src/quant-arena/leak-audit.ts +95 -0
  115. package/src/quant-arena/make-fixtures.mts +161 -0
  116. package/src/quant-arena/multiplicity.test.mts +68 -0
  117. package/src/quant-arena/multiplicity.ts +87 -0
  118. package/src/quant-arena/nautilus-certify.ts +31 -0
  119. package/src/quant-arena/oms.ts +90 -0
  120. package/src/quant-arena/profiles/quant-researcher.profile.json +7 -0
  121. package/src/quant-arena/python/pyproject.toml +8 -0
  122. package/src/quant-arena/python/uv.lock +1297 -0
  123. package/src/quant-arena/python/vbt-worker.py +192 -0
  124. package/src/quant-arena/quant-loop.mts +813 -0
  125. package/src/quant-arena/quant-loop.test.mts +75 -0
  126. package/src/quant-arena/strategies/buy-hold-index/strategy.ts +11 -0
  127. package/src/quant-arena/strategies/equal-weight/strategy.ts +20 -0
  128. package/src/quant-arena/strategies/sma-crossover/strategy.ts +42 -0
  129. package/src/quant-arena/types.ts +133 -0
  130. package/src/quant-arena/vbt-client.ts +321 -0
  131. package/src/quant-arena/vbt-parity.test.mts +183 -0
  132. package/src/quant-arena/windows.test.mts +45 -0
  133. package/src/quant-arena/windows.ts +54 -0
  134. package/src/rollout-ledger/backfill-swe-arena.mts +606 -0
  135. package/src/rollout-ledger/backfill-swe-arena.test.mts +338 -0
  136. package/src/rollout-ledger/settle-capture.mts +442 -0
  137. package/src/rollout-ledger/settle-capture.test.mts +270 -0
  138. package/src/stream-observe.py +45 -0
  139. package/src/stream-observe.tpl.html +247 -0
  140. package/src/supervisor-arena.mts +816 -0
  141. package/src/swe-arena/activation.mts +228 -0
  142. package/src/swe-arena/activation.test.mts +303 -0
  143. package/src/swe-arena/analyze.ts +211 -0
  144. package/src/swe-arena/arms.ts +804 -0
  145. package/src/swe-arena/bootstrap-meta.mts +188 -0
  146. package/src/swe-arena/bootstrap-meta.test.mts +51 -0
  147. package/src/swe-arena/briefing.mts +217 -0
  148. package/src/swe-arena/briefing.test.mts +178 -0
  149. package/src/swe-arena/calibrate.ts +217 -0
  150. package/src/swe-arena/capabilities.mts +76 -0
  151. package/src/swe-arena/capabilities.test.mts +57 -0
  152. package/src/swe-arena/capacity.ts +194 -0
  153. package/src/swe-arena/cell-evidence.mts +437 -0
  154. package/src/swe-arena/cell-evidence.test.mts +248 -0
  155. package/src/swe-arena/diagnosis-ensemble.test.mts +210 -0
  156. package/src/swe-arena/diagnosis-ensemble.ts +520 -0
  157. package/src/swe-arena/execution.test.mts +1170 -0
  158. package/src/swe-arena/factory-command-container.ts +284 -0
  159. package/src/swe-arena/factory-judge-child.mts +228 -0
  160. package/src/swe-arena/factory.test.mts +643 -0
  161. package/src/swe-arena/fixtures/analyze.py +80 -0
  162. package/src/swe-arena/fixtures/excludes.txt +8 -0
  163. package/src/swe-arena/fixtures/factory/agent-eval-309/calibration.md +51 -0
  164. package/src/swe-arena/fixtures/factory/agent-eval-309/manifest.json +29 -0
  165. package/src/swe-arena/fixtures/factory/agent-eval-309/spec.md +64 -0
  166. package/src/swe-arena/fixtures/factory/agent-runtime-232/calibration.md +48 -0
  167. package/src/swe-arena/fixtures/factory/agent-runtime-232/manifest.json +29 -0
  168. package/src/swe-arena/fixtures/factory/agent-runtime-232/spec.md +48 -0
  169. package/src/swe-arena/fixtures/factory/loops-28/calibration.md +47 -0
  170. package/src/swe-arena/fixtures/factory/loops-28/manifest.json +30 -0
  171. package/src/swe-arena/fixtures/factory/loops-28/spec.md +50 -0
  172. package/src/swe-arena/fixtures/gen1-salvage/README.md +45 -0
  173. package/src/swe-arena/fixtures/gen1-salvage/cand0-e6d7361.diff +116 -0
  174. package/src/swe-arena/fixtures/gen1-salvage/cand1-76a8590.diff +293 -0
  175. package/src/swe-arena/fixtures/holdout-preregister.log +12 -0
  176. package/src/swe-arena/fixtures/holdout.json +44 -0
  177. package/src/swe-arena/fixtures/instances.json +146 -0
  178. package/src/swe-arena/fixtures/ledger.jsonl +12 -0
  179. package/src/swe-arena/fixtures/patches/pallets__flask-5014.solo.patch +36 -0
  180. package/src/swe-arena/fixtures/patches/pydata__xarray-4687.sup.patch +33 -0
  181. package/src/swe-arena/fixtures/rejudge.jsonl +15 -0
  182. package/src/swe-arena/fixtures/rematch.jsonl +3 -0
  183. package/src/swe-arena/fixtures/rematch2.jsonl +3 -0
  184. package/src/swe-arena/fixtures/rematch3.jsonl +3 -0
  185. package/src/swe-arena/fixtures/run-report/README.md +43 -0
  186. package/src/swe-arena/fixtures/run-report/factory-agent-eval-309-FSUP0.json +173 -0
  187. package/src/swe-arena/fixtures/run-report/factory-agent-eval-309-FSUP0.md +100 -0
  188. package/src/swe-arena/fixtures/run-report/gen3-rollup.json +551 -0
  189. package/src/swe-arena/fixtures/run-report/gen3-rollup.md +64 -0
  190. package/src/swe-arena/fixtures/sup-journal-true.json +19 -0
  191. package/src/swe-arena/fixtures/verify/astropy__astropy-13033.sh +48 -0
  192. package/src/swe-arena/fixtures/verify/django__django-11532.sh +50 -0
  193. package/src/swe-arena/fixtures/verify/matplotlib__matplotlib-20826.sh +76 -0
  194. package/src/swe-arena/fixtures/verify/pydata__xarray-4687.sh +44 -0
  195. package/src/swe-arena/fixtures/verify/pytest-dev__pytest-6197.sh +32 -0
  196. package/src/swe-arena/fixtures/verify/sphinx-doc__sphinx-9658.sh +51 -0
  197. package/src/swe-arena/fixtures/worker-tokens.json +42 -0
  198. package/src/swe-arena/fixtures.ts +237 -0
  199. package/src/swe-arena/gepa-seat.mts +583 -0
  200. package/src/swe-arena/gepa-seat.test.mts +635 -0
  201. package/src/swe-arena/holdout-certify.mts +408 -0
  202. package/src/swe-arena/holdout-certify.test.mts +160 -0
  203. package/src/swe-arena/judge-child.mts +37 -0
  204. package/src/swe-arena/ledger-orphans.mts +77 -0
  205. package/src/swe-arena/ledger-orphans.test.mts +147 -0
  206. package/src/swe-arena/lineage-record.mts +164 -0
  207. package/src/swe-arena/lineage-record.test.mts +115 -0
  208. package/src/swe-arena/manifest.mts +293 -0
  209. package/src/swe-arena/manifest.test.mts +169 -0
  210. package/src/swe-arena/materialize.ts +142 -0
  211. package/src/swe-arena/outer-loop.mts +2795 -0
  212. package/src/swe-arena/outer-loop.test.mts +696 -0
  213. package/src/swe-arena/parity.test.mts +87 -0
  214. package/src/swe-arena/premeasured-from-cells.mts +281 -0
  215. package/src/swe-arena/premeasured-from-cells.test.mts +180 -0
  216. package/src/swe-arena/proc.test.mts +174 -0
  217. package/src/swe-arena/proc.ts +260 -0
  218. package/src/swe-arena/profiles/default-author.profile.json +4 -0
  219. package/src/swe-arena/proposer-fanout.mts +770 -0
  220. package/src/swe-arena/proposer-fanout.test.mts +619 -0
  221. package/src/swe-arena/proposer-provenance.mts +177 -0
  222. package/src/swe-arena/proposer-provenance.test.mts +106 -0
  223. package/src/swe-arena/reconcile.ts +0 -0
  224. package/src/swe-arena/replay.mts +183 -0
  225. package/src/swe-arena/replay.test.mts +300 -0
  226. package/src/swe-arena/run-experiment.mts +727 -0
  227. package/src/swe-arena/run-report.mts +75 -0
  228. package/src/swe-arena/run-supervisor.mjs +297 -0
  229. package/src/swe-arena/run-supervisor.test.mts +500 -0
  230. package/src/swe-arena/score-split.mts +140 -0
  231. package/src/swe-arena/score-split.test.mts +123 -0
  232. package/src/swe-arena/serialized-judge.ts +414 -0
  233. package/src/swe-arena/types.ts +218 -0
  234. package/src/swe-code-improve.mts +328 -0
  235. package/src/swe-emit-patch.mts +104 -0
  236. package/src/swe-improve.mts +232 -0
  237. package/src/swe-jail.ts +2 -2
  238. package/src/swe-local-proof.mts +169 -0
  239. package/src/swe-repro-calibrate.mts +446 -0
  240. package/src/swe-stream.mts +1497 -0
  241. package/src/swe-structural.mts +245 -837
  242. package/dist/chunk-LRRD7NAG.js.map +0 -1
  243. package/dist/chunk-PPYSEKFM.js.map +0 -1
  244. /package/dist/{chunk-CKUVRZ2T.js.map → chunk-3U5TXJZS.js.map} +0 -0
  245. /package/dist/{chunk-YCGY7UIZ.js.map → chunk-7GRVHU22.js.map} +0 -0
  246. /package/dist/{chunk-Z7ML6L77.js.map → chunk-HWST3SED.js.map} +0 -0
  247. /package/dist/{chunk-SYDW647C.js.map → chunk-IA2FBTWC.js.map} +0 -0
  248. /package/dist/{chunk-R67DFVLO.js.map → chunk-IFVINJ4B.js.map} +0 -0
  249. /package/dist/{chunk-R36V2VP7.js.map → chunk-IZ5M6OAC.js.map} +0 -0
  250. /package/dist/{chunk-ODT47UAY.js.map → chunk-K3BQGZCT.js.map} +0 -0
  251. /package/dist/{chunk-IFAV6KEM.js.map → chunk-KP5KD6EN.js.map} +0 -0
  252. /package/dist/{chunk-ZEWMTR5M.js.map → chunk-MQMRLGOG.js.map} +0 -0
  253. /package/dist/{chunk-TSWPNOYM.js.map → chunk-NQG5XDSB.js.map} +0 -0
  254. /package/dist/{chunk-7WSD27QQ.js.map → chunk-PB64GYIG.js.map} +0 -0
  255. /package/dist/{chunk-HBSWHQNJ.js.map → chunk-RCYQEFNX.js.map} +0 -0
  256. /package/dist/{chunk-J3KDJNX2.js.map → chunk-RH5F53JT.js.map} +0 -0
  257. /package/dist/{chunk-UAIOHCUK.js.map → chunk-SFLA7OH3.js.map} +0 -0
  258. /package/dist/{chunk-Y6O2OCUO.js.map → chunk-SHM6MRRF.js.map} +0 -0
  259. /package/dist/{chunk-KDIKRJGB.js.map → chunk-SHYIRB7I.js.map} +0 -0
  260. /package/dist/{chunk-HHXFIHXC.js.map → chunk-SVR2LKYI.js.map} +0 -0
  261. /package/dist/{chunk-5SBJCB6W.js.map → chunk-V7AEBY6U.js.map} +0 -0
  262. /package/dist/{chunk-2PVVP7GN.js.map → chunk-XKEFIFIC.js.map} +0 -0
  263. /package/dist/{chunk-JRWWGMK7.js.map → chunk-XYA4XSNU.js.map} +0 -0
  264. /package/dist/{chunk-X5YKXC6V.js.map → chunk-YSMEKBTD.js.map} +0 -0
  265. /package/dist/{chunk-2XU6OGEN.js.map → chunk-Z4TZ76N7.js.map} +0 -0
@@ -0,0 +1,284 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { mkdir, mkdtemp, realpath, rm, stat } from 'node:fs/promises'
3
+ import { tmpdir } from 'node:os'
4
+ import { delimiter, isAbsolute, join } from 'node:path'
5
+
6
+ import { run, type RunResult } from './proc'
7
+
8
+ const WORKSPACE_PATH = '/workspace'
9
+ const STATE_PATH = '/factory-state'
10
+ const IMAGE_DIGEST_RE = /^.+@sha256:[0-9a-f]{64}$/
11
+ const CONTAINER_PATH =
12
+ `${STATE_PATH}/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`
13
+ const CONTROL_TIMEOUT_MS = 30_000
14
+
15
+ export type FactoryCommandNetwork = 'enabled' | 'none'
16
+
17
+ export interface RunFactoryCommandOptions {
18
+ image: string
19
+ network: FactoryCommandNetwork
20
+ timeoutMs: number
21
+ signal?: AbortSignal
22
+ maxBuffer?: number
23
+ }
24
+
25
+ function hostPath(baseEnv: NodeJS.ProcessEnv): string {
26
+ const path = (baseEnv.PATH ?? '')
27
+ .split(delimiter)
28
+ .filter((entry) => entry.length > 0 && isAbsolute(entry))
29
+ .join(delimiter)
30
+ if (!path) throw new Error('factory container control process requires an absolute PATH')
31
+ return path
32
+ }
33
+
34
+ async function createControlEnvironment(): Promise<{
35
+ env: NodeJS.ProcessEnv
36
+ dispose: () => Promise<void>
37
+ }> {
38
+ const root = await mkdtemp(join(tmpdir(), 'factory-container-control-'))
39
+ const home = join(root, 'home')
40
+ const dockerConfig = join(root, 'docker')
41
+ const xdgConfig = join(root, 'xdg')
42
+ const temp = join(root, 'tmp')
43
+ try {
44
+ await Promise.all(
45
+ [home, dockerConfig, xdgConfig, temp].map((dir) =>
46
+ mkdir(dir, { recursive: true, mode: 0o700 }),
47
+ ),
48
+ )
49
+ let disposal: Promise<void> | undefined
50
+ return {
51
+ env: {
52
+ PATH: hostPath(process.env),
53
+ HOME: home,
54
+ DOCKER_CONFIG: dockerConfig,
55
+ XDG_CONFIG_HOME: xdgConfig,
56
+ TMPDIR: temp,
57
+ TMP: temp,
58
+ TEMP: temp,
59
+ LANG: 'C',
60
+ LC_ALL: 'C',
61
+ TZ: 'UTC',
62
+ },
63
+ dispose: () => (disposal ??= rm(root, { recursive: true, force: true })),
64
+ }
65
+ } catch (error) {
66
+ await rm(root, { recursive: true, force: true })
67
+ throw error
68
+ }
69
+ }
70
+
71
+ function currentUser(): { uid: number; gid: number } {
72
+ const uid = process.getuid?.()
73
+ const gid = process.getgid?.()
74
+ if (
75
+ typeof uid !== 'number' ||
76
+ typeof gid !== 'number' ||
77
+ !Number.isSafeInteger(uid) ||
78
+ !Number.isSafeInteger(gid)
79
+ ) {
80
+ throw new Error('factory command containers require a POSIX uid and gid')
81
+ }
82
+ if (uid === 0) {
83
+ throw new Error('factory command containers refuse to run candidate commands as root')
84
+ }
85
+ return { uid, gid }
86
+ }
87
+
88
+ function containerEnvironment(): string[] {
89
+ return [
90
+ `PATH=${CONTAINER_PATH}`,
91
+ `HOME=${STATE_PATH}/home`,
92
+ `XDG_CONFIG_HOME=${STATE_PATH}/xdg/config`,
93
+ `XDG_DATA_HOME=${STATE_PATH}/xdg/data`,
94
+ `XDG_CACHE_HOME=${STATE_PATH}/xdg/cache`,
95
+ `XDG_STATE_HOME=${STATE_PATH}/xdg/state`,
96
+ `XDG_RUNTIME_DIR=${STATE_PATH}/xdg/runtime`,
97
+ 'TMPDIR=/tmp',
98
+ 'TMP=/tmp',
99
+ 'TEMP=/tmp',
100
+ 'LANG=C',
101
+ 'LC_ALL=C',
102
+ 'TZ=UTC',
103
+ 'CI=false',
104
+ `COREPACK_HOME=${STATE_PATH}/corepack`,
105
+ 'COREPACK_DEFAULT_TO_LATEST=0',
106
+ 'COREPACK_ENABLE_DOWNLOAD_PROMPT=0',
107
+ `PNPM_HOME=${STATE_PATH}/pnpm-home`,
108
+ `npm_config_store_dir=${STATE_PATH}/pnpm-store`,
109
+ `NPM_CONFIG_CACHE=${STATE_PATH}/npm-cache`,
110
+ `NPM_CONFIG_USERCONFIG=${STATE_PATH}/npm/user.npmrc`,
111
+ `NPM_CONFIG_GLOBALCONFIG=${STATE_PATH}/npm/global.npmrc`,
112
+ 'GIT_CONFIG_NOSYSTEM=1',
113
+ `GIT_CONFIG_GLOBAL=${STATE_PATH}/git/global.config`,
114
+ `GIT_CONFIG_SYSTEM=${STATE_PATH}/git/system.config`,
115
+ 'GIT_TERMINAL_PROMPT=0',
116
+ 'GCM_INTERACTIVE=Never',
117
+ ]
118
+ }
119
+
120
+ const COMMAND_WRAPPER = `
121
+ set -eu
122
+ mkdir -p \
123
+ "$HOME" \
124
+ "$XDG_CONFIG_HOME" \
125
+ "$XDG_DATA_HOME" \
126
+ "$XDG_CACHE_HOME" \
127
+ "$XDG_STATE_HOME" \
128
+ "$XDG_RUNTIME_DIR" \
129
+ "$COREPACK_HOME" \
130
+ "$PNPM_HOME" \
131
+ "$npm_config_store_dir" \
132
+ "$NPM_CONFIG_CACHE" \
133
+ "${STATE_PATH}/npm" \
134
+ "${STATE_PATH}/git" \
135
+ "${STATE_PATH}/bin"
136
+ touch \
137
+ "$NPM_CONFIG_USERCONFIG" \
138
+ "$NPM_CONFIG_GLOBALCONFIG" \
139
+ "$GIT_CONFIG_GLOBAL" \
140
+ "$GIT_CONFIG_SYSTEM"
141
+ corepack enable --install-directory "${STATE_PATH}/bin" >/dev/null
142
+ exec /bin/bash --noprofile --norc -c "$1"
143
+ `
144
+
145
+ function dockerArgs(input: {
146
+ name: string
147
+ workspace: string
148
+ command: string
149
+ image: string
150
+ network: FactoryCommandNetwork
151
+ uid: number
152
+ gid: number
153
+ }): string[] {
154
+ const user = `${input.uid}:${input.gid}`
155
+ return [
156
+ 'run',
157
+ '--rm',
158
+ '--name',
159
+ input.name,
160
+ '--hostname',
161
+ 'factory-command',
162
+ '--pull=missing',
163
+ '--read-only',
164
+ '--init',
165
+ '--cap-drop=ALL',
166
+ '--security-opt=no-new-privileges',
167
+ '--pids-limit=512',
168
+ '--memory=4g',
169
+ '--memory-swap=4g',
170
+ '--cpus=2',
171
+ '--ulimit',
172
+ 'nofile=4096:4096',
173
+ '--ipc=private',
174
+ '--network',
175
+ input.network === 'none' ? 'none' : 'bridge',
176
+ '--user',
177
+ user,
178
+ '--workdir',
179
+ WORKSPACE_PATH,
180
+ '--mount',
181
+ `type=bind,src=${input.workspace},dst=${WORKSPACE_PATH},bind-propagation=rprivate`,
182
+ '--tmpfs',
183
+ `/tmp:rw,nosuid,nodev,mode=1777,size=512m,uid=${input.uid},gid=${input.gid}`,
184
+ '--tmpfs',
185
+ `${STATE_PATH}:rw,nosuid,nodev,mode=700,size=2048m,uid=${input.uid},gid=${input.gid}`,
186
+ '--entrypoint=/usr/bin/env',
187
+ input.image,
188
+ '-i',
189
+ ...containerEnvironment(),
190
+ '/bin/bash',
191
+ '--noprofile',
192
+ '--norc',
193
+ '-c',
194
+ COMMAND_WRAPPER,
195
+ 'factory-command',
196
+ input.command,
197
+ ]
198
+ }
199
+
200
+ function isAlreadyRemoved(result: RunResult): boolean {
201
+ return /no such container/iu.test(result.stderr || result.stdout)
202
+ }
203
+
204
+ /**
205
+ * Run one repository-controlled command in a fresh container.
206
+ *
207
+ * The candidate sees one writable bind mount: its disposable workspace.
208
+ * Process ids, root files, HOME, XDG state, Corepack, npm, and pnpm caches are
209
+ * private to this invocation and disappear when the container exits.
210
+ */
211
+ export async function runFactoryCommand(
212
+ workspace: string,
213
+ command: string,
214
+ options: RunFactoryCommandOptions,
215
+ ): Promise<RunResult> {
216
+ if (!command.trim()) throw new Error('factory command must not be empty')
217
+ if (!IMAGE_DIGEST_RE.test(options.image)) {
218
+ throw new Error(`factory command image must be pinned by sha256 digest: ${options.image}`)
219
+ }
220
+ if (!Number.isSafeInteger(options.timeoutMs) || options.timeoutMs <= 0) {
221
+ throw new Error(`factory command timeout must be a positive integer: ${options.timeoutMs}`)
222
+ }
223
+ const workspacePath = await realpath(workspace)
224
+ if (!(await stat(workspacePath)).isDirectory()) {
225
+ throw new Error(`factory command workspace is not a directory: ${workspacePath}`)
226
+ }
227
+ if (workspacePath.includes(',')) {
228
+ throw new Error(`factory command workspace path contains an unsupported comma: ${workspacePath}`)
229
+ }
230
+ const { uid, gid } = currentUser()
231
+ const name = `factory-command-${process.pid}-${randomUUID()}`
232
+ const control = await createControlEnvironment()
233
+ let commandResult: RunResult | undefined
234
+ let commandError: unknown
235
+ try {
236
+ commandResult = await run(
237
+ 'docker',
238
+ dockerArgs({
239
+ name,
240
+ workspace: workspacePath,
241
+ command,
242
+ image: options.image,
243
+ network: options.network,
244
+ uid,
245
+ gid,
246
+ }),
247
+ {
248
+ env: control.env,
249
+ timeoutMs: options.timeoutMs,
250
+ killGraceMs: 2_000,
251
+ ...(options.signal ? { signal: options.signal } : {}),
252
+ ...(options.maxBuffer === undefined ? {} : { maxBuffer: options.maxBuffer }),
253
+ },
254
+ )
255
+ } catch (error) {
256
+ commandError = error
257
+ }
258
+
259
+ let cleanupError: unknown
260
+ try {
261
+ const cleanup = await run('docker', ['rm', '-f', name], {
262
+ env: control.env,
263
+ timeoutMs: CONTROL_TIMEOUT_MS,
264
+ })
265
+ if (cleanup.code !== 0 && !isAlreadyRemoved(cleanup)) {
266
+ cleanupError = new Error(
267
+ `factory command container cleanup failed (${cleanup.code}): ${(cleanup.stderr || cleanup.stdout).slice(-1000)}`,
268
+ )
269
+ }
270
+ } catch (error) {
271
+ cleanupError = error
272
+ }
273
+ await control.dispose()
274
+
275
+ if (commandError !== undefined && cleanupError !== undefined) {
276
+ throw new AggregateError(
277
+ [commandError, cleanupError],
278
+ 'factory command and container cleanup both failed',
279
+ )
280
+ }
281
+ if (commandError !== undefined) throw commandError
282
+ if (cleanupError !== undefined) throw cleanupError
283
+ return commandResult!
284
+ }
@@ -0,0 +1,228 @@
1
+ /**
2
+ * Factory judge child — the factory-bench equivalent of `judge-child.mts`.
3
+ * One candidate patch, one hidden-test verdict, printed as a single
4
+ * `JUDGE_RESULT {...}` line so serialized-judge.ts (queue, retry, SIGKILL
5
+ * ceiling) carries over unchanged. The judge workspace is a `git archive`
6
+ * export of the instance's base commit from the local mirror. Setup and judge
7
+ * commands run in separate containers, and the PR's added test files are
8
+ * overlaid from the merge commit only after setup completes.
9
+ *
10
+ * Steps: export base tree → apply candidate patch → run `setup_cmds` in a
11
+ * fresh container → overlay judge tests from `judge_ref` → run `judge_cmds`
12
+ * in a second network-disabled container →
13
+ * parse vitest's pass/fail counts → JUDGE_RESULT with partial credit.
14
+ *
15
+ * Verdict semantics:
16
+ * - `resolved` = every calibrated judge test passes (passed === total, 0 failed).
17
+ * - `score` = passed / judgeTestTotal, where the denominator is the CALIBRATED
18
+ * total from the manifest's resolved_criterion — never vitest's reported
19
+ * total, which shrinks when a judge file fails to collect.
20
+ * - An unappliable patch is the candidate's failure → resolved:false, score 0.
21
+ * - A setup/parse failure is an INFRA failure → exit 1 with no JUDGE_RESULT
22
+ * line, so serialized-judge retries and then records `resolved: null`
23
+ * (inconclusive), never a fabricated verdict.
24
+ *
25
+ * usage: node --import tsx src/swe-arena/factory-judge-child.mts <instanceDir> <patchPath>
26
+ */
27
+
28
+ import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
29
+ import { tmpdir } from 'node:os'
30
+ import { dirname, join } from 'node:path'
31
+ import { pathToFileURL } from 'node:url'
32
+ import { applyPatchWithFallback } from './calibrate.ts'
33
+ import { runFactoryCommand } from './factory-command-container.ts'
34
+ import { loadFactoryInstance, type LoadedFactoryInstance } from './fixtures.ts'
35
+ import { runOk, shq } from './proc.ts'
36
+
37
+ export interface VitestSummary {
38
+ passed: number
39
+ failed: number
40
+ /** vitest's own reported total (collected tests only — informational). */
41
+ reportedTotal: number
42
+ }
43
+
44
+ const stripAnsi = (s: string): string => s.replace(/\u001b\[[0-9;]*m/g, '')
45
+
46
+ /**
47
+ * Parse the `Tests …` summary line of a vitest run (v3 and v4 formats):
48
+ * " Tests 30 passed (30)"
49
+ * " Tests 17 failed | 13 passed (30)"
50
+ * " Tests no tests" (collection failure — 0 passed is a verdict)
51
+ * Returns undefined when no summary line exists (infra failure, not a verdict).
52
+ */
53
+ export function parseVitestSummary(output: string): VitestSummary | undefined {
54
+ for (const rawLine of stripAnsi(output).split('\n')) {
55
+ const m = /^\s*Tests\s{2,}(.+)$/.exec(rawLine)
56
+ if (!m) continue
57
+ const body = m[1].trim()
58
+ if (body.startsWith('no tests')) return { passed: 0, failed: 0, reportedTotal: 0 }
59
+ const passed = /(\d+) passed/.exec(body)
60
+ const failed = /(\d+) failed/.exec(body)
61
+ const total = /\((\d+)\)/.exec(body)
62
+ if (!passed && !failed) continue
63
+ return {
64
+ passed: passed ? Number(passed[1]) : 0,
65
+ failed: failed ? Number(failed[1]) : 0,
66
+ reportedTotal: total ? Number(total[1]) : 0,
67
+ }
68
+ }
69
+ return undefined
70
+ }
71
+
72
+ /** The JUDGE_RESULT row this child prints (superset of the SWE child's fields). */
73
+ export interface FactoryJudgeResult {
74
+ iid: string
75
+ resolved: boolean
76
+ /** passed / judgeTestTotal — partial credit for the staircase. */
77
+ score: number
78
+ passed: number
79
+ total: number
80
+ secs: number
81
+ patch_bytes: number
82
+ error?: string
83
+ }
84
+
85
+ /** Parse one JUDGE_RESULT line back out of child stdout (calibrate + tests). */
86
+ export function parseFactoryJudgeResult(stdout: string): FactoryJudgeResult | undefined {
87
+ const line = stdout.split('\n').find((l) => l.includes('JUDGE_RESULT'))
88
+ if (!line) return undefined
89
+ try {
90
+ const parsed = JSON.parse(line.slice(line.indexOf('JUDGE_RESULT') + 'JUDGE_RESULT'.length).trim())
91
+ if (typeof parsed !== 'object' || parsed === null || typeof parsed.resolved !== 'boolean') return undefined
92
+ return parsed as FactoryJudgeResult
93
+ } catch {
94
+ return undefined
95
+ }
96
+ }
97
+
98
+ /** `git archive <ref> | tar -x` — a bare tree, no .git, no refs, no future history. */
99
+ export async function exportBaseTree(mirror: string, ref: string, dest: string): Promise<void> {
100
+ await mkdir(dest, { recursive: true })
101
+ await runOk('bash', ['-c', `git -C ${shq(mirror)} archive ${shq(ref)} | tar -x -C ${shq(dest)}`])
102
+ }
103
+
104
+ /** Overlay each judge test from the merge commit (`git show <judge_ref>:<path>`). */
105
+ export async function overlayJudgeTests(inst: LoadedFactoryInstance, ws: string): Promise<void> {
106
+ for (const testPath of inst.judge_tests) {
107
+ const show = await runOk('git', ['-C', inst.repo_local_mirror, 'show', `${inst.judge_ref}:${testPath}`])
108
+ await mkdir(dirname(join(ws, testPath)), { recursive: true })
109
+ await writeFile(join(ws, testPath), show.stdout)
110
+ }
111
+ }
112
+
113
+ export interface FactoryJudgeOutcome {
114
+ result: FactoryJudgeResult
115
+ /** Raw judge_cmds output, for post-mortem. */
116
+ output: string
117
+ }
118
+
119
+ /**
120
+ * Build the judge workspace and run the judge over one patch. Throws on infra
121
+ * failure (export/overlay/setup/parse); returns a verdict otherwise.
122
+ */
123
+ export async function judgeFactoryPatch(
124
+ inst: LoadedFactoryInstance,
125
+ patch: string,
126
+ opts: { workDir?: string; keepWorkspace?: boolean } = {},
127
+ ): Promise<FactoryJudgeOutcome> {
128
+ const t0 = Date.now()
129
+ const ws = opts.workDir ?? (await mkdtemp(join(tmpdir(), `factory-judge-${inst.id.replace(/[^a-zA-Z0-9.-]/g, '-')}-`)))
130
+ const cmdTimeoutMs = inst.timeout_s * 1000
131
+ try {
132
+ await exportBaseTree(inst.repo_local_mirror, inst.base_commit, ws)
133
+ // A git repo (fresh, historyless) so `git apply` and repo tooling behave;
134
+ // judge-side only, so its refs are irrelevant to leak prevention.
135
+ await runOk('git', ['-C', ws, 'init', '-q'])
136
+
137
+ if (patch.trim().length > 0) {
138
+ const patchFile = join(ws, '.factory-candidate.patch')
139
+ await writeFile(patchFile, patch)
140
+ const applyRc = await applyPatchWithFallback(ws, patchFile)
141
+ await rm(patchFile, { force: true })
142
+ if (applyRc !== 0) {
143
+ return {
144
+ result: {
145
+ iid: inst.id,
146
+ resolved: false,
147
+ score: 0,
148
+ passed: 0,
149
+ total: inst.judgeTestTotal,
150
+ secs: Math.round((Date.now() - t0) / 1000),
151
+ patch_bytes: patch.length,
152
+ error: `apply-failed rc=${applyRc}`,
153
+ },
154
+ output: '',
155
+ }
156
+ }
157
+ }
158
+
159
+ for (const cmd of inst.setup_cmds) {
160
+ const res = await runFactoryCommand(ws, cmd, {
161
+ image: inst.command_image,
162
+ network: 'enabled',
163
+ timeoutMs: cmdTimeoutMs,
164
+ })
165
+ if (res.code !== 0) {
166
+ throw new Error(
167
+ `setup_cmd failed (rc=${res.code}${res.timedOut ? ', timeout' : ''}): ${cmd}\n${(res.stderr || res.stdout).slice(-2000)}`,
168
+ )
169
+ }
170
+ }
171
+
172
+ await overlayJudgeTests(inst, ws)
173
+
174
+ let passed = 0
175
+ let failed = 0
176
+ let output = ''
177
+ for (const cmd of inst.judge_cmds) {
178
+ const res = await runFactoryCommand(ws, cmd, {
179
+ image: inst.command_image,
180
+ network: 'none',
181
+ timeoutMs: cmdTimeoutMs,
182
+ })
183
+ const combined = res.stdout + res.stderr
184
+ output += combined
185
+ if (res.timedOut) throw new Error(`judge_cmd timed out after ${cmdTimeoutMs}ms: ${cmd}`)
186
+ const summary = parseVitestSummary(combined)
187
+ if (!summary) {
188
+ throw new Error(`judge_cmd produced no parseable test summary (rc=${res.code}): ${cmd}\n${combined.slice(-2000)}`)
189
+ }
190
+ passed += summary.passed
191
+ failed += summary.failed
192
+ }
193
+
194
+ const total = inst.judgeTestTotal
195
+ return {
196
+ result: {
197
+ iid: inst.id,
198
+ resolved: failed === 0 && passed === total,
199
+ score: total > 0 ? Number((passed / total).toFixed(4)) : 0,
200
+ passed,
201
+ total,
202
+ secs: Math.round((Date.now() - t0) / 1000),
203
+ patch_bytes: patch.length,
204
+ },
205
+ output,
206
+ }
207
+ } finally {
208
+ if (!opts.keepWorkspace) await rm(ws, { recursive: true, force: true })
209
+ }
210
+ }
211
+
212
+ // ---------------------------------------------------------------------------
213
+ // CLI (guarded so calibrate/tests can import the helpers above).
214
+ // ---------------------------------------------------------------------------
215
+
216
+ const isMain = process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href
217
+
218
+ if (isMain) {
219
+ const [, , instanceDir, patchPath] = process.argv
220
+ if (!instanceDir || !patchPath) {
221
+ console.error('usage: node --import tsx factory-judge-child.mts <instanceDir> <patchPath>')
222
+ process.exit(2)
223
+ }
224
+ const inst = loadFactoryInstance(instanceDir)
225
+ const patch = await readFile(patchPath, 'utf8')
226
+ const { result } = await judgeFactoryPatch(inst, patch)
227
+ console.log('JUDGE_RESULT ' + JSON.stringify(result))
228
+ }