@tangle-network/agent-bench 0.3.6 → 0.3.7

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 (91) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/dist/adapters.js +2 -2
  3. package/dist/benchmarks/humaneval.d.ts +10 -1
  4. package/dist/benchmarks/humaneval.js +5 -3
  5. package/dist/{chunk-PPYSEKFM.js → chunk-5H5XV76F.js} +73 -15
  6. package/dist/chunk-5H5XV76F.js.map +1 -0
  7. package/dist/{chunk-5SBJCB6W.js → chunk-PWQVGAJB.js} +2 -2
  8. package/dist/index.js +2 -2
  9. package/package.json +5 -4
  10. package/scripts/run-package-tests.mjs +30 -8
  11. package/scripts/verify-pier-agent.mts +1 -0
  12. package/src/benchmarks/humaneval.test.mts +122 -0
  13. package/src/benchmarks/humaneval.ts +100 -27
  14. package/src/david-attribution.mts +78 -0
  15. package/src/david-goliath.mts +149 -0
  16. package/src/hev-improve.mts +25 -6
  17. package/src/humaneval-object-ablation.mts +201 -0
  18. package/src/live-improve-campaign-mbpp.mts +641 -0
  19. package/src/live-improve-campaign.mts +500 -0
  20. package/src/mbpp-structural.mts +12 -7
  21. package/src/stream-observe.py +45 -0
  22. package/src/stream-observe.tpl.html +247 -0
  23. package/src/supervisor-arena.mts +816 -0
  24. package/src/swe-arena/analyze.ts +211 -0
  25. package/src/swe-arena/arms.ts +788 -0
  26. package/src/swe-arena/bootstrap-meta.mts +188 -0
  27. package/src/swe-arena/bootstrap-meta.test.mts +51 -0
  28. package/src/swe-arena/calibrate.ts +116 -0
  29. package/src/swe-arena/capabilities.mts +76 -0
  30. package/src/swe-arena/capabilities.test.mts +57 -0
  31. package/src/swe-arena/capacity.ts +194 -0
  32. package/src/swe-arena/cell-evidence.mts +405 -0
  33. package/src/swe-arena/cell-evidence.test.mts +248 -0
  34. package/src/swe-arena/diagnosis-ensemble.test.mts +210 -0
  35. package/src/swe-arena/diagnosis-ensemble.ts +520 -0
  36. package/src/swe-arena/execution.test.mts +1170 -0
  37. package/src/swe-arena/fixtures/analyze.py +80 -0
  38. package/src/swe-arena/fixtures/excludes.txt +8 -0
  39. package/src/swe-arena/fixtures/gen1-salvage/README.md +45 -0
  40. package/src/swe-arena/fixtures/gen1-salvage/cand0-e6d7361.diff +116 -0
  41. package/src/swe-arena/fixtures/gen1-salvage/cand1-76a8590.diff +293 -0
  42. package/src/swe-arena/fixtures/holdout-preregister.log +12 -0
  43. package/src/swe-arena/fixtures/holdout.json +44 -0
  44. package/src/swe-arena/fixtures/instances.json +146 -0
  45. package/src/swe-arena/fixtures/ledger.jsonl +12 -0
  46. package/src/swe-arena/fixtures/patches/pallets__flask-5014.solo.patch +36 -0
  47. package/src/swe-arena/fixtures/patches/pydata__xarray-4687.sup.patch +33 -0
  48. package/src/swe-arena/fixtures/rejudge.jsonl +15 -0
  49. package/src/swe-arena/fixtures/rematch.jsonl +3 -0
  50. package/src/swe-arena/fixtures/rematch2.jsonl +3 -0
  51. package/src/swe-arena/fixtures/rematch3.jsonl +3 -0
  52. package/src/swe-arena/fixtures/sup-journal-true.json +19 -0
  53. package/src/swe-arena/fixtures/verify/astropy__astropy-13033.sh +48 -0
  54. package/src/swe-arena/fixtures/verify/django__django-11532.sh +50 -0
  55. package/src/swe-arena/fixtures/verify/matplotlib__matplotlib-20826.sh +76 -0
  56. package/src/swe-arena/fixtures/verify/pydata__xarray-4687.sh +44 -0
  57. package/src/swe-arena/fixtures/verify/pytest-dev__pytest-6197.sh +32 -0
  58. package/src/swe-arena/fixtures/verify/sphinx-doc__sphinx-9658.sh +51 -0
  59. package/src/swe-arena/fixtures/worker-tokens.json +42 -0
  60. package/src/swe-arena/fixtures.ts +104 -0
  61. package/src/swe-arena/holdout-certify.mts +408 -0
  62. package/src/swe-arena/holdout-certify.test.mts +160 -0
  63. package/src/swe-arena/judge-child.mts +37 -0
  64. package/src/swe-arena/manifest.mts +293 -0
  65. package/src/swe-arena/manifest.test.mts +169 -0
  66. package/src/swe-arena/materialize.ts +142 -0
  67. package/src/swe-arena/outer-loop.mts +2145 -0
  68. package/src/swe-arena/outer-loop.test.mts +696 -0
  69. package/src/swe-arena/parity.test.mts +87 -0
  70. package/src/swe-arena/proc.test.mts +174 -0
  71. package/src/swe-arena/proc.ts +260 -0
  72. package/src/swe-arena/profiles/default-author.profile.json +4 -0
  73. package/src/swe-arena/proposer-fanout.mts +489 -0
  74. package/src/swe-arena/proposer-fanout.test.mts +372 -0
  75. package/src/swe-arena/reconcile.ts +0 -0
  76. package/src/swe-arena/replay.mts +183 -0
  77. package/src/swe-arena/replay.test.mts +300 -0
  78. package/src/swe-arena/run-experiment.mts +361 -0
  79. package/src/swe-arena/run-supervisor.mjs +297 -0
  80. package/src/swe-arena/run-supervisor.test.mts +498 -0
  81. package/src/swe-arena/serialized-judge.ts +414 -0
  82. package/src/swe-arena/types.ts +166 -0
  83. package/src/swe-code-improve.mts +328 -0
  84. package/src/swe-emit-patch.mts +104 -0
  85. package/src/swe-improve.mts +232 -0
  86. package/src/swe-jail.ts +2 -2
  87. package/src/swe-local-proof.mts +169 -0
  88. package/src/swe-repro-calibrate.mts +446 -0
  89. package/src/swe-stream.mts +1497 -0
  90. package/dist/chunk-PPYSEKFM.js.map +0 -1
  91. /package/dist/{chunk-5SBJCB6W.js.map → chunk-PWQVGAJB.js.map} +0 -0
@@ -0,0 +1,300 @@
1
+ /**
2
+ * Proof-of-faithfulness gate for the swe-arena replay module.
3
+ *
4
+ * Every expected value below was produced by running the reference
5
+ * implementation (`fixtures/analyze.py`) against the committed fixtures on
6
+ * 2026-07-15 and captured verbatim — the typed port must reproduce it exactly
7
+ * before any typed execution path is built on top.
8
+ *
9
+ * KNOWN, DELIBERATE DIVERGENCE (flagged, both sides pinned): analyze.py's
10
+ * printed "SUP total tokens: 560,554 / 0.83x" counts the supervisor BRAIN
11
+ * only (journal metered events). The true SUP-arm spend adds worker-session
12
+ * tokens (worker-tokens.json): 560,554 + 1,161,836 = 1,722,390 → 2.55x
13
+ * SOLO. Both rollups are pinned; neither replaces the other.
14
+ */
15
+
16
+ import { createHash } from 'node:crypto'
17
+ import { describe, expect, it } from 'vitest'
18
+ import {
19
+ costRollup,
20
+ ledgerOutcomes,
21
+ pairedSignTest,
22
+ reconciledOutcomes,
23
+ roundsProgression,
24
+ splitPairs,
25
+ } from './analyze.ts'
26
+ import {
27
+ loadHoldout,
28
+ loadLedger,
29
+ loadPreregisterLog,
30
+ loadRejudge,
31
+ loadRematchRounds,
32
+ loadSupJournalTrue,
33
+ loadWorkerTokens,
34
+ readFixture,
35
+ } from './fixtures.ts'
36
+ import { applyRejudge, reconcile } from './reconcile.ts'
37
+ import { buildReplay, renderReplay } from './replay.mts'
38
+
39
+ const DISCORDANT = [
40
+ 'astropy__astropy-13033',
41
+ 'django__django-11532',
42
+ 'matplotlib__matplotlib-20826',
43
+ ]
44
+
45
+ describe('fixture integrity', () => {
46
+ // The fixtures ARE the experiment record. Any byte drift invalidates every
47
+ // pinned number below, so drift must fail loudly here first.
48
+ const sha256 = (name: string): string =>
49
+ createHash('sha256').update(readFixture(name)).digest('hex')
50
+
51
+ it.each([
52
+ ['ledger.jsonl', '0014a1a2e7432a6551edbaf6668357cdbee8adb15b92e4f48ff530daf6ab8529'],
53
+ ['rejudge.jsonl', '71ecadde0925d573573a7bb0fe171d26da386149f693035d3ca47c983a5f1700'],
54
+ ['rematch.jsonl', 'aac48fdaa3c80f08367c220e406e1bb28b09c4f7d74fd17e4b76f50b5caaa5e4'],
55
+ ['rematch2.jsonl', 'fe8347eae3e3f48c838cca0aa37e835730520482b705038c19450c98edd54d54'],
56
+ ['rematch3.jsonl', '4eaeb9916634f3ffea7f66cb3bf747040a346524602a74a537efcdbc828ff020'],
57
+ ['holdout.json', '56938f7c509621bcadbd50b1d6dacbee0f63b350506795e45d785c9de37d93f2'],
58
+ ['worker-tokens.json', 'aa2f394120984a1c21ea7b70ed830a990477c08a1b38b6db743024660b43b129'],
59
+ ['sup-journal-true.json', 'a95b48bdd7ab46011355c6a2b2844d67aa5811235ed3b8a5c9a4c9342eff9784'],
60
+ ['analyze.py', '5512f4e1732ae4f0f92d7cb92840e5e99e54073c27f2b8ebd293b75346d9ebfc'],
61
+ ['holdout-preregister.log', 'e11fbf34840765d8cd452c870905acec67e5a6b9dc05c2f76c64f71c2ad70884'],
62
+ ])('%s is byte-identical to the captured artifact', (name, expected) => {
63
+ expect(sha256(name)).toBe(expected)
64
+ })
65
+
66
+ it('loads the expected row counts', () => {
67
+ expect(loadLedger()).toHaveLength(12)
68
+ expect(loadRejudge()).toHaveLength(15)
69
+ expect(loadRematchRounds().map((r) => r.length)).toEqual([3, 3, 3])
70
+ })
71
+
72
+ it('psf__requests-1766 carries the corrected-sup-verdict note', () => {
73
+ const row = loadLedger().find((r) => r.iid === 'psf__requests-1766')
74
+ expect(row?.sup_resolved).toBe(true)
75
+ expect(row?._note).toMatch(/re-judged 2x stable resolved=true/)
76
+ })
77
+ })
78
+
79
+ describe('reconcile: rejudge overrides + gold gate', () => {
80
+ const table = reconcile(loadLedger(), loadRejudge())
81
+
82
+ it('excludes exactly the gold-ungradeable instances 2317 + 2931', () => {
83
+ expect(table.excluded.map((e) => e.iid)).toEqual(['psf__requests-2317', 'psf__requests-2931'])
84
+ expect(table.excluded.map((e) => e.excludeReason)).toEqual([
85
+ 'gold patch unresolved by judge (gold2) — instance ungradeable',
86
+ 'gold patch unresolved by judge (gold) — instance ungradeable',
87
+ ])
88
+ expect(table.valid).toHaveLength(10)
89
+ })
90
+
91
+ it('gold-control (flask) grades true and stays in the denominator', () => {
92
+ const flask = table.valid.find((r) => r.iid === 'pallets__flask-5014')
93
+ expect(flask?.goldStatus).toBe('gradeable')
94
+ expect(flask?.excluded).toBe(false)
95
+ })
96
+
97
+ it('parse-error rejudge rows (resolved=null) never override; final2 retries do', () => {
98
+ const r2317 = applyRejudge(loadLedger(), loadRejudge()).find(
99
+ (r) => r.iid === 'psf__requests-2317',
100
+ )
101
+ // solo-final and sup-final on 2317 both failed to parse; the *-final2
102
+ // retries are the authoritative rows.
103
+ expect(r2317?.solo).toEqual({ resolved: false, source: 'solo-final2' })
104
+ expect(r2317?.sup).toEqual({ resolved: false, source: 'sup-final2' })
105
+ // gold parse error superseded by the conclusive gold2 retry → ungradeable.
106
+ expect(r2317?.goldStatus).toBe('ungradeable')
107
+ })
108
+
109
+ it('personal re-judges override the automated verdict for their arm only', () => {
110
+ const byIid = new Map(applyRejudge(loadLedger(), loadRejudge()).map((r) => [r.iid, r]))
111
+ for (const iid of DISCORDANT) {
112
+ expect(byIid.get(iid)?.solo).toEqual({ resolved: true, source: 'solo-final' })
113
+ expect(byIid.get(iid)?.sup.source).toBe('ledger')
114
+ }
115
+ expect(byIid.get('pydata__xarray-4687')?.solo).toEqual({
116
+ resolved: false,
117
+ source: 'solo-final',
118
+ })
119
+ expect(byIid.get('pydata__xarray-4687')?.sup).toEqual({ resolved: false, source: 'sup-final' })
120
+ })
121
+ })
122
+
123
+ describe('analyze: raw ledger reproduction of analyze.py', () => {
124
+ const outcomes = ledgerOutcomes(loadLedger())
125
+ const split = splitPairs(outcomes)
126
+ const sign = pairedSignTest(outcomes)
127
+
128
+ it('SOLO 7/12, SUP 4/12', () => {
129
+ expect(outcomes.filter((o) => o.solo)).toHaveLength(7)
130
+ expect(outcomes.filter((o) => o.sup)).toHaveLength(4)
131
+ })
132
+
133
+ it('discordant pairs: 3 SOLO-only, 0 SUP-only', () => {
134
+ expect(split.soloOnly).toEqual(DISCORDANT)
135
+ expect(split.supOnly).toEqual([])
136
+ expect(split.both).toHaveLength(4)
137
+ expect(split.neither).toEqual([
138
+ 'psf__requests-2317',
139
+ 'psf__requests-2931',
140
+ 'pydata__xarray-4687',
141
+ 'pytest-dev__pytest-6197',
142
+ 'sphinx-doc__sphinx-9658',
143
+ ])
144
+ })
145
+
146
+ it('exact two-sided sign test p = 0.25 (agent-eval mcnemar)', () => {
147
+ expect(sign.b).toBe(0)
148
+ expect(sign.c).toBe(3)
149
+ expect(sign.nDiscordant).toBe(3)
150
+ expect(sign.pValue).toBeCloseTo(0.25, 10)
151
+ expect(sign.pValue.toFixed(4)).toBe('0.2500')
152
+ })
153
+ })
154
+
155
+ describe('analyze: valid-denominator verdict', () => {
156
+ const outcomes = reconciledOutcomes(reconcile(loadLedger(), loadRejudge()).valid)
157
+
158
+ it('SOLO 7/10, SUP 4/10 after excluding 2931 + 2317', () => {
159
+ expect(outcomes).toHaveLength(10)
160
+ expect(outcomes.filter((o) => o.solo)).toHaveLength(7)
161
+ expect(outcomes.filter((o) => o.sup)).toHaveLength(4)
162
+ })
163
+
164
+ it('same discordant set and p=0.25 (excluded pairs were concordant-neither)', () => {
165
+ const split = splitPairs(outcomes)
166
+ expect(split.soloOnly).toEqual(DISCORDANT)
167
+ expect(split.supOnly).toEqual([])
168
+ expect(pairedSignTest(outcomes).pValue).toBeCloseTo(0.25, 10)
169
+ })
170
+ })
171
+
172
+ describe('analyze: cost rollups', () => {
173
+ const cost = costRollup(loadLedger(), loadSupJournalTrue(), loadWorkerTokens())
174
+
175
+ it('SOLO total 675,412 tokens (analyze.py oracle)', () => {
176
+ expect(cost.soloTokens).toBe(675412)
177
+ })
178
+
179
+ it('SUP brain total 560,554 tokens — what analyze.py prints as "SUP total"', () => {
180
+ expect(cost.supBrainTokens).toBe(560554)
181
+ expect(cost.brainTokenRatio.toFixed(2)).toBe('0.83')
182
+ })
183
+
184
+ it('TRUE SUP total 1,722,390 = brain 560,554 + workers 1,161,836 → 2.55x SOLO', () => {
185
+ // The loudly-flagged divergence: analyze.py never printed worker tokens,
186
+ // so its 0.83x understates the SUP arm's true spend by the worker share.
187
+ expect(cost.supWorkerTokens).toBe(1161836)
188
+ expect(cost.supTotalTokens).toBe(1722390)
189
+ expect(cost.totalTokenRatio).toBeCloseTo(2.5501, 4)
190
+ expect(cost.totalTokenRatio.toFixed(2)).toBe('2.55')
191
+ })
192
+
193
+ it('USD via blended SUP rate (analyze.py oracle strings)', () => {
194
+ expect(cost.supUsd.toFixed(4)).toBe('0.1754')
195
+ expect((cost.blendedRatePerTok * 1e6).toFixed(3)).toBe('0.313')
196
+ expect(cost.soloUsdDerived.toFixed(4)).toBe('0.2114')
197
+ })
198
+
199
+ it('wall time: SOLO 3769s vs SUP 9124s → 2.42x', () => {
200
+ expect(cost.soloWallS).toBe(3769)
201
+ expect(cost.supWallS).toBe(9124)
202
+ expect(cost.wallRatio.toFixed(2)).toBe('2.42')
203
+ })
204
+
205
+ it('telemetry gaps: runtime zeroed spentTokens on the 4 no-winner/crashed runs', () => {
206
+ expect(cost.telemetryGaps).toEqual([
207
+ 'astropy__astropy-13033',
208
+ 'django__django-11532',
209
+ 'matplotlib__matplotlib-20826',
210
+ 'pytest-dev__pytest-6197',
211
+ ])
212
+ })
213
+ })
214
+
215
+ describe('analyze: supervisor evolution rounds', () => {
216
+ const rounds = roundsProgression(loadLedger(), loadRematchRounds())
217
+
218
+ it('matplotlib: 0-line unresolved at SUP round 0 → RESOLVED at SUP4', () => {
219
+ const states = rounds.get('matplotlib__matplotlib-20826')
220
+ expect(states?.map((s) => ({ round: s.round, resolved: s.resolved, patchLines: s.patchLines }))).toEqual([
221
+ { round: 'SUP', resolved: false, patchLines: 0 },
222
+ { round: 'SUP2', resolved: false, patchLines: 0 },
223
+ { round: 'SUP3', resolved: false, patchLines: 0 },
224
+ { round: 'SUP4', resolved: true, patchLines: 23 },
225
+ ])
226
+ })
227
+
228
+ it('astropy + django: never resolved across SUP..SUP4', () => {
229
+ for (const iid of ['astropy__astropy-13033', 'django__django-11532']) {
230
+ const states = rounds.get(iid)
231
+ expect(states).toHaveLength(4)
232
+ expect(states?.every((s) => !s.resolved)).toBe(true)
233
+ }
234
+ })
235
+ })
236
+
237
+ describe('holdout registry', () => {
238
+ const holdout = loadHoldout()
239
+ const log = loadPreregisterLog()
240
+
241
+ it('6 instances, all gold-verified and judge-calibrated, single selection commit', () => {
242
+ expect(holdout.entries).toHaveLength(6)
243
+ expect(holdout.selectedAtCommit).toBe('4a06fc54bd180789d1402c843a63ed245df9f8eb')
244
+ expect(holdout.entries.every((e) => e.gold_official_resolved && e.verify_calibrated)).toBe(true)
245
+ })
246
+
247
+ it('every entry was preregistered before any arm ran, then registered', () => {
248
+ const iids = holdout.entries.map((e) => e.iid)
249
+ for (const iid of iids) {
250
+ const pre = log.findIndex((l) => l.includes('PREREGISTER') && l.includes(iid))
251
+ const reg = log.findIndex((l) => l.includes('REGISTERED') && l.includes(iid))
252
+ expect(pre).toBeGreaterThanOrEqual(0)
253
+ expect(reg).toBeGreaterThan(pre)
254
+ expect(log[pre]).toContain('status=selected-before-any-arm-run')
255
+ }
256
+ })
257
+ })
258
+
259
+ describe('replay CLI output', () => {
260
+ // Lines below are verbatim from running fixtures/analyze.py on 2026-07-15
261
+ // (trailing whitespace trimmed — the per-instance table pads columns).
262
+ const lines = renderReplay(buildReplay())
263
+ .split('\n')
264
+ .map((l) => l.trimEnd())
265
+
266
+ it.each([
267
+ ['SOLO resolved: 7/12 = 58.3%'],
268
+ ['SUP resolved: 4/12 = 33.3%'],
269
+ ['delta (SUP-SOLO): -3 instances (-25.0 pts)'],
270
+ [" SOLO-only wins (SOLO✓ SUP✗): 3 ['astropy__astropy-13033', 'django__django-11532', 'matplotlib__matplotlib-20826']"],
271
+ [' SUP-only wins (SUP✓ SOLO✗): 0 []'],
272
+ [' exact two-sided sign test on discordant pairs: p=0.2500'],
273
+ ['COST (measured tokens; USD via shared blended rate $0.313/1M from SUP accounting):'],
274
+ [' SOLO total tokens: 675,412 -> derived $0.2114'],
275
+ [' SUP total tokens: 560,554 -> runtime $0.1754'],
276
+ [' SUP/SOLO token ratio: 0.83x'],
277
+ [' SUP/SOLO cost ratio (token-derived): 0.83x'],
278
+ [" [telemetry] instances where runtime spentTokens != journal-true (no-winner zeroing): ['astropy__astropy-13033', 'django__django-11532', 'matplotlib__matplotlib-20826', 'pytest-dev__pytest-6197']"],
279
+ [' WALL: SOLO 3769s total vs SUP 9124s total -> SUP 2.42x wall'],
280
+ ['pallets__flask-5014 True True T T ? 30738 15731 0.0124 116 261'],
281
+ ['astropy__astropy-13033 True False T F 3 59496 0 0.0000 350 1550'],
282
+ ['pytest-dev__pytest-6197 False False F F 0 133032 0 0.0000 755 248'],
283
+ ])('reproduces analyze.py line: %s', (expected) => {
284
+ expect(lines).toContain(expected)
285
+ })
286
+
287
+ it.each([
288
+ ['SOLO resolved: 7/10'],
289
+ ['SUP resolved: 4/10'],
290
+ [' EXCLUDED psf__requests-2317: gold patch unresolved by judge (gold2) — instance ungradeable'],
291
+ [' EXCLUDED psf__requests-2931: gold patch unresolved by judge (gold) — instance ungradeable'],
292
+ ['exact two-sided sign test: p=0.2500'],
293
+ [' brain 560,554 + workers 1,161,836 = 1,722,390 tokens'],
294
+ [' SUP/SOLO true token ratio: 2.55x (brain-only ratio: 0.83x)'],
295
+ [' matplotlib__matplotlib-20826 SUP:unresolved(0L,null) -> SUP2:unresolved(0L,no-winner) -> SUP3:unresolved(0L,null) -> SUP4:RESOLVED(23L,delivered)'],
296
+ ['HOLDOUT REGISTRY (pre-registered at loops@4a06fc54bd, untouched):'],
297
+ ])('prints reconciled line: %s', (expected) => {
298
+ expect(lines).toContain(expected)
299
+ })
300
+ })
@@ -0,0 +1,361 @@
1
+ /**
2
+ * Experiment runner CLI — the typed replacement for the experiment's
3
+ * `orchestrate.sh` + `run-instance.sh`:
4
+ *
5
+ * tsx src/swe-arena/run-experiment.mts <config.json>
6
+ * tsx src/swe-arena/run-experiment.mts --dry-run-parity [workDir]
7
+ *
8
+ * Per instance, sequentially: ledger-skip resume → endpoint capacity gates
9
+ * (supervisor arms gate on the ROUTER path too — probing z.ai alone was the
10
+ * proven blind spot) → solo arm → serialized judge → supervisor arm →
11
+ * serialized judge → append one typed LedgerRow (M1 schema) to the ledger.
12
+ *
13
+ * DRY-RUN PARITY (the M2 gate): `--dry-run-parity` executes NO arms and spends
14
+ * NO model tokens. It replays patch extraction + official judging for two
15
+ * committed fixture patches (pallets__flask-5014 SOLO — resolved;
16
+ * pydata__xarray-4687 SUP — unresolved) through materialize → apply →
17
+ * extractPatch → serialized-judge, and checks the verdicts against the pinned
18
+ * M1 fixtures. Docker time only.
19
+ *
20
+ * TODO(operator approval): full 12-instance parity re-run — re-execute both
21
+ * arms on the same 12 instances through this typed path and diff the resulting
22
+ * ledger against fixtures/ledger.jsonl. Costs ~$1 in model spend + ~4h wall;
23
+ * do not launch without an explicit operator go.
24
+ */
25
+
26
+ import { appendFile, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
27
+ import { join } from 'node:path'
28
+ import { pathToFileURL, fileURLToPath } from 'node:url'
29
+ import { createSweBenchAdapter } from '../benchmarks/swe-bench.ts'
30
+ import {
31
+ extractPatch,
32
+ loadExcludes,
33
+ runSoloArm,
34
+ runSupervisorArm,
35
+ type ExecutableArmSpec,
36
+ type SecretsEnv,
37
+ type SoloArmResult,
38
+ type SoloArmSpec,
39
+ type SupervisorArmResult,
40
+ type SupervisorArmSpec,
41
+ } from './arms.ts'
42
+ import { applyPatchWithFallback } from './calibrate.ts'
43
+ import { gatesForArmKind, waitForCapacity } from './capacity.ts'
44
+ import { materializeWorkspace } from './materialize.ts'
45
+ import {
46
+ createSerializedJudge,
47
+ type JudgeVerdict,
48
+ type SerializedJudge,
49
+ } from './serialized-judge.ts'
50
+ import type { LedgerRow } from './types.ts'
51
+
52
+ const fixturesDir = fileURLToPath(new URL('./fixtures', import.meta.url))
53
+
54
+ // ---------------------------------------------------------------------------
55
+ // Instance images (fixtures/instances.json, vendored from the experiment).
56
+ // ---------------------------------------------------------------------------
57
+
58
+ export interface InstanceImageEntry {
59
+ repo: string
60
+ base_commit: string
61
+ image: string
62
+ environment_setup_commit: string | null
63
+ }
64
+
65
+ export async function loadInstanceImages(path?: string): Promise<Record<string, InstanceImageEntry>> {
66
+ const raw = await readFile(path ?? join(fixturesDir, 'instances.json'), 'utf8')
67
+ return JSON.parse(raw) as Record<string, InstanceImageEntry>
68
+ }
69
+
70
+ // ---------------------------------------------------------------------------
71
+ // Ledger row assembly + resume.
72
+ // ---------------------------------------------------------------------------
73
+
74
+ /**
75
+ * One paired LedgerRow from the two arm results + judge verdicts — the exact
76
+ * field mapping run-instance.sh wrote. Throws on an inconclusive verdict
77
+ * (resolved: null): an infra failure must abort the pair, never be written
78
+ * into a boolean column.
79
+ */
80
+ export function buildLedgerRow(
81
+ solo: SoloArmResult,
82
+ soloVerdict: JudgeVerdict,
83
+ sup: SupervisorArmResult,
84
+ supVerdict: JudgeVerdict,
85
+ ): LedgerRow {
86
+ if (solo.iid !== sup.iid) throw new Error(`ledger row: arm iid mismatch ${solo.iid} vs ${sup.iid}`)
87
+ if (soloVerdict.resolved === null || supVerdict.resolved === null) {
88
+ throw new Error(
89
+ `ledger row ${solo.iid}: inconclusive judge verdict (solo=${soloVerdict.resolved}, sup=${supVerdict.resolved}) — not writing a fabricated boolean`,
90
+ )
91
+ }
92
+ const SUP_STATUSES = ['completed', 'running', 'failed', 'cancelled', null] as const
93
+ const SUP_VERDICTS = ['delivered', 'no-winner', 'best-effort', null] as const
94
+ if (!SUP_STATUSES.includes(sup.sup_status as (typeof SUP_STATUSES)[number])) {
95
+ throw new Error(`ledger row ${solo.iid}: unknown sup_status ${JSON.stringify(sup.sup_status)} — loops contract changed?`)
96
+ }
97
+ if (!SUP_VERDICTS.includes(sup.sup_verdict as (typeof SUP_VERDICTS)[number])) {
98
+ throw new Error(`ledger row ${solo.iid}: unknown sup_verdict ${JSON.stringify(sup.sup_verdict)} — loops contract changed?`)
99
+ }
100
+ return {
101
+ iid: solo.iid,
102
+ solo_resolved: soloVerdict.resolved,
103
+ sup_resolved: supVerdict.resolved,
104
+ solo_verify_pass: solo.verify_pass,
105
+ sup_verify_pass: sup.verify_pass,
106
+ solo_patch_lines: solo.patch_lines,
107
+ sup_patch_lines: sup.patch_lines,
108
+ solo_wall_s: solo.wall_s,
109
+ sup_wall_s: sup.wall_s,
110
+ solo_tokens: solo.usage.total_io,
111
+ solo_usage: solo.usage,
112
+ sup_spentTokens: sup.spentTokens,
113
+ sup_spentUsd: sup.spentUsd,
114
+ sup_spawned: sup.spawned,
115
+ sup_workers: sup.workers,
116
+ sup_settled: sup.settled,
117
+ sup_subtasks: sup.subtasks,
118
+ sup_delivered: sup.delivered,
119
+ sup_status: sup.sup_status as LedgerRow['sup_status'],
120
+ sup_verdict: sup.sup_verdict as LedgerRow['sup_verdict'],
121
+ solo_oc_rc: solo.oc_rc,
122
+ sup_driver_rc: sup.driver_rc,
123
+ solo_patch: solo.patchPath,
124
+ sup_patch: sup.patchPath,
125
+ }
126
+ }
127
+
128
+ /** iids already present in the ledger (resume-skip, orchestrate.sh semantics). */
129
+ export async function ledgerIids(ledgerPath: string): Promise<Set<string>> {
130
+ const raw = await readFile(ledgerPath, 'utf8').catch(() => '')
131
+ const iids = new Set<string>()
132
+ for (const line of raw.split('\n')) {
133
+ if (!line.trim()) continue
134
+ try {
135
+ const row = JSON.parse(line) as { iid?: string }
136
+ if (typeof row.iid === 'string') iids.add(row.iid)
137
+ } catch {
138
+ throw new Error(`corrupt ledger line in ${ledgerPath}: ${line.slice(0, 120)}`)
139
+ }
140
+ }
141
+ return iids
142
+ }
143
+
144
+ // ---------------------------------------------------------------------------
145
+ // Experiment config + loop.
146
+ // ---------------------------------------------------------------------------
147
+
148
+ export interface ExperimentConfig {
149
+ instances: string[]
150
+ /** Exactly one solo and one supervisor arm (the paired-ledger contract). */
151
+ arms: ExecutableArmSpec[]
152
+ ledgerPath: string
153
+ outDir: string
154
+ secretsDir: string
155
+ envFiles: string[]
156
+ /** Per-instance self-repro verify scripts: <verifyDir>/<iid>.sh. */
157
+ verifyDir: string
158
+ /** Override fixtures/instances.json (image map). */
159
+ instanceImagesPath?: string
160
+ judgeTimeoutMs?: number
161
+ gateWaitCeilingMs?: number
162
+ /** Probe model id. Defaults per-endpoint in capacity.ts. */
163
+ capacityModel?: string
164
+ /** Pause between instances (orchestrate.sh: 15s, gentle on the shared key). */
165
+ cooldownMs?: number
166
+ }
167
+
168
+ function armPair(arms: ExecutableArmSpec[]): { solo: SoloArmSpec; sup: SupervisorArmSpec } {
169
+ const solo = arms.filter((a): a is SoloArmSpec => a.kind === 'solo')
170
+ const sup = arms.filter((a): a is SupervisorArmSpec => a.kind === 'supervisor')
171
+ if (solo.length !== 1 || sup.length !== 1) {
172
+ throw new Error(`expected exactly one solo + one supervisor arm, got ${arms.map((a) => a.kind).join(', ')}`)
173
+ }
174
+ return { solo: solo[0], sup: sup[0] }
175
+ }
176
+
177
+ export async function runExperiment(config: ExperimentConfig): Promise<void> {
178
+ const { solo, sup } = armPair(config.arms)
179
+ const secrets: SecretsEnv = { secretsDir: config.secretsDir, envFiles: config.envFiles }
180
+ const excludes = await loadExcludes()
181
+ const images = await loadInstanceImages(config.instanceImagesPath)
182
+ const judge = createSerializedJudge({
183
+ ...(config.judgeTimeoutMs !== undefined ? { timeoutMs: config.judgeTimeoutMs } : {}),
184
+ })
185
+ const adapter = createSweBenchAdapter()
186
+ const log = (msg: string): void => console.log(`[${new Date().toISOString().slice(11, 19)}] ${msg}`)
187
+
188
+ const done = await ledgerIids(config.ledgerPath)
189
+ const pending = config.instances.filter((iid) => !done.has(iid))
190
+ for (const iid of config.instances.filter((i) => done.has(i))) log(`SKIP ${iid} (already in ledger)`)
191
+ if (pending.length === 0) {
192
+ log('nothing to do — all instances already in ledger')
193
+ return
194
+ }
195
+
196
+ // One dataset load for all pending instances (problem statements + metadata).
197
+ const tasks = await adapter.loadTasks({ ids: pending, split: 'test' })
198
+ const taskById = new Map(tasks.map((t) => [t.id, t]))
199
+
200
+ for (const iid of pending) {
201
+ const task = taskById.get(iid)
202
+ if (!task) throw new Error(`instance ${iid} not found in SWE-bench_Verified`)
203
+ const entry = images[iid]
204
+ if (!entry) throw new Error(`instance ${iid} has no image mapping (instances.json)`)
205
+ const problemStatement = String(task.metadata?.problem_statement ?? '')
206
+ if (!problemStatement) throw new Error(`instance ${iid}: empty problem_statement`)
207
+
208
+ // Capacity gates: worker path always; router path because a supervisor arm runs.
209
+ const gateOpts = {
210
+ ...(config.gateWaitCeilingMs !== undefined ? { waitCeilingMs: config.gateWaitCeilingMs } : {}),
211
+ ...(config.capacityModel !== undefined ? { model: config.capacityModel } : {}),
212
+ onStatus: log,
213
+ }
214
+ for (const gate of gatesForArmKind('supervisor', secrets, gateOpts)) {
215
+ if (!(await waitForCapacity(gate))) {
216
+ log(`NO CAPACITY on ${gate.name} within ceiling — stopping before ${iid} (resume later)`)
217
+ return
218
+ }
219
+ }
220
+
221
+ const ctx = {
222
+ instanceId: iid,
223
+ image: entry.image,
224
+ baseCommit: entry.base_commit,
225
+ problemStatement,
226
+ verifyCmd: `bash ${join(config.verifyDir, `${iid}.sh`)}`,
227
+ outDir: config.outDir,
228
+ secrets,
229
+ excludes,
230
+ }
231
+
232
+ log(`>>> ${iid} SOLO arm`)
233
+ const soloResult = await runSoloArm(solo, ctx)
234
+ const soloVerdict = await judge.judge(iid, soloResult.patchPath, 'solo')
235
+ log(`${iid} SOLO judged: ${JSON.stringify(soloVerdict)}`)
236
+
237
+ log(`>>> ${iid} SUP arm`)
238
+ const supResult = await runSupervisorArm(sup, ctx)
239
+ const supVerdict = await judge.judge(iid, supResult.patchPath, 'sup')
240
+ log(`${iid} SUP judged: ${JSON.stringify(supVerdict)}`)
241
+
242
+ const row = buildLedgerRow(soloResult, soloVerdict, supResult, supVerdict)
243
+ await appendFile(config.ledgerPath, JSON.stringify(row) + '\n')
244
+ log(`LEDGER_ROW ${iid} solo=${row.solo_resolved} sup=${row.sup_resolved}`)
245
+ await new Promise((r) => setTimeout(r, config.cooldownMs ?? 15_000))
246
+ }
247
+ }
248
+
249
+ // ---------------------------------------------------------------------------
250
+ // Dry-run parity — the M2 gate. No arms, no tokens; docker only.
251
+ // ---------------------------------------------------------------------------
252
+
253
+ export interface ParityCaseSpec {
254
+ iid: string
255
+ arm: 'solo' | 'sup'
256
+ /** Committed patch fixture, relative to fixtures/ (e.g. patches/x.solo.patch). */
257
+ patchFixture: string
258
+ }
259
+
260
+ export interface ParityCaseResult {
261
+ iid: string
262
+ arm: 'solo' | 'sup'
263
+ applyRc: number
264
+ fixtureFiles: string[]
265
+ extractedFiles: string[]
266
+ extractedPatchLines: number
267
+ verdict: JudgeVerdict
268
+ }
269
+
270
+ /** The two pinned parity cases: one resolved SOLO patch, one unresolved SUP patch. */
271
+ export const PARITY_CASES: ParityCaseSpec[] = [
272
+ { iid: 'pallets__flask-5014', arm: 'solo', patchFixture: 'patches/pallets__flask-5014.solo.patch' },
273
+ { iid: 'pydata__xarray-4687', arm: 'sup', patchFixture: 'patches/pydata__xarray-4687.sup.patch' },
274
+ ]
275
+
276
+ /** Changed paths of a unified diff (b/ side), for extraction-parity checks. */
277
+ export function diffChangedFiles(patch: string): string[] {
278
+ const files = new Set<string>()
279
+ for (const m of patch.matchAll(/^diff --git a\/.+ b\/(.+)$/gm)) files.add(m[1])
280
+ return [...files].sort()
281
+ }
282
+
283
+ /**
284
+ * Replay extraction + judging for committed patches WITHOUT running any arm:
285
+ * materialize the instance workspace from its image, apply the committed
286
+ * patch, re-extract it via the arms.ts extraction path, then grade the
287
+ * re-extracted patch with the serialized judge. Byte-identical output is not
288
+ * required (git normalizes); the changed-file set and the official verdict are.
289
+ */
290
+ export async function replayPatchParity(
291
+ cases: ParityCaseSpec[],
292
+ opts: { workDir: string; judge?: SerializedJudge; keepWorkspaces?: boolean },
293
+ ): Promise<ParityCaseResult[]> {
294
+ const judge = opts.judge ?? createSerializedJudge()
295
+ const excludes = await loadExcludes()
296
+ const images = await loadInstanceImages()
297
+ const results: ParityCaseResult[] = []
298
+ for (const c of cases) {
299
+ const entry = images[c.iid]
300
+ if (!entry) throw new Error(`parity: no image mapping for ${c.iid}`)
301
+ const fixturePatchPath = join(fixturesDir, c.patchFixture)
302
+ const fixturePatch = await readFile(fixturePatchPath, 'utf8')
303
+ const ws = join(opts.workDir, `parity-${c.iid}-${c.arm}`)
304
+ try {
305
+ await materializeWorkspace({
306
+ instanceId: c.iid,
307
+ image: entry.image,
308
+ baseCommit: entry.base_commit,
309
+ dest: ws,
310
+ })
311
+ const applyRc = await applyPatchWithFallback(ws, fixturePatchPath)
312
+ if (applyRc !== 0) throw new Error(`parity ${c.iid}: committed patch failed to apply (rc=${applyRc})`)
313
+ const extracted = await extractPatch(ws, entry.base_commit, excludes)
314
+ const extractedPath = join(opts.workDir, `parity-${c.iid}.${c.arm}.extracted.patch`)
315
+ await writeFile(extractedPath, extracted)
316
+ const verdict = await judge.judge(c.iid, extractedPath, `parity-${c.arm}`)
317
+ results.push({
318
+ iid: c.iid,
319
+ arm: c.arm,
320
+ applyRc,
321
+ fixtureFiles: diffChangedFiles(fixturePatch),
322
+ extractedFiles: diffChangedFiles(extracted),
323
+ extractedPatchLines: extracted.length === 0 ? 0 : extracted.split('\n').length - 1,
324
+ verdict,
325
+ })
326
+ } finally {
327
+ if (!opts.keepWorkspaces) await rm(ws, { recursive: true, force: true })
328
+ }
329
+ }
330
+ return results
331
+ }
332
+
333
+ // ---------------------------------------------------------------------------
334
+ // CLI.
335
+ // ---------------------------------------------------------------------------
336
+
337
+ const isMain = process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href
338
+
339
+ if (isMain) {
340
+ const [arg, extra] = process.argv.slice(2)
341
+ if (arg === '--dry-run-parity') {
342
+ const workDir = extra ?? join(process.env.TMPDIR ?? '/tmp', 'swe-arena-parity')
343
+ await mkdir(workDir, { recursive: true })
344
+ const results = await replayPatchParity(PARITY_CASES, { workDir })
345
+ for (const r of results) {
346
+ console.log(
347
+ `PARITY ${r.iid} [${r.arm}] resolved=${r.verdict.resolved} score=${r.verdict.score} ` +
348
+ `files(fixture=${r.fixtureFiles.join(',')} extracted=${r.extractedFiles.join(',')})`,
349
+ )
350
+ }
351
+ } else if (arg && !arg.startsWith('--')) {
352
+ const config = JSON.parse(await readFile(arg, 'utf8')) as ExperimentConfig
353
+ await runExperiment(config)
354
+ } else {
355
+ console.error(
356
+ 'usage: tsx src/swe-arena/run-experiment.mts <config.json>\n' +
357
+ ' tsx src/swe-arena/run-experiment.mts --dry-run-parity [workDir]',
358
+ )
359
+ process.exit(2)
360
+ }
361
+ }