@tangle-network/agent-bench 0.11.3 → 0.13.2

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 (170) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/HARNESS.md +6 -2
  3. package/README.md +1 -4
  4. package/package.json +5 -5
  5. package/scripts/run-package-tests.mjs +2 -2
  6. package/src/quant-arena/README.md +0 -144
  7. package/src/quant-arena/backtest.test.mts +0 -135
  8. package/src/quant-arena/backtest.ts +0 -218
  9. package/src/quant-arena/data.test.mts +0 -44
  10. package/src/quant-arena/data.ts +0 -141
  11. package/src/quant-arena/driver.test.mts +0 -253
  12. package/src/quant-arena/driver.ts +0 -219
  13. package/src/quant-arena/fixtures/data/PROVENANCE.md +0 -26
  14. package/src/quant-arena/fixtures/data/holdout/IDX.csv +0 -523
  15. package/src/quant-arena/fixtures/data/holdout/S01.csv +0 -523
  16. package/src/quant-arena/fixtures/data/holdout/S02.csv +0 -523
  17. package/src/quant-arena/fixtures/data/holdout/S03.csv +0 -523
  18. package/src/quant-arena/fixtures/data/holdout/S04.csv +0 -523
  19. package/src/quant-arena/fixtures/data/holdout/S05.csv +0 -523
  20. package/src/quant-arena/fixtures/data/holdout/S06.csv +0 -523
  21. package/src/quant-arena/fixtures/data/holdout/S07.csv +0 -523
  22. package/src/quant-arena/fixtures/data/holdout/S08.csv +0 -523
  23. package/src/quant-arena/fixtures/data/holdout/S09.csv +0 -523
  24. package/src/quant-arena/fixtures/data/holdout/S10.csv +0 -523
  25. package/src/quant-arena/fixtures/data/insample/IDX.csv +0 -2087
  26. package/src/quant-arena/fixtures/data/insample/S01.csv +0 -2087
  27. package/src/quant-arena/fixtures/data/insample/S02.csv +0 -2087
  28. package/src/quant-arena/fixtures/data/insample/S03.csv +0 -2087
  29. package/src/quant-arena/fixtures/data/insample/S04.csv +0 -2087
  30. package/src/quant-arena/fixtures/data/insample/S05.csv +0 -2087
  31. package/src/quant-arena/fixtures/data/insample/S06.csv +0 -2087
  32. package/src/quant-arena/fixtures/data/insample/S07.csv +0 -2087
  33. package/src/quant-arena/fixtures/data/insample/S08.csv +0 -2087
  34. package/src/quant-arena/fixtures/data/insample/S09.csv +0 -2087
  35. package/src/quant-arena/fixtures/data/insample/S10.csv +0 -2087
  36. package/src/quant-arena/fixtures/demo-campaign/cost-ledger.jsonl +0 -16
  37. package/src/quant-arena/fixtures/demo-campaign/notebook.jsonl +0 -5
  38. package/src/quant-arena/fixtures/demo-campaign/rollout-manifest.json +0 -171
  39. package/src/quant-arena/fixtures/demo-campaign/strategies/cand-001-default-author/strategy.ts +0 -119
  40. package/src/quant-arena/fixtures/demo-campaign/strategies/cand-002-default-author/strategy.ts +0 -119
  41. package/src/quant-arena/fixtures/demo-campaign/strategies/cand-003-quant-researcher/strategy.ts +0 -105
  42. package/src/quant-arena/fixtures/demo-campaign/strategies/cand-004-quant-researcher/strategy.ts +0 -102
  43. package/src/quant-arena/fixtures/demo-campaign-v2/cost-ledger.jsonl +0 -4
  44. package/src/quant-arena/fixtures/demo-campaign-v2/notebook.jsonl +0 -2
  45. package/src/quant-arena/fixtures/demo-campaign-v2/rollout-manifest.json +0 -84
  46. package/src/quant-arena/fixtures/demo-campaign-v2/strategies/cand-001-quant-researcher/strategy.ts +0 -117
  47. package/src/quant-arena/holdout-certify.mts +0 -206
  48. package/src/quant-arena/holdout-certify.test.mts +0 -82
  49. package/src/quant-arena/leak-audit.test.mts +0 -79
  50. package/src/quant-arena/leak-audit.ts +0 -95
  51. package/src/quant-arena/make-fixtures.mts +0 -161
  52. package/src/quant-arena/multiplicity.test.mts +0 -68
  53. package/src/quant-arena/multiplicity.ts +0 -87
  54. package/src/quant-arena/nautilus-certify.ts +0 -31
  55. package/src/quant-arena/oms.ts +0 -90
  56. package/src/quant-arena/profiles/quant-researcher.profile.json +0 -12
  57. package/src/quant-arena/python/pyproject.toml +0 -8
  58. package/src/quant-arena/python/uv.lock +0 -1297
  59. package/src/quant-arena/python/vbt-worker.py +0 -192
  60. package/src/quant-arena/quant-loop.mts +0 -840
  61. package/src/quant-arena/quant-loop.test.mts +0 -75
  62. package/src/quant-arena/strategies/buy-hold-index/strategy.ts +0 -11
  63. package/src/quant-arena/strategies/equal-weight/strategy.ts +0 -20
  64. package/src/quant-arena/strategies/sma-crossover/strategy.ts +0 -42
  65. package/src/quant-arena/types.ts +0 -133
  66. package/src/quant-arena/vbt-client.ts +0 -321
  67. package/src/quant-arena/vbt-parity.test.mts +0 -183
  68. package/src/quant-arena/windows.test.mts +0 -45
  69. package/src/quant-arena/windows.ts +0 -54
  70. package/src/rollout-ledger/backfill-swe-arena.mts +0 -610
  71. package/src/rollout-ledger/backfill-swe-arena.test.mts +0 -347
  72. package/src/rollout-ledger/settle-capture.mts +0 -448
  73. package/src/rollout-ledger/settle-capture.test.mts +0 -270
  74. package/src/swe-arena/activation.mts +0 -225
  75. package/src/swe-arena/activation.test.mts +0 -300
  76. package/src/swe-arena/analyze.ts +0 -211
  77. package/src/swe-arena/arms.ts +0 -862
  78. package/src/swe-arena/bootstrap-meta.mts +0 -188
  79. package/src/swe-arena/bootstrap-meta.test.mts +0 -51
  80. package/src/swe-arena/briefing.mts +0 -217
  81. package/src/swe-arena/briefing.test.mts +0 -179
  82. package/src/swe-arena/calibrate.ts +0 -217
  83. package/src/swe-arena/capabilities.mts +0 -76
  84. package/src/swe-arena/capabilities.test.mts +0 -57
  85. package/src/swe-arena/capacity.ts +0 -198
  86. package/src/swe-arena/cell-evidence.mts +0 -437
  87. package/src/swe-arena/cell-evidence.test.mts +0 -248
  88. package/src/swe-arena/diagnosis-ensemble.test.mts +0 -210
  89. package/src/swe-arena/diagnosis-ensemble.ts +0 -523
  90. package/src/swe-arena/execution.test.mts +0 -1171
  91. package/src/swe-arena/factory-command-container.ts +0 -284
  92. package/src/swe-arena/factory-judge-child.mts +0 -228
  93. package/src/swe-arena/factory.test.mts +0 -645
  94. package/src/swe-arena/fixtures/analyze.py +0 -80
  95. package/src/swe-arena/fixtures/excludes.txt +0 -8
  96. package/src/swe-arena/fixtures/factory/agent-eval-309/calibration.md +0 -51
  97. package/src/swe-arena/fixtures/factory/agent-eval-309/manifest.json +0 -29
  98. package/src/swe-arena/fixtures/factory/agent-eval-309/spec.md +0 -64
  99. package/src/swe-arena/fixtures/factory/agent-runtime-232/calibration.md +0 -48
  100. package/src/swe-arena/fixtures/factory/agent-runtime-232/manifest.json +0 -29
  101. package/src/swe-arena/fixtures/factory/agent-runtime-232/spec.md +0 -48
  102. package/src/swe-arena/fixtures/factory/loops-28/calibration.md +0 -47
  103. package/src/swe-arena/fixtures/factory/loops-28/manifest.json +0 -30
  104. package/src/swe-arena/fixtures/factory/loops-28/spec.md +0 -50
  105. package/src/swe-arena/fixtures/gen1-salvage/README.md +0 -45
  106. package/src/swe-arena/fixtures/gen1-salvage/cand0-e6d7361.diff +0 -116
  107. package/src/swe-arena/fixtures/gen1-salvage/cand1-76a8590.diff +0 -293
  108. package/src/swe-arena/fixtures/holdout-preregister.log +0 -12
  109. package/src/swe-arena/fixtures/holdout.json +0 -44
  110. package/src/swe-arena/fixtures/instances.json +0 -146
  111. package/src/swe-arena/fixtures/ledger.jsonl +0 -12
  112. package/src/swe-arena/fixtures/patches/pallets__flask-5014.solo.patch +0 -36
  113. package/src/swe-arena/fixtures/patches/pydata__xarray-4687.sup.patch +0 -33
  114. package/src/swe-arena/fixtures/rejudge.jsonl +0 -15
  115. package/src/swe-arena/fixtures/rematch.jsonl +0 -3
  116. package/src/swe-arena/fixtures/rematch2.jsonl +0 -3
  117. package/src/swe-arena/fixtures/rematch3.jsonl +0 -3
  118. package/src/swe-arena/fixtures/run-report/README.md +0 -43
  119. package/src/swe-arena/fixtures/run-report/factory-agent-eval-309-FSUP0.json +0 -173
  120. package/src/swe-arena/fixtures/run-report/factory-agent-eval-309-FSUP0.md +0 -100
  121. package/src/swe-arena/fixtures/run-report/gen3-rollup.json +0 -551
  122. package/src/swe-arena/fixtures/run-report/gen3-rollup.md +0 -64
  123. package/src/swe-arena/fixtures/sup-journal-true.json +0 -19
  124. package/src/swe-arena/fixtures/verify/astropy__astropy-13033.sh +0 -48
  125. package/src/swe-arena/fixtures/verify/django__django-11532.sh +0 -50
  126. package/src/swe-arena/fixtures/verify/matplotlib__matplotlib-20826.sh +0 -76
  127. package/src/swe-arena/fixtures/verify/pydata__xarray-4687.sh +0 -44
  128. package/src/swe-arena/fixtures/verify/pytest-dev__pytest-6197.sh +0 -32
  129. package/src/swe-arena/fixtures/verify/sphinx-doc__sphinx-9658.sh +0 -51
  130. package/src/swe-arena/fixtures/worker-tokens.json +0 -42
  131. package/src/swe-arena/fixtures.ts +0 -237
  132. package/src/swe-arena/gepa-seat.mts +0 -886
  133. package/src/swe-arena/gepa-seat.test.mts +0 -1136
  134. package/src/swe-arena/holdout-certify.mts +0 -408
  135. package/src/swe-arena/holdout-certify.test.mts +0 -160
  136. package/src/swe-arena/implementation-ref.test.mts +0 -64
  137. package/src/swe-arena/implementation-ref.ts +0 -62
  138. package/src/swe-arena/judge-child.mts +0 -37
  139. package/src/swe-arena/ledger-orphans.mts +0 -77
  140. package/src/swe-arena/ledger-orphans.test.mts +0 -149
  141. package/src/swe-arena/manifest.mts +0 -293
  142. package/src/swe-arena/manifest.test.mts +0 -169
  143. package/src/swe-arena/materialize.ts +0 -142
  144. package/src/swe-arena/outer-loop.mts +0 -2854
  145. package/src/swe-arena/outer-loop.test.mts +0 -714
  146. package/src/swe-arena/parity.test.mts +0 -87
  147. package/src/swe-arena/premeasured-from-cells.mts +0 -296
  148. package/src/swe-arena/premeasured-from-cells.test.mts +0 -201
  149. package/src/swe-arena/proc.test.mts +0 -172
  150. package/src/swe-arena/proc.ts +0 -260
  151. package/src/swe-arena/profiles/deepseek-author.profile.json +0 -12
  152. package/src/swe-arena/profiles/default-author.profile.json +0 -12
  153. package/src/swe-arena/proposer-fanout.mts +0 -736
  154. package/src/swe-arena/proposer-fanout.test.mts +0 -660
  155. package/src/swe-arena/proposer-provenance.mts +0 -176
  156. package/src/swe-arena/proposer-provenance.test.mts +0 -106
  157. package/src/swe-arena/reconcile.ts +0 -0
  158. package/src/swe-arena/replay.mts +0 -183
  159. package/src/swe-arena/replay.test.mts +0 -300
  160. package/src/swe-arena/run-experiment.mts +0 -729
  161. package/src/swe-arena/run-report.mts +0 -75
  162. package/src/swe-arena/run-supervisor.mjs +0 -297
  163. package/src/swe-arena/run-supervisor.test.mts +0 -539
  164. package/src/swe-arena/score-split.mts +0 -140
  165. package/src/swe-arena/score-split.test.mts +0 -123
  166. package/src/swe-arena/scratch-worktree-serialization.test.mts +0 -72
  167. package/src/swe-arena/scratch-worktree.test.mts +0 -56
  168. package/src/swe-arena/scratch-worktree.ts +0 -64
  169. package/src/swe-arena/serialized-judge.ts +0 -414
  170. package/src/swe-arena/types.ts +0 -218
@@ -1,169 +0,0 @@
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
- })
@@ -1,142 +0,0 @@
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
- }