@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,293 @@
1
+ /**
2
+ * Rollout manifest — a pure READER/JOIN over what the round already writes.
3
+ * No new capture pipeline: the lib's improve() run emits loop-provenance.json,
4
+ * per-cell cached results, and the durable cost log; the swe-arena dispatch
5
+ * emits arm result/judge files, candidate patches, and proposer-shot receipts.
6
+ * This module joins them into one versioned per-generation manifest of
7
+ * (state, action, outcome, cost, artifactPaths) triples.
8
+ *
9
+ * tsx src/swe-arena/manifest.mts <outDir> # writes <outDir>/rollout-manifest.json
10
+ *
11
+ * Sources (all optional — a missing file is a labeled gap, never a crash):
12
+ * - <outDir>/improve-run/loop-provenance.json (lib)
13
+ * - <outDir>/improve-run/cost-ledger.jsonl (lib, durable receipts)
14
+ * - <outDir>/improve-run/baseline and gen-N/candidate-K (lib, per-cell caches)
15
+ * - <outDir>/candidates/<commit10>.patch (ours, diff writing)
16
+ * - <outDir>/proposer-shots/genN-candK-shotS.json (ours, shot receipts)
17
+ * - per-cell artifact.runDir result.json + judge.json (ours, arm + judge)
18
+ */
19
+
20
+ import { readdir, readFile, writeFile } from 'node:fs/promises'
21
+ import { existsSync } from 'node:fs'
22
+ import { join } from 'node:path'
23
+ import { pathToFileURL } from 'node:url'
24
+ import {
25
+ loadCampaignCells,
26
+ loadCandidateCellGroups,
27
+ perInstanceFromCells,
28
+ replicateRunsFromCells,
29
+ resolvedInstanceCount,
30
+ sumWallSFromCells,
31
+ type EvidenceCell,
32
+ type StaircasePerInstance,
33
+ } from './cell-evidence.mts'
34
+
35
+ export const ROLLOUT_SCHEMA = 'swe-arena.rollout.v1'
36
+
37
+ export interface RolloutCost {
38
+ /** Σ campaign-cell CostLedger spend (worker receipts) across the cells. */
39
+ cellCostUsd: number
40
+ cellTokensIn: number
41
+ cellTokensOut: number
42
+ /** Σ runtime spend-tree usd/tokens off the artifacts (telemetry-gap nulls skipped). */
43
+ armSpentUsd: number
44
+ armSpentTokens: number
45
+ wallS: number
46
+ judgeWallS: number
47
+ /** Durable cost-ledger receipts whose tags name this campaign dir. */
48
+ receiptCallIds: string[]
49
+ }
50
+
51
+ export interface RolloutEntry {
52
+ state: {
53
+ generation: number
54
+ /** -1 candidateIndex = the baseline campaign. */
55
+ candidateIndex: number
56
+ campaignDir: string
57
+ commit: string | null
58
+ }
59
+ action: {
60
+ /** Candidate diff written at dispatch time (null for the baseline / a
61
+ * resumed-only run whose diff was not rewritten). */
62
+ diffPath: string | null
63
+ /** Persisted proposer-shot receipts for this (generation, candidate). */
64
+ shotReceiptPaths: string[]
65
+ }
66
+ outcome: {
67
+ perInstance: StaircasePerInstance[]
68
+ resolvedCount: number
69
+ cellsCached: number
70
+ }
71
+ cost: RolloutCost
72
+ artifactPaths: {
73
+ cells: string[]
74
+ armResults: string[]
75
+ judgeVerdicts: string[]
76
+ patches: string[]
77
+ }
78
+ }
79
+
80
+ export interface RolloutGeneration {
81
+ generation: number
82
+ rollouts: RolloutEntry[]
83
+ }
84
+
85
+ export interface RolloutManifest {
86
+ schema: typeof ROLLOUT_SCHEMA
87
+ outDir: string
88
+ at: string
89
+ /** The lib's durable provenance record, verbatim (null = not emitted). */
90
+ provenance: unknown | null
91
+ /** Improvement-set ids inferred from the baseline cells. */
92
+ instances: string[]
93
+ generations: RolloutGeneration[]
94
+ }
95
+
96
+ interface LedgerReceipt {
97
+ callId: string
98
+ tags?: Record<string, string>
99
+ [k: string]: unknown
100
+ }
101
+
102
+ /** Settled receipts out of the lib's append-only cost-ledger.jsonl. */
103
+ export async function loadLedgerReceipts(improveRunDir: string): Promise<LedgerReceipt[]> {
104
+ const raw = await readFile(join(improveRunDir, 'cost-ledger.jsonl'), 'utf8').catch(() => '')
105
+ const receipts: LedgerReceipt[] = []
106
+ for (const line of raw.split('\n')) {
107
+ if (!line.trim()) continue
108
+ let event: Record<string, unknown>
109
+ try {
110
+ event = JSON.parse(line) as Record<string, unknown>
111
+ } catch {
112
+ continue
113
+ }
114
+ const record = event.record as Record<string, unknown> | undefined
115
+ if (record && record.status === 'settled' && typeof record.callId === 'string') {
116
+ receipts.push(record as unknown as LedgerReceipt)
117
+ }
118
+ }
119
+ return receipts
120
+ }
121
+
122
+ function costFromCells(
123
+ cells: EvidenceCell[],
124
+ campaignDir: string,
125
+ receipts: LedgerReceipt[],
126
+ ): RolloutCost {
127
+ let cellCostUsd = 0
128
+ let cellTokensIn = 0
129
+ let cellTokensOut = 0
130
+ let armSpentUsd = 0
131
+ let armSpentTokens = 0
132
+ let judgeWallS = 0
133
+ for (const cell of cells) {
134
+ cellCostUsd += cell.costUsd ?? 0
135
+ cellTokensIn += cell.tokenUsage?.input ?? 0
136
+ cellTokensOut += cell.tokenUsage?.output ?? 0
137
+ const a = cell.artifact
138
+ if (a !== null && a.kind === 'swe-arm') {
139
+ armSpentUsd += a.spentUsd ?? 0
140
+ armSpentTokens += a.spentTokens ?? 0
141
+ judgeWallS += a.judgeWallS ?? 0
142
+ }
143
+ }
144
+ return {
145
+ cellCostUsd: Number(cellCostUsd.toFixed(6)),
146
+ cellTokensIn,
147
+ cellTokensOut,
148
+ armSpentUsd: Number(armSpentUsd.toFixed(6)),
149
+ armSpentTokens,
150
+ wallS: sumWallSFromCells(cells),
151
+ judgeWallS,
152
+ receiptCallIds: receipts
153
+ .filter((r) => r.tags?.runDir === campaignDir)
154
+ .map((r) => r.callId)
155
+ .sort(),
156
+ }
157
+ }
158
+
159
+ function artifactPathsFromCells(cells: EvidenceCell[], campaignDir: string): RolloutEntry['artifactPaths'] {
160
+ const armResults: string[] = []
161
+ const judgeVerdicts: string[] = []
162
+ const patches: string[] = []
163
+ for (const cell of cells) {
164
+ const a = cell.artifact
165
+ if (a === null || a.kind !== 'swe-arm') continue
166
+ if (a.runDir) {
167
+ const resultPath = join(a.runDir, 'result.json')
168
+ const judgePath = join(a.runDir, 'judge.json')
169
+ if (existsSync(resultPath)) armResults.push(resultPath)
170
+ if (existsSync(judgePath)) judgeVerdicts.push(judgePath)
171
+ }
172
+ if (a.patchPath && existsSync(a.patchPath)) patches.push(a.patchPath)
173
+ }
174
+ return {
175
+ // The campaign dir holds the per-cell cached-result.json score records.
176
+ cells: cells.length > 0 ? [campaignDir] : [],
177
+ armResults: [...new Set(armResults)].sort(),
178
+ judgeVerdicts: [...new Set(judgeVerdicts)].sort(),
179
+ patches: [...new Set(patches)].sort(),
180
+ }
181
+ }
182
+
183
+ async function shotReceiptPathsFor(
184
+ outDir: string,
185
+ generation: number,
186
+ candidateIndex: number,
187
+ ): Promise<string[]> {
188
+ const shotDir = join(outDir, 'proposer-shots')
189
+ const names = await readdir(shotDir).catch(() => [])
190
+ return names
191
+ .filter((n) => n.startsWith(`gen${generation}-cand${candidateIndex}-`) && n.endsWith('.json'))
192
+ .sort()
193
+ .map((n) => join(shotDir, n))
194
+ }
195
+
196
+ /** Build the rollout manifest for one round outDir. Pure join — reads only. */
197
+ export async function buildRolloutManifest(outDir: string): Promise<RolloutManifest> {
198
+ const improveRunDir = join(outDir, 'improve-run')
199
+ const provenanceRaw = await readFile(join(improveRunDir, 'loop-provenance.json'), 'utf8').catch(() => null)
200
+ const provenance = provenanceRaw === null ? null : (JSON.parse(provenanceRaw) as unknown)
201
+ const receipts = await loadLedgerReceipts(improveRunDir)
202
+
203
+ const baselineDir = join(improveRunDir, 'baseline')
204
+ const baselineCells = await loadCampaignCells(baselineDir)
205
+ const instances = [...new Set(baselineCells.map((c) => c.scenarioId))].sort()
206
+
207
+ const generations = new Map<number, RolloutGeneration>()
208
+ const genOf = (g: number): RolloutGeneration => {
209
+ const existing = generations.get(g)
210
+ if (existing) return existing
211
+ const fresh: RolloutGeneration = { generation: g, rollouts: [] }
212
+ generations.set(g, fresh)
213
+ return fresh
214
+ }
215
+
216
+ if (baselineCells.length > 0) {
217
+ genOf(-1).rollouts.push({
218
+ state: { generation: -1, candidateIndex: -1, campaignDir: baselineDir, commit: baselineCells[0]?.artifact?.commit ?? null },
219
+ action: { diffPath: null, shotReceiptPaths: [] },
220
+ outcome: {
221
+ perInstance: perInstanceFromCells(baselineCells),
222
+ resolvedCount: resolvedInstanceCount(
223
+ replicateRunsFromCells(baselineCells),
224
+ instances,
225
+ maxRep(baselineCells) + 1,
226
+ ),
227
+ cellsCached: baselineCells.length,
228
+ },
229
+ cost: costFromCells(baselineCells, baselineDir, receipts),
230
+ artifactPaths: artifactPathsFromCells(baselineCells, baselineDir),
231
+ })
232
+ }
233
+
234
+ for (const group of await loadCandidateCellGroups(improveRunDir)) {
235
+ const diffPath = group.commit ? join(outDir, 'candidates', `${group.commit.slice(0, 10)}.patch`) : null
236
+ genOf(group.generation).rollouts.push({
237
+ state: {
238
+ generation: group.generation,
239
+ candidateIndex: group.candidateIndex,
240
+ campaignDir: group.dir,
241
+ commit: group.commit,
242
+ },
243
+ action: {
244
+ diffPath: diffPath !== null && existsSync(diffPath) ? diffPath : null,
245
+ shotReceiptPaths: await shotReceiptPathsFor(outDir, group.generation, group.candidateIndex),
246
+ },
247
+ outcome: {
248
+ perInstance: perInstanceFromCells(group.cells),
249
+ resolvedCount: resolvedInstanceCount(
250
+ replicateRunsFromCells(group.cells),
251
+ instances,
252
+ maxRep(group.cells) + 1,
253
+ ),
254
+ cellsCached: group.cells.length,
255
+ },
256
+ cost: costFromCells(group.cells, group.dir, receipts),
257
+ artifactPaths: artifactPathsFromCells(group.cells, group.dir),
258
+ })
259
+ }
260
+
261
+ return {
262
+ schema: ROLLOUT_SCHEMA,
263
+ outDir,
264
+ at: new Date().toISOString(),
265
+ provenance,
266
+ instances,
267
+ generations: [...generations.values()].sort((a, b) => a.generation - b.generation),
268
+ }
269
+ }
270
+
271
+ /** Replicate count inferred from the cells themselves (reps = max rep index
272
+ * + 1). The manifest is a reader with no config in scope; an incomplete
273
+ * candidate under-infers reps and its resolvedCount stays fail-closed. */
274
+ const maxRep = (cells: EvidenceCell[]): number => cells.reduce((m, c) => Math.max(m, c.rep), 0)
275
+
276
+ export async function writeRolloutManifest(outDir: string): Promise<string> {
277
+ const manifest = await buildRolloutManifest(outDir)
278
+ const path = join(outDir, 'rollout-manifest.json')
279
+ await writeFile(path, JSON.stringify(manifest, null, 2))
280
+ return path
281
+ }
282
+
283
+ const isMain = process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href
284
+
285
+ if (isMain) {
286
+ const outDir = process.argv[2]
287
+ if (!outDir) {
288
+ console.error('usage: tsx src/swe-arena/manifest.mts <outDir>')
289
+ process.exit(2)
290
+ }
291
+ const path = await writeRolloutManifest(outDir)
292
+ console.log(`rollout manifest → ${path}`)
293
+ }
@@ -0,0 +1,169 @@
1
+ /**
2
+ * Rollout-manifest reader: a synthetic round outDir with the lib's files
3
+ * (loop-provenance.json, cost-ledger.jsonl, per-cell caches) and the
4
+ * swe-arena files (arm result/judge json, patches, shot receipts) joins into
5
+ * one versioned manifest. Pure reads — nothing is dispatched.
6
+ */
7
+
8
+ import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
9
+ import { tmpdir } from 'node:os'
10
+ import { join } from 'node:path'
11
+ import { afterAll, describe, expect, it } from 'vitest'
12
+ import type { R4Artifact } from './cell-evidence.mts'
13
+ import { buildRolloutManifest, loadLedgerReceipts, ROLLOUT_SCHEMA, writeRolloutManifest } from './manifest.mts'
14
+
15
+ const IID = 'django__django-11532'
16
+
17
+ describe('rollout manifest (synthetic outDir)', () => {
18
+ let outDir: string
19
+ let armRunDir: string
20
+ let candDir: string
21
+
22
+ afterAll(async () => {
23
+ await rm(outDir, { recursive: true, force: true })
24
+ })
25
+
26
+ async function writeCell(campaignDir: string, rep: number, artifact: R4Artifact, costUsd: number): Promise<void> {
27
+ const cellDir = join(campaignDir, `cell-${IID}-r${rep}`)
28
+ await mkdir(cellDir, { recursive: true })
29
+ await writeFile(
30
+ join(cellDir, 'cached-result.json'),
31
+ JSON.stringify({
32
+ cellId: `cell-${IID}-r${rep}`,
33
+ scenarioId: IID,
34
+ rep,
35
+ artifact,
36
+ costUsd,
37
+ tokenUsage: { input: 400, output: 100 },
38
+ judgeScores: {},
39
+ durationMs: 5,
40
+ seed: 42,
41
+ cached: false,
42
+ }),
43
+ )
44
+ }
45
+
46
+ async function makeOutDir(): Promise<void> {
47
+ outDir = await mkdtemp(join(tmpdir(), 'r4-manifest-'))
48
+ const improveRun = join(outDir, 'improve-run')
49
+
50
+ // Arm run dir the artifacts point at (ours: result.json + judge.json).
51
+ armRunDir = join(outDir, 'arm-runs', 'cafebabe00', 'rep-0', 'runs', IID, 'R4')
52
+ await mkdir(armRunDir, { recursive: true })
53
+ await writeFile(join(armRunDir, 'result.json'), JSON.stringify({ arm: 'R4', iid: IID }))
54
+ await writeFile(join(armRunDir, 'judge.json'), JSON.stringify({ iid: IID, resolved: true, wallS: 31 }))
55
+ const patchPath = join(outDir, 'patches', `${IID}.r4.patch`)
56
+ await mkdir(join(outDir, 'patches'), { recursive: true })
57
+ await writeFile(patchPath, 'diff --git a b\n')
58
+
59
+ const artifact = (resolved: boolean): R4Artifact => ({
60
+ kind: 'swe-arm',
61
+ iid: IID,
62
+ commit: 'cafebabe0012345678',
63
+ resolved,
64
+ verifyPass: resolved,
65
+ patchLines: 4,
66
+ wallS: 120,
67
+ spentTokens: 2000,
68
+ spentUsd: 0.02,
69
+ recoveredTokens: 2500,
70
+ workerTokIn: 400,
71
+ workerTokOut: 100,
72
+ judgeAttempts: 1,
73
+ judgeWallS: 31,
74
+ runDir: armRunDir,
75
+ patchPath,
76
+ })
77
+
78
+ // Lib: baseline campaign cells (different commit).
79
+ const baselineDir = join(improveRun, 'baseline')
80
+ await writeCell(baselineDir, 0, { ...artifact(true), commit: 'basecommit12345678' }, 0.01)
81
+ await writeCell(baselineDir, 1, { ...artifact(true), commit: 'basecommit12345678' }, 0.01)
82
+
83
+ // Lib: gen-0 candidate campaign cells.
84
+ candDir = join(improveRun, 'gen-0', 'candidate-0')
85
+ await writeCell(candDir, 0, artifact(false), 0.02)
86
+ await writeCell(candDir, 1, artifact(false), 0.02)
87
+
88
+ // Lib: durable provenance + cost log.
89
+ await writeFile(
90
+ join(improveRun, 'loop-provenance.json'),
91
+ JSON.stringify({ schema: 'tangle.loop-provenance', runId: 'r4-test', candidates: [] }),
92
+ )
93
+ await writeFile(
94
+ join(improveRun, 'cost-ledger.jsonl'),
95
+ [
96
+ JSON.stringify({ version: 1, record: { status: 'pending', callId: 'p1', channel: 'agent', phase: 'x', actor: 'a', model: 'm', timestamp: 1 } }),
97
+ JSON.stringify({ version: 1, record: { status: 'settled', callId: 'c1', channel: 'agent', phase: 'search.candidate', actor: 'a', model: 'm', timestamp: 2, inputTokens: 400, outputTokens: 100, costUsd: 0.02, costUnknown: false, tags: { runDir: candDir, cellId: `cell-${IID}-r0` } } }),
98
+ JSON.stringify({ version: 1, record: { status: 'settled', callId: 'c2', channel: 'judge', phase: 'search.candidate', actor: 'j', model: 'swe-bench-official-judge', timestamp: 3, inputTokens: 0, outputTokens: 0, costUsd: 0, costUnknown: false, tags: { runDir: candDir, cellId: `cell-${IID}-r1` } } }),
99
+ 'garbage line',
100
+ ].join('\n'),
101
+ )
102
+
103
+ // Ours: candidate diff + proposer shot receipt.
104
+ await mkdir(join(outDir, 'candidates'), { recursive: true })
105
+ await writeFile(join(outDir, 'candidates', 'cafebabe00.patch'), 'diff --git x y\n')
106
+ await mkdir(join(outDir, 'proposer-shots'), { recursive: true })
107
+ await writeFile(join(outDir, 'proposer-shots', 'gen0-cand0-shot1.json'), JSON.stringify({ receipt: { shot: 1 } }))
108
+ }
109
+
110
+ it('joins lib + swe-arena files into versioned per-generation rollout triples', async () => {
111
+ await makeOutDir()
112
+ const manifest = await buildRolloutManifest(outDir)
113
+
114
+ expect(manifest.schema).toBe(ROLLOUT_SCHEMA)
115
+ expect(manifest.instances).toEqual([IID])
116
+ expect((manifest.provenance as { schema: string }).schema).toBe('tangle.loop-provenance')
117
+ expect(manifest.generations.map((g) => g.generation)).toEqual([-1, 0])
118
+
119
+ const baseline = manifest.generations[0]!.rollouts[0]!
120
+ expect(baseline.state).toMatchObject({ generation: -1, candidateIndex: -1, commit: 'basecommit12345678' })
121
+ expect(baseline.outcome.resolvedCount).toBe(1)
122
+ expect(baseline.outcome.perInstance).toHaveLength(2)
123
+ expect(baseline.action.shotReceiptPaths).toEqual([])
124
+
125
+ const cand = manifest.generations[1]!.rollouts[0]!
126
+ expect(cand.state).toMatchObject({ generation: 0, candidateIndex: 0, commit: 'cafebabe0012345678', campaignDir: candDir })
127
+ expect(cand.outcome.resolvedCount).toBe(0)
128
+ expect(cand.outcome.cellsCached).toBe(2)
129
+ // Cost joins: cell ledger spend + artifact spend-tree + judge wall.
130
+ expect(cand.cost.cellCostUsd).toBeCloseTo(0.04, 6)
131
+ expect(cand.cost.cellTokensIn).toBe(800)
132
+ expect(cand.cost.armSpentUsd).toBeCloseTo(0.04, 6)
133
+ expect(cand.cost.armSpentTokens).toBe(4000)
134
+ expect(cand.cost.wallS).toBe(240)
135
+ expect(cand.cost.judgeWallS).toBe(62)
136
+ expect(cand.cost.receiptCallIds).toEqual(['c1', 'c2'])
137
+ // Artifact joins: our arm/judge/patch files + the shot receipt.
138
+ expect(cand.artifactPaths.armResults).toEqual([join(armRunDir, 'result.json')])
139
+ expect(cand.artifactPaths.judgeVerdicts).toEqual([join(armRunDir, 'judge.json')])
140
+ expect(cand.artifactPaths.patches).toHaveLength(1)
141
+ expect(cand.action.diffPath).toBe(join(outDir, 'candidates', 'cafebabe00.patch'))
142
+ expect(cand.action.shotReceiptPaths).toEqual([join(outDir, 'proposer-shots', 'gen0-cand0-shot1.json')])
143
+ })
144
+
145
+ it('loadLedgerReceipts keeps settled records only and survives garbage lines', async () => {
146
+ const receipts = await loadLedgerReceipts(join(outDir, 'improve-run'))
147
+ expect(receipts.map((r) => r.callId)).toEqual(['c1', 'c2'])
148
+ })
149
+
150
+ it('writeRolloutManifest emits <outDir>/rollout-manifest.json (the CLI body)', async () => {
151
+ const path = await writeRolloutManifest(outDir)
152
+ expect(path).toBe(join(outDir, 'rollout-manifest.json'))
153
+ const parsed = JSON.parse(await readFile(path, 'utf8')) as { schema: string }
154
+ expect(parsed.schema).toBe(ROLLOUT_SCHEMA)
155
+ })
156
+
157
+ it('a bare outDir (no improve-run yet) yields an empty, well-formed manifest', async () => {
158
+ const empty = await mkdtemp(join(tmpdir(), 'r4-manifest-empty-'))
159
+ try {
160
+ const manifest = await buildRolloutManifest(empty)
161
+ expect(manifest.schema).toBe(ROLLOUT_SCHEMA)
162
+ expect(manifest.provenance).toBeNull()
163
+ expect(manifest.instances).toEqual([])
164
+ expect(manifest.generations).toEqual([])
165
+ } finally {
166
+ await rm(empty, { recursive: true, force: true })
167
+ }
168
+ })
169
+ })
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Workspace materialization from SWE-bench instance images — the typed port of
3
+ * the experiment's `setup-ws.sh`, stage for stage:
4
+ *
5
+ * docker create <image> → docker cp <container>:/testbed <dest> → docker rm
6
+ * → git reset --hard <base_commit> → git clean -fd → work branch checkout
7
+ *
8
+ * IMAGE materialization is the DEFAULT and must stay so. A plain `git clone`
9
+ * at `base_commit` is insufficient: the instance's runnable environment (conda
10
+ * env, compiled C extensions, version pins) is built by the official harness at
11
+ * `environment_setup_commit` and lives only in the image's /testbed. Round-2 of
12
+ * the supervisor evolution proved this live — clone-materialized worker
13
+ * sandboxes dropped those build artifacts and every verify run died on imports
14
+ * (astropy/matplotlib), which is exactly the failure mode the image path
15
+ * removes. Clone materialization may only ever be an explicit opt-in for
16
+ * pure-python instances, never the default.
17
+ */
18
+
19
+ import { randomUUID } from 'node:crypto'
20
+ import { mkdir, rm, stat } from 'node:fs/promises'
21
+ import { dirname } from 'node:path'
22
+ import { run, runOk } from './proc'
23
+
24
+ export interface MaterializeOptions {
25
+ instanceId: string
26
+ /** Instance image, e.g. swebench/sweb.eval.x86_64.pallets_1776_flask-5014:latest. */
27
+ image: string
28
+ baseCommit: string
29
+ /** Destination directory; removed and recreated (setup-ws.sh `rm -rf`). */
30
+ dest: string
31
+ /** Work branch forced to base_commit and checked out. Default matches the bash. */
32
+ workBranch?: string
33
+ /** Cancels Docker/Git setup before a cell begins model execution. */
34
+ signal?: AbortSignal
35
+ }
36
+
37
+ export interface MaterializedWorkspace {
38
+ head: string
39
+ /** `git status --porcelain` empty after materialization. */
40
+ clean: boolean
41
+ }
42
+
43
+ /** setup-ws.sh container-name sanitization: `tr '_/' '--'` + unique suffix. */
44
+ export function containerName(instanceId: string): string {
45
+ const sanitized = instanceId.replace(/[_/]/g, '-')
46
+ return `ext-${sanitized}-${process.pid}-${randomUUID()}`
47
+ }
48
+
49
+ const DOCKER_CREATE_TIMEOUT_MS = 5 * 60_000
50
+ const DOCKER_COPY_TIMEOUT_MS = 10 * 60_000
51
+ const DOCKER_CLEANUP_TIMEOUT_MS = 60_000
52
+ const GIT_COMMAND_TIMEOUT_MS = 2 * 60_000
53
+
54
+ /**
55
+ * Materialize a pristine workspace for `instanceId` at `dest`. Throws with the
56
+ * setup-ws.sh stage label (create-fail / cp-fail / no-git / reset-fail) so
57
+ * failures stay greppable against the bash experiment's logs.
58
+ */
59
+ export async function materializeWorkspace(opts: MaterializeOptions): Promise<MaterializedWorkspace> {
60
+ const { instanceId, image, baseCommit, dest } = opts
61
+ const workBranch = opts.workBranch ?? 'hh-work'
62
+ const container = containerName(instanceId)
63
+
64
+ opts.signal?.throwIfAborted()
65
+ await rm(dest, { recursive: true, force: true })
66
+ await mkdir(dirname(dest), { recursive: true })
67
+ opts.signal?.throwIfAborted()
68
+
69
+ const create = await run('docker', ['create', '--name', container, image], {
70
+ signal: opts.signal,
71
+ timeoutMs: DOCKER_CREATE_TIMEOUT_MS,
72
+ })
73
+ let stageError: unknown
74
+ try {
75
+ opts.signal?.throwIfAborted()
76
+ if (create.code !== 0) {
77
+ throw new Error(`materialize ${instanceId}: create-fail (${image}): ${create.stderr.slice(0, 500)}`)
78
+ }
79
+ const cp = await run('docker', ['cp', `${container}:/testbed`, dest], {
80
+ signal: opts.signal,
81
+ timeoutMs: DOCKER_COPY_TIMEOUT_MS,
82
+ })
83
+ opts.signal?.throwIfAborted()
84
+ if (cp.code !== 0) {
85
+ throw new Error(`materialize ${instanceId}: cp-fail: ${cp.stderr.slice(0, 500)}`)
86
+ }
87
+ } catch (cause) {
88
+ stageError = cause
89
+ }
90
+
91
+ // Cleanup must still run after the caller signal fires, so it gets its own
92
+ // short deadline instead of the already-aborted cell signal.
93
+ let cleanupError: unknown
94
+ try {
95
+ const cleanup = await run('docker', ['rm', '-f', container], {
96
+ timeoutMs: DOCKER_CLEANUP_TIMEOUT_MS,
97
+ })
98
+ const detail = cleanup.stderr || cleanup.stdout
99
+ const absent = /no such container/iu.test(detail)
100
+ if (cleanup.code !== 0 && !absent) {
101
+ cleanupError = new Error(
102
+ `materialize ${instanceId}: cleanup-fail container=${container} exit=${cleanup.code}: ${detail.slice(0, 500)}`,
103
+ )
104
+ }
105
+ } catch (cause) {
106
+ cleanupError = cause
107
+ }
108
+ if (stageError !== undefined && cleanupError !== undefined) {
109
+ throw new AggregateError(
110
+ [stageError, cleanupError],
111
+ `materialize ${instanceId}: workspace extraction and container cleanup both failed`,
112
+ )
113
+ }
114
+ if (stageError !== undefined) throw stageError
115
+ if (cleanupError !== undefined) throw cleanupError
116
+
117
+ opts.signal?.throwIfAborted()
118
+ const gitDir = await stat(`${dest}/.git`).catch(() => null)
119
+ if (!gitDir?.isDirectory()) {
120
+ throw new Error(`materialize ${instanceId}: no-git (image ${image} has no /testbed git repo)`)
121
+ }
122
+
123
+ const gitOpts = { signal: opts.signal, timeoutMs: GIT_COMMAND_TIMEOUT_MS }
124
+ const reset = await run('git', ['-C', dest, 'reset', '-q', '--hard', baseCommit], gitOpts)
125
+ opts.signal?.throwIfAborted()
126
+ if (reset.code !== 0) {
127
+ throw new Error(`materialize ${instanceId}: reset-fail base=${baseCommit}: ${reset.stderr.slice(0, 500)}`)
128
+ }
129
+ // Tolerated failure in the bash (`|| true`): a clean error must not kill setup.
130
+ const clean = await run('git', ['-C', dest, 'clean', '-qfd'], gitOpts)
131
+ opts.signal?.throwIfAborted()
132
+ if (clean.timedOut) {
133
+ throw new Error(`materialize ${instanceId}: clean-timeout: ${(clean.stderr || clean.stdout).slice(0, 500)}`)
134
+ }
135
+
136
+ await runOk('git', ['-C', dest, 'branch', '-f', workBranch, baseCommit], gitOpts)
137
+ await runOk('git', ['-C', dest, 'checkout', '-q', workBranch], gitOpts)
138
+
139
+ const head = (await runOk('git', ['-C', dest, 'rev-parse', 'HEAD'], gitOpts)).stdout.trim()
140
+ const status = (await runOk('git', ['-C', dest, 'status', '--porcelain'], gitOpts)).stdout.trim()
141
+ return { head, clean: status.length === 0 }
142
+ }