@tangle-network/agent-bench 0.11.2 → 0.13.0

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