@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,408 @@
1
+ /**
2
+ * 2-rep holdout certification — the operator-approved run that decides whether
3
+ * a would-be-KEEP winner ships. Encodes the gen-2 postmortem: the winner
4
+ * failed certification 3/6 vs 4/6 on a ONE-REP holdout with exactly one
5
+ * discordant cell — a known single-rep noise class — so the protocol now
6
+ * pins:
7
+ *
8
+ * - `holdoutRepsPerInstance` (default 2) replicate cells per instance,
9
+ * - resolved = ALL reps resolved (fail-closed, identical to the improvement
10
+ * set's AND-rule in cell-evidence.mts),
11
+ * - the certification bar compares against a SAME-PROTOCOL parent
12
+ * measurement: `config.holdoutBaseline` is either an explicit
13
+ * `{iid -> bool}` verdict map measured under this exact protocol, or
14
+ * 'measure' — the incumbent runs the same 2-rep holdout FIRST in this run.
15
+ *
16
+ * Certification rule (pre-registered, gen-2 bar unchanged in kind):
17
+ * non-regression — the candidate's AND-resolved count must be >= the parent's,
18
+ * with complete conclusive coverage on the candidate side. The improvement-set
19
+ * gate already demanded a strict gain; the holdout certifies that the gain did
20
+ * not cost held-out performance.
21
+ *
22
+ * The operator-release valve is unchanged: the outer loop always runs with
23
+ * `holdout: 'deferred'` and only reports a would-be-KEEP brief; THIS module is
24
+ * the separate, operator-fired run:
25
+ *
26
+ * tsx src/swe-arena/holdout-certify.mts <config.json> --candidate <loops-commit> [--out <dir>]
27
+ */
28
+
29
+ import { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises'
30
+ import { existsSync } from 'node:fs'
31
+ import { join } from 'node:path'
32
+ import { pathToFileURL } from 'node:url'
33
+ import process from 'node:process'
34
+ import { createSweBenchAdapter } from '../benchmarks/swe-bench.ts'
35
+ import { loadExcludes, runSupervisorArm, type SecretsEnv, type SupervisorArmSpec } from './arms.ts'
36
+ import { gatesForArmKind, waitForCapacity } from './capacity.ts'
37
+ import {
38
+ replicateCoverageComplete,
39
+ resolvedInstanceCount,
40
+ type ReplicateRun,
41
+ } from './cell-evidence.mts'
42
+ import {
43
+ acquireInstanceLock,
44
+ addEvalWorktree,
45
+ assertFrozenArm,
46
+ assertLaunchEnv,
47
+ removeEvalWorktree,
48
+ runWithPostGateClock,
49
+ type OuterLoopConfig,
50
+ } from './outer-loop.mts'
51
+ import { installProcessSignalAbort, runOk } from './proc.ts'
52
+ import { loadInstanceImages } from './run-experiment.mts'
53
+ import { createSerializedJudge, type SerializedJudge } from './serialized-judge.ts'
54
+
55
+ // ---------------------------------------------------------------------------
56
+ // Pure protocol pieces — unit-tested against synthetic replicate runs.
57
+ // ---------------------------------------------------------------------------
58
+
59
+ export const DEFAULT_HOLDOUT_REPS = 2
60
+
61
+ export function holdoutReps(config: Pick<OuterLoopConfig, 'holdoutRepsPerInstance'>): number {
62
+ const reps = config.holdoutRepsPerInstance ?? DEFAULT_HOLDOUT_REPS
63
+ if (!Number.isInteger(reps) || reps < 1) {
64
+ throw new Error(`holdout-certify: holdoutRepsPerInstance must be a positive integer, got ${JSON.stringify(reps)}`)
65
+ }
66
+ return reps
67
+ }
68
+
69
+ /** Validate an explicit same-protocol parent verdict map: every holdout
70
+ * instance must carry a boolean (a partial map cannot anchor the bar). */
71
+ export function assertHoldoutBaselineMap(
72
+ baseline: Record<string, boolean>,
73
+ holdoutInstances: string[],
74
+ ): void {
75
+ const missing = holdoutInstances.filter((iid) => typeof baseline[iid] !== 'boolean')
76
+ if (missing.length > 0) {
77
+ throw new Error(
78
+ `holdout-certify: holdoutBaseline map is missing same-protocol verdicts for: ${missing.join(', ')} — ` +
79
+ "provide all instances or use holdoutBaseline: 'measure'",
80
+ )
81
+ }
82
+ const extras = Object.keys(baseline).filter((iid) => !holdoutInstances.includes(iid))
83
+ if (extras.length > 0) {
84
+ throw new Error(`holdout-certify: holdoutBaseline names non-holdout instances: ${extras.join(', ')}`)
85
+ }
86
+ }
87
+
88
+ export interface HoldoutCertification {
89
+ candResolved: number
90
+ parentResolved: number
91
+ coverageComplete: boolean
92
+ certified: boolean
93
+ reasons: string[]
94
+ perInstance: Array<{ iid: string; candidate: boolean | null; parent: boolean | null; discordant: boolean }>
95
+ }
96
+
97
+ /** The certification decision over fail-closed AND-verdicts. Pure. */
98
+ export function decideHoldoutCertification(input: {
99
+ candidateRuns: ReplicateRun[]
100
+ /** Parent AND-verdict per instance, measured under the SAME protocol
101
+ * (reps, fail-closed rule). */
102
+ parentVerdicts: Record<string, boolean>
103
+ iids: string[]
104
+ reps: number
105
+ }): HoldoutCertification {
106
+ const { candidateRuns, parentVerdicts, iids, reps } = input
107
+ assertHoldoutBaselineMap(parentVerdicts, iids)
108
+ const candResolved = resolvedInstanceCount(candidateRuns, iids, reps)
109
+ const parentResolved = iids.filter((iid) => parentVerdicts[iid] === true).length
110
+ const coverageComplete = replicateCoverageComplete(candidateRuns, iids, reps)
111
+ const perInstance = iids.map((iid) => {
112
+ const mine = candidateRuns.filter((r) => r.iid === iid)
113
+ const candidate =
114
+ mine.length === reps && mine.every((r) => r.resolved !== null)
115
+ ? mine.every((r) => r.resolved === true)
116
+ : null
117
+ const parent = parentVerdicts[iid] ?? null
118
+ return { iid, candidate, parent, discordant: candidate !== null && parent !== null && candidate !== parent }
119
+ })
120
+ const reasons: string[] = []
121
+ if (!coverageComplete) reasons.push(`candidate coverage incomplete: not every instance has ${reps} conclusive reps`)
122
+ if (candResolved < parentResolved) {
123
+ reasons.push(`regression: candidate ${candResolved} < parent ${parentResolved} (same-protocol AND-verdicts)`)
124
+ }
125
+ const certified = coverageComplete && candResolved >= parentResolved
126
+ if (certified) reasons.push(`non-regression met: candidate ${candResolved} >= parent ${parentResolved} at ${reps} reps, fail-closed`)
127
+ return { candResolved, parentResolved, coverageComplete, certified, reasons, perInstance }
128
+ }
129
+
130
+ // ---------------------------------------------------------------------------
131
+ // The runner — real arms + the official judge, resumable per (commit,iid,rep).
132
+ // ---------------------------------------------------------------------------
133
+
134
+ export interface HoldoutCellRow {
135
+ schema: 'swe-arena.holdout-cell.v1'
136
+ at: string
137
+ commit: string
138
+ side: 'candidate' | 'parent'
139
+ iid: string
140
+ rep: number
141
+ resolved: boolean | null
142
+ verifyPass: boolean | null
143
+ wallS: number | null
144
+ runDir: string
145
+ error?: string
146
+ }
147
+
148
+ /** Read prior cells (resume): conclusive rows are reused, inconclusive re-run. */
149
+ export async function loadHoldoutCells(cellsPath: string): Promise<HoldoutCellRow[]> {
150
+ if (!existsSync(cellsPath)) return []
151
+ const raw = await readFile(cellsPath, 'utf8')
152
+ return raw
153
+ .split('\n')
154
+ .filter((l) => l.trim().length > 0)
155
+ .map((l) => JSON.parse(l) as HoldoutCellRow)
156
+ .filter((r) => r.schema === 'swe-arena.holdout-cell.v1')
157
+ }
158
+
159
+ const log = (msg: string): void => console.log(`[${new Date().toISOString().slice(11, 19)}] ${msg}`)
160
+
161
+ export async function runHoldoutCertification(
162
+ config: OuterLoopConfig,
163
+ opts: { candidateCommit: string; outDir?: string },
164
+ signal?: AbortSignal,
165
+ ): Promise<HoldoutCertification> {
166
+ signal?.throwIfAborted()
167
+ assertFrozenArm(config.arm)
168
+ const reps = holdoutReps(config)
169
+ const iids = config.holdoutInstances
170
+ if (iids.length === 0) throw new Error('holdout-certify: empty holdout set')
171
+ const outDir = opts.outDir ?? join(config.outDir, 'holdout-certification')
172
+ await mkdir(outDir, { recursive: true })
173
+ const cellsPath = join(outDir, 'cells.jsonl')
174
+
175
+ const secrets: SecretsEnv = { secretsDir: config.secretsDir, envFiles: config.envFiles }
176
+ const excludes = await loadExcludes()
177
+ const images = await loadInstanceImages(config.instanceImagesPath)
178
+ const adapter = createSweBenchAdapter()
179
+ const tasks = await adapter.loadTasks({ ids: iids, split: 'test' })
180
+ const problemById = new Map<string, string>()
181
+ for (const iid of iids) {
182
+ const task = tasks.find((t) => t.id === iid)
183
+ if (!task) throw new Error(`holdout-certify: ${iid} not found in SWE-bench_Verified`)
184
+ const problem = String(task.metadata?.problem_statement ?? '')
185
+ if (!problem) throw new Error(`holdout-certify: ${iid} has an empty problem_statement`)
186
+ if (!images[iid]) throw new Error(`holdout-certify: ${iid} has no image mapping`)
187
+ if (!existsSync(join(config.verifyDir, `${iid}.sh`))) {
188
+ throw new Error(`holdout-certify: missing verify script ${join(config.verifyDir, `${iid}.sh`)}`)
189
+ }
190
+ problemById.set(iid, problem)
191
+ }
192
+
193
+ const judge: SerializedJudge = createSerializedJudge(
194
+ config.judgeTimeoutMs !== undefined ? { timeoutMs: config.judgeTimeoutMs } : {},
195
+ )
196
+ const prior = await loadHoldoutCells(cellsPath)
197
+
198
+ const awaitGates = async (gateSignal: AbortSignal | undefined = signal): Promise<void> => {
199
+ for (const gate of gatesForArmKind('supervisor', secrets, {
200
+ ...(config.gateWaitCeilingMs !== undefined ? { waitCeilingMs: config.gateWaitCeilingMs } : {}),
201
+ ...(config.capacityModel !== undefined ? { model: config.capacityModel } : {}),
202
+ onStatus: log,
203
+ })) {
204
+ if (!(await waitForCapacity(gate, gateSignal))) throw new Error(`no capacity on ${gate.name} within ceiling`)
205
+ }
206
+ }
207
+
208
+ const runSide = async (side: 'candidate' | 'parent', commit: string): Promise<ReplicateRun[]> => {
209
+ signal?.throwIfAborted()
210
+ const runs: ReplicateRun[] = []
211
+ for (const iid of iids) {
212
+ for (let rep = 0; rep < reps; rep++) {
213
+ signal?.throwIfAborted()
214
+ const cached = prior.find(
215
+ (r) => r.side === side && r.commit === commit && r.iid === iid && r.rep === rep && r.resolved !== null,
216
+ )
217
+ if (cached) {
218
+ log(`holdout ${side} ${iid} rep=${rep}: cached resolved=${cached.resolved}`)
219
+ runs.push({ iid, resolved: cached.resolved })
220
+ continue
221
+ }
222
+ const tag = `${side}-${commit.slice(0, 10)}`
223
+ const evalWt = join(outDir, 'eval-wt', `${tag}-${iid}-r${rep}`)
224
+ const armOutDir = join(outDir, 'arm-runs', tag, iid, `rep-${rep}`)
225
+ let row: HoldoutCellRow
226
+ try {
227
+ try {
228
+ await addEvalWorktree(config.loopsRepo, commit, evalWt, signal)
229
+ const spec: SupervisorArmSpec = {
230
+ kind: 'supervisor',
231
+ name: config.armName,
232
+ workerModel: config.arm.workerModel,
233
+ driverModel: config.arm.driverModel,
234
+ budget: config.arm.budget,
235
+ maxSandboxes: config.arm.maxSandboxes,
236
+ maxUsd: config.arm.maxUsd,
237
+ maxDepth: config.arm.maxDepth,
238
+ ...(config.arm.envKnobs ? { envKnobs: config.arm.envKnobs } : {}),
239
+ loopsRepo: evalWt,
240
+ extensionPath: join(evalWt, 'extensions', 'pi', 'loops.ts'),
241
+ timeoutMs: config.arm.timeoutMs,
242
+ }
243
+ log(`>>> holdout ${side} ${iid} rep=${rep} @ ${commit.slice(0, 10)}`)
244
+ const entry = images[iid]!
245
+ const { armRes, verdict } = await runWithPostGateClock({
246
+ awaitGates,
247
+ work: async (signal) => {
248
+ const armRes = await runSupervisorArm(spec, {
249
+ instanceId: iid,
250
+ image: entry.image,
251
+ baseCommit: entry.base_commit,
252
+ problemStatement: problemById.get(iid)!,
253
+ verifyCmd: `bash ${join(config.verifyDir, `${iid}.sh`)}`,
254
+ outDir: armOutDir,
255
+ secrets,
256
+ excludes,
257
+ signal,
258
+ })
259
+ signal.throwIfAborted()
260
+ const verdict = await judge.judge(iid, armRes.patchPath, `holdout-${tag}`, signal)
261
+ return { armRes, verdict }
262
+ },
263
+ timeoutMs: config.dispatchTimeoutMs,
264
+ label: `holdout ${side} ${iid} r${rep}`,
265
+ signal,
266
+ })
267
+ row = {
268
+ schema: 'swe-arena.holdout-cell.v1',
269
+ at: new Date().toISOString(),
270
+ commit,
271
+ side,
272
+ iid,
273
+ rep,
274
+ resolved: verdict.resolved,
275
+ verifyPass: armRes.verify_pass,
276
+ wallS: armRes.wall_s,
277
+ runDir: join(armOutDir, 'runs', iid, config.armName),
278
+ ...(verdict.resolved === null ? { error: verdict.error ?? 'inconclusive judge verdict' } : {}),
279
+ }
280
+ } finally {
281
+ await removeEvalWorktree(config.loopsRepo, evalWt)
282
+ }
283
+ } catch (cause) {
284
+ if (signal?.aborted) throw cause
285
+ // An errored cell is an INCONCLUSIVE replicate (resolved: null) —
286
+ // fail-closed downstream, never a fabricated boolean.
287
+ row = {
288
+ schema: 'swe-arena.holdout-cell.v1',
289
+ at: new Date().toISOString(),
290
+ commit,
291
+ side,
292
+ iid,
293
+ rep,
294
+ resolved: null,
295
+ verifyPass: null,
296
+ wallS: null,
297
+ runDir: armOutDir,
298
+ error: (cause as Error).message,
299
+ }
300
+ }
301
+ await appendFile(cellsPath, JSON.stringify(row) + '\n')
302
+ log(`holdout ${side} ${iid} rep=${rep}: resolved=${row.resolved}${row.error ? ` (${row.error})` : ''}`)
303
+ runs.push({ iid, resolved: row.resolved })
304
+ }
305
+ }
306
+ return runs
307
+ }
308
+
309
+ // SAME-PROTOCOL parent verdicts: an explicit operator-provided map, or the
310
+ // incumbent measured FIRST under the identical 2-rep fail-closed protocol.
311
+ let parentVerdicts: Record<string, boolean>
312
+ let parentSource: 'provided' | 'measured'
313
+ let parentCommit: string | null = null
314
+ const baseline = config.holdoutBaseline ?? 'measure'
315
+ if (baseline !== 'measure') {
316
+ assertHoldoutBaselineMap(baseline, iids)
317
+ parentVerdicts = baseline
318
+ parentSource = 'provided'
319
+ } else {
320
+ parentCommit = (
321
+ await runOk('git', ['-C', config.loopsRepo, 'rev-parse', config.loopsBaseRef], { signal })
322
+ ).stdout.trim()
323
+ log(`holdout parent: measuring incumbent ${parentCommit.slice(0, 10)} under the same ${reps}-rep protocol`)
324
+ const parentRuns = await runSide('parent', parentCommit)
325
+ parentVerdicts = {}
326
+ for (const iid of iids) {
327
+ const mine = parentRuns.filter((r) => r.iid === iid)
328
+ // Fail-closed: an inconclusive/missing parent replicate reads as NOT
329
+ // resolved for the parent — it can only make the bar EASIER, never
330
+ // stricter, so a broken parent measurement cannot fail a good candidate.
331
+ parentVerdicts[iid] = mine.length === reps && mine.every((r) => r.resolved === true)
332
+ }
333
+ parentSource = 'measured'
334
+ }
335
+
336
+ const candidateRuns = await runSide('candidate', opts.candidateCommit)
337
+ signal?.throwIfAborted()
338
+ const decision = decideHoldoutCertification({ candidateRuns, parentVerdicts, iids, reps })
339
+
340
+ const record = {
341
+ schema: 'swe-arena.holdout-certification.v1',
342
+ at: new Date().toISOString(),
343
+ round: config.round,
344
+ reps,
345
+ instances: iids,
346
+ candidateCommit: opts.candidateCommit,
347
+ parent: { source: parentSource, commit: parentCommit, verdicts: parentVerdicts },
348
+ ...decision,
349
+ }
350
+ const recordPath = join(outDir, `certification-${opts.candidateCommit.slice(0, 10)}.json`)
351
+ await writeFile(recordPath, JSON.stringify(record, null, 2))
352
+ log(
353
+ `holdout certification: candidate ${decision.candResolved}/${iids.length} vs parent ` +
354
+ `${decision.parentResolved}/${iids.length} at ${reps} reps — ${decision.certified ? 'CERTIFIED' : 'NOT CERTIFIED'}`,
355
+ )
356
+ for (const r of decision.reasons) log(` - ${r}`)
357
+ log(`certification record → ${recordPath}`)
358
+ signal?.throwIfAborted()
359
+ return decision
360
+ }
361
+
362
+ // ---------------------------------------------------------------------------
363
+ // CLI.
364
+ // ---------------------------------------------------------------------------
365
+
366
+ const isMain = process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href
367
+
368
+ if (isMain) {
369
+ const interrupt = installProcessSignalAbort('holdout-certify')
370
+ try {
371
+ const argv = process.argv.slice(2)
372
+ const configPath = argv[0]
373
+ const flag = (name: string): string | undefined => {
374
+ const i = argv.indexOf(name)
375
+ return i !== -1 ? argv[i + 1] : undefined
376
+ }
377
+ const candidate = flag('--candidate')
378
+ if (!configPath || configPath.startsWith('--') || !candidate) {
379
+ console.error(
380
+ 'usage: tsx src/swe-arena/holdout-certify.mts <config.json> --candidate <loops-commit> [--out <dir>] # SPENDS: arms + judges',
381
+ )
382
+ process.exit(2)
383
+ }
384
+ const config = JSON.parse(await readFile(configPath, 'utf8')) as OuterLoopConfig
385
+ assertLaunchEnv()
386
+ interrupt.signal.throwIfAborted()
387
+ const out = flag('--out')
388
+ const lockDir = out ?? join(config.outDir, 'holdout-certification')
389
+ await mkdir(lockDir, { recursive: true })
390
+ const lock = await acquireInstanceLock(lockDir)
391
+ try {
392
+ const decision = await runHoldoutCertification(config, {
393
+ candidateCommit: candidate,
394
+ ...(out ? { outDir: out } : {}),
395
+ }, interrupt.signal)
396
+ interrupt.signal.throwIfAborted()
397
+ process.exitCode = decision.certified ? 0 : 1
398
+ } finally {
399
+ await lock.release()
400
+ }
401
+ } catch (cause) {
402
+ if (!interrupt.signal.aborted) throw cause
403
+ const detail = cause instanceof Error ? cause.message : String(cause)
404
+ console.error(`holdout-certify stopped after cleanup: ${detail}`)
405
+ } finally {
406
+ interrupt.dispose()
407
+ }
408
+ }
@@ -0,0 +1,160 @@
1
+ import { mkdtemp, rm, writeFile } from 'node:fs/promises'
2
+ import { tmpdir } from 'node:os'
3
+ import { join } from 'node:path'
4
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest'
5
+ import type { ReplicateRun } from './cell-evidence.mts'
6
+ import {
7
+ assertHoldoutBaselineMap,
8
+ decideHoldoutCertification,
9
+ DEFAULT_HOLDOUT_REPS,
10
+ holdoutReps,
11
+ loadHoldoutCells,
12
+ type HoldoutCellRow,
13
+ } from './holdout-certify.mts'
14
+
15
+ const IIDS = ['a', 'b', 'c']
16
+
17
+ const runs = (spec: Record<string, Array<boolean | null>>): ReplicateRun[] =>
18
+ Object.entries(spec).flatMap(([iid, reps]) => reps.map((resolved) => ({ iid, resolved })))
19
+
20
+ describe('holdoutReps', () => {
21
+ it('defaults to 2 — the gen-2 postmortem protocol', () => {
22
+ expect(DEFAULT_HOLDOUT_REPS).toBe(2)
23
+ expect(holdoutReps({})).toBe(2)
24
+ expect(holdoutReps({ holdoutRepsPerInstance: 3 })).toBe(3)
25
+ })
26
+
27
+ it('rejects non-positive/non-integer reps', () => {
28
+ expect(() => holdoutReps({ holdoutRepsPerInstance: 0 })).toThrow(/positive integer/)
29
+ expect(() => holdoutReps({ holdoutRepsPerInstance: 1.5 })).toThrow(/positive integer/)
30
+ })
31
+ })
32
+
33
+ describe('assertHoldoutBaselineMap', () => {
34
+ it('requires a same-protocol verdict for EVERY holdout instance', () => {
35
+ expect(() => assertHoldoutBaselineMap({ a: true }, IIDS)).toThrow(/missing same-protocol verdicts.*b, c/)
36
+ })
37
+
38
+ it('rejects verdicts for non-holdout instances', () => {
39
+ expect(() => assertHoldoutBaselineMap({ a: true, b: false, c: true, z: true }, IIDS)).toThrow(/non-holdout/)
40
+ })
41
+
42
+ it('accepts a complete map', () => {
43
+ expect(() => assertHoldoutBaselineMap({ a: true, b: false, c: true }, IIDS)).not.toThrow()
44
+ })
45
+ })
46
+
47
+ describe('decideHoldoutCertification — 2-rep fail-closed aggregation', () => {
48
+ const parent = { a: true, b: false, c: true } // parent 2/3 same-protocol
49
+
50
+ it('an instance resolves only when BOTH reps resolve (T/F counts as unresolved)', () => {
51
+ const d = decideHoldoutCertification({
52
+ candidateRuns: runs({ a: [true, true], b: [true, false], c: [true, true] }),
53
+ parentVerdicts: parent,
54
+ iids: IIDS,
55
+ reps: 2,
56
+ })
57
+ expect(d.candResolved).toBe(2) // a + c; b's discordant pair is fail-closed
58
+ expect(d.parentResolved).toBe(2)
59
+ expect(d.coverageComplete).toBe(true)
60
+ expect(d.certified).toBe(true) // non-regression: 2 >= 2
61
+ expect(d.perInstance.find((p) => p.iid === 'b')).toMatchObject({ candidate: false, parent: false, discordant: false })
62
+ })
63
+
64
+ it('regression fails certification even with complete coverage', () => {
65
+ const d = decideHoldoutCertification({
66
+ candidateRuns: runs({ a: [true, true], b: [false, false], c: [false, true] }),
67
+ parentVerdicts: parent,
68
+ iids: IIDS,
69
+ reps: 2,
70
+ })
71
+ expect(d.candResolved).toBe(1)
72
+ expect(d.certified).toBe(false)
73
+ expect(d.reasons.join(' ')).toMatch(/regression: candidate 1 < parent 2/)
74
+ expect(d.perInstance.find((p) => p.iid === 'c')).toMatchObject({ candidate: false, parent: true, discordant: true })
75
+ })
76
+
77
+ it('an inconclusive replicate (errored cell) blocks coverage and certification — fail-closed', () => {
78
+ const d = decideHoldoutCertification({
79
+ candidateRuns: runs({ a: [true, true], b: [false, false], c: [true, null] }),
80
+ parentVerdicts: parent,
81
+ iids: IIDS,
82
+ reps: 2,
83
+ })
84
+ expect(d.coverageComplete).toBe(false)
85
+ expect(d.certified).toBe(false)
86
+ expect(d.reasons.join(' ')).toMatch(/coverage incomplete/)
87
+ expect(d.perInstance.find((p) => p.iid === 'c')).toMatchObject({ candidate: null, discordant: false })
88
+ })
89
+
90
+ it('a missing replicate (only 1 of 2 reps ran) blocks coverage', () => {
91
+ const d = decideHoldoutCertification({
92
+ candidateRuns: runs({ a: [true, true], b: [true, true], c: [true] }),
93
+ parentVerdicts: parent,
94
+ iids: IIDS,
95
+ reps: 2,
96
+ })
97
+ expect(d.coverageComplete).toBe(false)
98
+ expect(d.certified).toBe(false)
99
+ })
100
+
101
+ it('gen-2 shape: one discordant instance under 1-rep would have failed; the same data at 2 reps needs both reps', () => {
102
+ // At 1 rep a single flipped cell decided the gen-2 verdict. The 2-rep
103
+ // protocol requires the flip to REPLICATE before it counts either way.
104
+ const oneRep = decideHoldoutCertification({
105
+ candidateRuns: runs({ a: [true], b: [false], c: [false] }),
106
+ parentVerdicts: parent,
107
+ iids: IIDS,
108
+ reps: 1,
109
+ })
110
+ expect(oneRep.certified).toBe(false) // 1 < 2 — the gen-2 outcome
111
+ const twoRep = decideHoldoutCertification({
112
+ candidateRuns: runs({ a: [true, true], b: [false, false], c: [true, true] }),
113
+ parentVerdicts: parent,
114
+ iids: IIDS,
115
+ reps: 2,
116
+ })
117
+ expect(twoRep.certified).toBe(true) // c held up under replication
118
+ })
119
+
120
+ it('validates the parent map before deciding', () => {
121
+ expect(() =>
122
+ decideHoldoutCertification({
123
+ candidateRuns: runs({ a: [true, true] }),
124
+ parentVerdicts: { a: true },
125
+ iids: IIDS,
126
+ reps: 2,
127
+ }),
128
+ ).toThrow(/missing same-protocol verdicts/)
129
+ })
130
+ })
131
+
132
+ describe('loadHoldoutCells', () => {
133
+ let dir: string
134
+ beforeEach(async () => {
135
+ dir = await mkdtemp(join(tmpdir(), 'holdout-cells-'))
136
+ })
137
+ afterEach(async () => {
138
+ await rm(dir, { recursive: true, force: true })
139
+ })
140
+
141
+ it('returns [] for a missing file and round-trips schema-valid rows', async () => {
142
+ const path = join(dir, 'cells.jsonl')
143
+ expect(await loadHoldoutCells(path)).toEqual([])
144
+ const row: HoldoutCellRow = {
145
+ schema: 'swe-arena.holdout-cell.v1',
146
+ at: new Date(0).toISOString(),
147
+ commit: 'abc123',
148
+ side: 'candidate',
149
+ iid: 'a',
150
+ rep: 0,
151
+ resolved: true,
152
+ verifyPass: true,
153
+ wallS: 100,
154
+ runDir: '/tmp/x',
155
+ }
156
+ await writeFile(path, `${JSON.stringify(row)}\n${JSON.stringify({ schema: 'other' })}\n`)
157
+ const rows = await loadHoldoutCells(path)
158
+ expect(rows).toEqual([row]) // foreign schemas are dropped
159
+ })
160
+ })
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Judge child entrypoint — the experiment's `judge.mts`, tracked. One patch,
3
+ * one official swebench verdict, printed as a single `JUDGE_RESULT {...}` line
4
+ * that serialized-judge.ts parses. Runs as a CHILD process (not in-process) so
5
+ * the judge ceiling can SIGKILL a hung swebench run without taking the
6
+ * experiment down, exactly like the bash `timeout N node judge.mts`.
7
+ *
8
+ * usage: node --import tsx src/swe-arena/judge-child.mts <instance_id> <patchPath>
9
+ */
10
+
11
+ import { readFileSync } from 'node:fs'
12
+ import { createSweBenchAdapter } from '../benchmarks/swe-bench.ts'
13
+
14
+ const [, , iid, patchPath] = process.argv
15
+ if (!iid || !patchPath) {
16
+ console.error('usage: node --import tsx judge-child.mts <instance_id> <patchPath>')
17
+ process.exit(2)
18
+ }
19
+ const patch = readFileSync(patchPath, 'utf8')
20
+ const adapter = createSweBenchAdapter()
21
+ const [task] = await adapter.loadTasks({ ids: [iid], split: 'test' })
22
+ if (!task) {
23
+ console.log(JSON.stringify({ iid, error: 'no-task' }))
24
+ process.exit(2)
25
+ }
26
+ const t0 = Date.now()
27
+ const score = await adapter.judge(task, patch)
28
+ console.log(
29
+ 'JUDGE_RESULT ' +
30
+ JSON.stringify({
31
+ iid,
32
+ resolved: score.resolved,
33
+ score: score.score,
34
+ secs: Math.round((Date.now() - t0) / 1000),
35
+ patch_bytes: patch.length,
36
+ }),
37
+ )
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Crash-orphan reconciliation for the improve-run CostLedger.
3
+ *
4
+ * A killed outer-loop process leaves its in-flight paid call as a durable
5
+ * 'pending' record with no receipt. On resume the ledger's fail-closed
6
+ * admission guard ("N unresolved call(s) must be reconciled before new paid
7
+ * work") then refuses EVERY new paid call, so a single crash permanently
8
+ * blocks the run. This module settles those orphans at startup through the
9
+ * ledger's dedicated crash-recovery verb, `CostLedger.reconcile()`.
10
+ *
11
+ * Safety contract — never settle a live run's call:
12
+ * - The caller must hold the outDir single-instance pid lock
13
+ * (`acquireInstanceLock` in outer-loop.mts) before invoking this, so no
14
+ * concurrent outer-loop shares the ledger file. Every pending record
15
+ * restored from disk is therefore from a dead process.
16
+ * - Belt and braces, only `state: 'interrupted'` pendings are touched:
17
+ * restored-from-persistence calls this process's ledger instance never
18
+ * started. An 'active'/'late' pending belongs to an in-flight
19
+ * `runPaidCall` and settles through its own path.
20
+ * - The ledger's persistence append is compare-and-swap on the file
21
+ * revision, so even an unexpected concurrent writer makes reconciliation
22
+ * fail loud (`CostCallConflictError`) instead of corrupting the log.
23
+ *
24
+ * The orphan settles as a FAILED receipt with zero usage and a fully-known
25
+ * $0 actual cost (`actualCostUsd: 0`), reason 'process-crash-orphan'. A
26
+ * `costUnknown`/`usageUnknown` receipt would be marginally more honest about
27
+ * the crashed call's true spend, but an unknown-cost receipt marks the
28
+ * ledger's accounting incomplete forever, which blocks all paid work in
29
+ * capped runs — the same permanent lockout this module exists to fix.
30
+ */
31
+
32
+ import { existsSync } from 'node:fs'
33
+ import { join } from 'node:path'
34
+ import type { CostReceipt, PendingCostCallView } from '@tangle-network/agent-eval'
35
+ import { createRunCostLedger, fsCampaignStorage } from '@tangle-network/agent-eval/campaign'
36
+
37
+ export const CRASH_ORPHAN_REASON = 'process-crash-orphan'
38
+
39
+ /** The two ledger verbs reconciliation needs, structural for testability. */
40
+ export interface OrphanReconcilableLedger {
41
+ listPending(): PendingCostCallView[]
42
+ reconcile(
43
+ callId: string,
44
+ observed: {
45
+ model: string
46
+ inputTokens: number
47
+ outputTokens: number
48
+ actualCostUsd?: number
49
+ },
50
+ options?: { error?: string },
51
+ ): CostReceipt
52
+ }
53
+
54
+ /** Settle every crash-orphaned ('interrupted') pending call as a $0 failure. */
55
+ export function reconcileCrashOrphanCalls(ledger: OrphanReconcilableLedger): CostReceipt[] {
56
+ return ledger
57
+ .listPending()
58
+ .filter((pending) => pending.state === 'interrupted')
59
+ .map((pending) =>
60
+ ledger.reconcile(
61
+ pending.callId,
62
+ { model: pending.model, inputTokens: 0, outputTokens: 0, actualCostUsd: 0 },
63
+ { error: CRASH_ORPHAN_REASON },
64
+ ),
65
+ )
66
+ }
67
+
68
+ /**
69
+ * Open the durable ledger under `improveRunDir` and settle crash orphans.
70
+ * No-op (empty result) when no ledger file exists yet — a fresh run.
71
+ * PRECONDITION: the caller holds the outDir instance lock (see module doc).
72
+ */
73
+ export function reconcileCrashOrphansOnDisk(improveRunDir: string): CostReceipt[] {
74
+ if (!existsSync(join(improveRunDir, 'cost-ledger.jsonl'))) return []
75
+ const ledger = createRunCostLedger({ storage: fsCampaignStorage(), runDir: improveRunDir })
76
+ return reconcileCrashOrphanCalls(ledger)
77
+ }