@tangle-network/agent-bench 0.14.2 → 0.14.4

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 (40) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/package.json +6 -6
  3. package/scripts/verify-packed-consumer.mjs +0 -1
  4. package/src/atom-mcp-e2e.mts +14 -2
  5. package/src/coordination-mcp-container-reach.mts +5 -5
  6. package/src/gate.ts +1 -1
  7. package/src/mcp-mount-probe.mts +7 -5
  8. package/src/run-benchmarks.test.mts +0 -4
  9. package/src/search-bench/profiles.ts +1 -1
  10. package/src/tb-supervisor-sidecar.mts +1 -1
  11. package/tb_agents/opencode_supervisor_agent.py +2 -2
  12. package/src/browser/adapters/bad-design-audit.ts +0 -153
  13. package/src/browser/adapters/bad-design-audit.verify.ts +0 -85
  14. package/src/browser/adapters/bad.ts +0 -165
  15. package/src/browser/agent-adapter.ts +0 -145
  16. package/src/browser/process-adapter.ts +0 -146
  17. package/src/browser/run-to-spans.ts +0 -105
  18. package/src/browser/run-to-spans.verify.ts +0 -89
  19. package/src/browser/ui-reviewer.ts +0 -200
  20. package/src/browser/ui-reviewer.verify.ts +0 -94
  21. package/src/browser/verify.ts +0 -96
  22. package/src/clbench-codebase-gate.mts +0 -314
  23. package/src/clbench-context-gate.mts +0 -341
  24. package/src/commit0-env-run.mts +0 -62
  25. package/src/commit0-env.ts +0 -172
  26. package/src/commit0-gate.mts +0 -558
  27. package/src/egress-probe.mts +0 -26
  28. package/src/humaneval-repair-gate.mts +0 -182
  29. package/src/profile-coordinates.ts +0 -134
  30. package/src/run-benchmarks-report.ts +0 -66
  31. package/src/skill-sandbox-smoke.mts +0 -101
  32. package/src/supervisor-arena.mts +0 -825
  33. package/src/swe-emit-patch.mts +0 -125
  34. package/src/swe-local-proof.mts +0 -265
  35. package/src/swe-repro-calibrate.mts +0 -451
  36. package/src/swe-stream.mts +0 -1561
  37. package/src/trajectory-assemble.mjs +0 -130
  38. package/src/worker-browser.ts +0 -115
  39. package/src/worker-cad.ts +0 -470
  40. package/src/workspace-loop.mts +0 -133
@@ -1,825 +0,0 @@
1
- /**
2
- * Supervisor showdown arena — implements supervisor-lab
3
- * docs/results/PREREG-supervisor-showdown.md (2026-07-09) EXACTLY. The prereg is
4
- * the contract: task sets, arms, equal-compute rule, plan contract, and the
5
- * Phase A/B separation are fixed there and must not be tuned after results.
6
- *
7
- * Arms (SET=hard: the 62 problems the committed structural run ended hiddenFinal=0;
8
- * SET=control: 20 problems it solved — supervision must NOT move these):
9
- * A — more-blind-compute control: one fresh structural round (k=5, testgen=6,
10
- * <=2 repairs, Llama-3-8B temp 0.8), no evidence shown.
11
- * B — self-supervisor: Llama reads the visible evidence package, writes a
12
- * diagnosis+plan (no code), then the arm-A loop runs conditioned on it.
13
- * C — smart supervisor: glm-4.5-air writes the plan (<=400 tokens by explicit
14
- * instruction; fenced code / `def ` lines stripped + planLeaked recorded),
15
- * same Llama loop conditioned on it.
16
- * D — smart-solo anchor: one glm-4.5-air call, plain solve instruction.
17
- *
18
- * Evidence (arms B/C) comes ONLY from the committed run rows (EVIDENCE jsonl):
19
- * samples, visible-check outputs, authored asserts, repair transcript. The rows'
20
- * hiddenSamples/hiddenFinal fields are NEVER read into any prompt — hidden info
21
- * defines the task sets (already hardcoded here) and nothing else.
22
- *
23
- * Phase separation (as hev-structural.mts, whose runJailed/nonce-judge/oracle
24
- * this file replicates — that module runs main() on import, so its internals
25
- * cannot be imported without side effects):
26
- * Phase A: all arm decisions from visible info only; rows appended to OUT.phaseA.
27
- * Phase B: rig-local nonce-sentinel hidden judge grades every sample and the
28
- * locked final, script-side; graded rows appended to OUT.
29
- *
30
- * cd bench && ARM=A|B|C|D SET=hard|control N=… OUT=/abs/rows.jsonl \
31
- * EVIDENCE=/abs/full-llama3-8b-testgen.jsonl HUMANEVAL_GZ=/abs/HumanEval.jsonl.gz \
32
- * TANGLE_API_KEY=$TOGETHER_API_KEY ZAI_API_KEY=… npx tsx src/supervisor-arena.mts
33
- */
34
- import { execFile, execFileSync } from 'node:child_process'
35
- import { randomBytes } from 'node:crypto'
36
- import { appendFileSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
37
- import { tmpdir } from 'node:os'
38
- import { join } from 'node:path'
39
- import { type HumanEvalTask, basePrompt, extractCode, loadHumanEval } from './benchmarks/humaneval'
40
- import { runBenchRouterTurn } from './router-turn'
41
- import { pool } from './stats.mts'
42
-
43
- // ---------- pre-registered task sets (verbatim from the prereg; DO NOT EDIT) ----------
44
-
45
- const hardIds = [
46
- 2, 5, 10, 16, 18, 20, 21, 26, 27, 1, 33, 37, 39, 38, 41, 46, 54, 52, 62, 64, 65, 73, 75, 80, 81, 85, 84, 92, 91, 93,
47
- 100, 99, 101, 70, 32, 103, 102, 108, 110, 112, 109, 115, 118, 119, 120, 122, 125, 126, 127, 131, 129, 130, 134, 138,
48
- 135, 137, 140, 145, 148, 157, 160, 163,
49
- ].map((n) => `HumanEval/${n}`)
50
-
51
- const controlIds = [0, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 15, 17, 19, 22, 23, 24, 25, 28, 29].map((n) => `HumanEval/${n}`)
52
-
53
- // ---------- models + list prices (per 1M tokens; printed as list-price $, not billed truth) ----------
54
-
55
- const workerModelDefault = 'meta-llama/Meta-Llama-3-8B-Instruct-Lite'
56
- const glmModelDefault = 'glm-4.5-air'
57
- const listPrices: Record<string, { in: number; out: number }> = {
58
- [workerModelDefault]: { in: 0.1, out: 0.1 },
59
- [glmModelDefault]: { in: 0.2, out: 1.1 },
60
- }
61
-
62
- const dockerImage = 'python:3.12-slim'
63
- const dockerTimeoutMs = Number(process.env.DOCKER_TIMEOUT_MS ?? 20000)
64
-
65
- function must(name: string): string {
66
- const v = process.env[name]
67
- if (!v) throw new Error(`env ${name} is required`)
68
- return v
69
- }
70
-
71
- // ---------- docker semaphore + jailed runner (replicated from hev-structural) ----------
72
-
73
- let dockerSlots = 6
74
- let dockerInFlight = 0
75
- const dockerWaiters: Array<() => void> = []
76
- async function withDockerSlot<T>(fn: () => Promise<T>): Promise<T> {
77
- if (dockerInFlight >= dockerSlots) await new Promise<void>((r) => dockerWaiters.push(r))
78
- dockerInFlight += 1
79
- try {
80
- return await fn()
81
- } finally {
82
- dockerInFlight -= 1
83
- dockerWaiters.shift()?.()
84
- }
85
- }
86
-
87
- const containerPrefix = `supv-${process.pid}`
88
- let containerSeq = 0
89
-
90
- function reapContainers(): void {
91
- try {
92
- const ids = execFileSync('docker', ['ps', '-aq', '--filter', `name=${containerPrefix}`], { timeout: 10000 }).toString().trim()
93
- if (ids) execFileSync('docker', ['rm', '-f', ...ids.split('\n')], { timeout: 15000 })
94
- } catch {
95
- /* reaper is best-effort by design */
96
- }
97
- }
98
- process.on('SIGINT', () => {
99
- reapContainers()
100
- process.exit(130)
101
- })
102
- process.on('SIGTERM', () => {
103
- reapContainers()
104
- process.exit(143)
105
- })
106
-
107
- interface JailResult {
108
- exitCode: number
109
- stdout: string
110
- stderr: string
111
- }
112
-
113
- /** One python program in the jail: --network=none, cpu/mem caps, in-container
114
- * `timeout -s KILL`, client timeout, backstop. Docker INFRA faults throw. */
115
- function runJailed(program: string): Promise<JailResult> {
116
- return withDockerSlot(
117
- () =>
118
- new Promise<JailResult>((resolvePromise, reject) => {
119
- const dir = mkdtempSync(join(tmpdir(), 'supv-'))
120
- writeFileSync(join(dir, 'p.py'), program)
121
- const name = `${containerPrefix}-${containerSeq++}`
122
- let settled = false
123
- const cleanup = () => {
124
- rmSync(dir, { recursive: true, force: true })
125
- execFile('docker', ['rm', '-f', name], () => {})
126
- }
127
- const finish = (res: JailResult) => {
128
- if (settled) return
129
- settled = true
130
- clearTimeout(backstop)
131
- cleanup()
132
- resolvePromise(res)
133
- }
134
- const fail = (e: Error) => {
135
- if (settled) return
136
- settled = true
137
- clearTimeout(backstop)
138
- cleanup()
139
- reject(e)
140
- }
141
- const backstop = setTimeout(() => finish({ exitCode: 124, stdout: '', stderr: 'backstop timeout (no output)' }), dockerTimeoutMs + 5000)
142
- const inContainerSecs = Math.ceil(dockerTimeoutMs / 1000) + 2
143
- execFile(
144
- 'docker',
145
- [
146
- 'run', '--rm', '--name', name, '--network=none', '--cpus=1', '--memory=512m',
147
- '-v', `${dir}:/w:ro`, '-w', '/w', dockerImage,
148
- 'timeout', '-s', 'KILL', String(inContainerSecs), 'python', '/w/p.py',
149
- ],
150
- { timeout: dockerTimeoutMs + 3000, killSignal: 'SIGKILL', maxBuffer: 4 * 1024 * 1024 },
151
- (err, stdout, stderr) => {
152
- if (err) {
153
- const e = err as NodeJS.ErrnoException & { code?: number | string }
154
- if (e.code === 'ENOENT') return fail(new Error('docker binary not found on PATH'))
155
- const se = stderr ?? ''
156
- if (/cannot connect to the docker daemon|is the docker daemon running|permission denied while trying to connect/i.test(se)) {
157
- return fail(new Error(`docker daemon unreachable: ${se.slice(0, 200)}`))
158
- }
159
- if (/(unable to find image|pull access denied|manifest unknown|error response from daemon).*(pull|repository|registry)/i.test(se)) {
160
- return fail(new Error(`docker image ${dockerImage} unavailable: ${se.slice(0, 200)}`))
161
- }
162
- const code = typeof e.code === 'number' ? e.code : 1
163
- return finish({ exitCode: code, stdout: stdout ?? '', stderr: se })
164
- }
165
- finish({ exitCode: 0, stdout: stdout ?? '', stderr: stderr ?? '' })
166
- },
167
- )
168
- }),
169
- )
170
- }
171
-
172
- // ---------- honest oracle (visible docstring doctests + authored asserts; replicated) ----------
173
-
174
- interface HonestResult {
175
- attempted: number
176
- failed: number
177
- failureOutput: string
178
- pass: boolean
179
- dAttempted?: number
180
- dFailed?: number
181
- gAttempted?: number
182
- gFailed?: number
183
- }
184
-
185
- function buildHonestProgram(task: HumanEvalTask, candidate: string, nonce: string, genTests: string[] = []): string {
186
- const promptB64 = Buffer.from(task.prompt, 'utf8').toString('base64')
187
- const entryB64 = Buffer.from(task.entryPoint, 'utf8').toString('base64')
188
- const genB64 = Buffer.from(JSON.stringify(genTests), 'utf8').toString('base64')
189
- return `${task.prompt}\n${candidate}\n
190
- import ast as _ast, base64 as _b64, doctest as _doctest, io as _io, json as _json, sys as _sys
191
- _prompt_text = _b64.b64decode("${promptB64}").decode("utf8")
192
- _entry = _b64.b64decode("${entryB64}").decode("utf8")
193
- _gen_tests = _json.loads(_b64.b64decode("${genB64}").decode("utf8"))
194
- _stub_ns = {}
195
- exec(_prompt_text, _stub_ns)
196
- _doc = getattr(_stub_ns.get(_entry), "__doc__", None) or ""
197
- try:
198
- _examples = _doctest.DocTestParser().get_examples(_doc)
199
- except ValueError:
200
- _examples = [] # malformed docstring indentation -> no usable signal, not a crash
201
-
202
- class _Checker(_doctest.OutputChecker):
203
- def check_output(self, want, got, optionflags):
204
- if super().check_output(want, got, optionflags):
205
- return True
206
- if want.strip() == "" and got.strip() == "True":
207
- return True
208
- try:
209
- return _ast.literal_eval(want.strip()) == _ast.literal_eval(got.strip())
210
- except Exception:
211
- return False
212
-
213
- _test = _doctest.DocTest(_examples, globs=dict(globals()), name="visible", filename="p", lineno=0, docstring=_doc)
214
- _runner = _doctest.DocTestRunner(checker=_Checker(), verbose=False, optionflags=_doctest.NORMALIZE_WHITESPACE | _doctest.IGNORE_EXCEPTION_DETAIL)
215
- _buf = _io.StringIO()
216
- _res = _runner.run(_test, out=_buf.write)
217
-
218
- _g_att, _g_fail = 0, 0
219
- for _t in _gen_tests:
220
- _g_att += 1
221
- try:
222
- exec(_t, dict(globals()))
223
- except Exception as _e:
224
- _g_fail += 1
225
- _buf.write("GENTEST FAILED: %s -> %s: %s\\n" % (_t.strip()[:200], type(_e).__name__, str(_e)[:200]))
226
-
227
- _att = _res.attempted + _g_att
228
- _fail = _res.failed + _g_fail
229
- print("HONEST-${nonce} attempted=%d failed=%d datt=%d dfail=%d gatt=%d gfail=%d" % (_att, _fail, _res.attempted, _res.failed, _g_att, _g_fail))
230
- _sys.stdout.write(_buf.getvalue()[-1500:])
231
- _sys.exit(0 if _att > 0 and _fail == 0 else 1)
232
- `
233
- }
234
-
235
- async function runHonestOracle(task: HumanEvalTask, candidate: string, genTests: string[] = []): Promise<HonestResult> {
236
- const nonce = randomBytes(8).toString('hex')
237
- const r = await runJailed(buildHonestProgram(task, candidate, nonce, genTests))
238
- const summary = new RegExp(`HONEST-${nonce} attempted=(\\d+) failed=(\\d+) datt=(\\d+) dfail=(\\d+) gatt=(\\d+) gfail=(\\d+)`).exec(r.stdout)
239
- if (!summary) {
240
- const detail = (r.stderr || r.stdout).slice(-1500) || 'timed out (no output)'
241
- return { attempted: -1, failed: -1, failureOutput: detail, pass: false }
242
- }
243
- const attempted = Number(summary[1])
244
- const failed = Number(summary[2])
245
- const failureOutput = r.stdout.replace(summary[0], '').slice(-1500)
246
- return {
247
- attempted,
248
- failed,
249
- failureOutput,
250
- pass: attempted > 0 && failed === 0,
251
- dAttempted: Number(summary[3]),
252
- dFailed: Number(summary[4]),
253
- gAttempted: Number(summary[5]),
254
- gFailed: Number(summary[6]),
255
- }
256
- }
257
-
258
- function honestScore(h: HonestResult): number {
259
- if (h.attempted <= 0) return h.attempted === 0 ? 0 : -1
260
- return (h.attempted - h.failed) / h.attempted
261
- }
262
-
263
- // ---------- hidden judge (Phase B ONLY; nonce sentinel, not exit-0; replicated) ----------
264
-
265
- function buildHiddenProgram(task: HumanEvalTask, candidate: string, nonce: string): string {
266
- return `${task.prompt}\n${candidate}\n\n${task.test}\n\ncheck(${task.entryPoint})\nprint("HIDDEN-${nonce} PASS")\n`
267
- }
268
-
269
- async function runHiddenJudge(task: HumanEvalTask, candidate: string): Promise<{ pass: number; detail?: string }> {
270
- const nonce = randomBytes(8).toString('hex')
271
- const r = await runJailed(buildHiddenProgram(task, candidate, nonce))
272
- if (r.exitCode === 0 && r.stdout.includes(`HIDDEN-${nonce} PASS`)) return { pass: 1 }
273
- return { pass: 0, detail: (r.stderr || r.stdout).slice(-600) || 'timed out (no output)' }
274
- }
275
-
276
- // ---------- model client (plain fetch; retries transient HTTP AND empty content — the
277
- // glm-4.5-air reasoning path starves `content` when reasoning eats max_tokens) ----------
278
-
279
- interface ClientCfg {
280
- base: string
281
- key: string
282
- model: string
283
- maxTokens: number
284
- temperature: number
285
- }
286
-
287
- interface Completion {
288
- content: string
289
- attempts: number
290
- tokensIn: number
291
- tokensOut: number
292
- }
293
-
294
- async function complete(cfg: ClientCfg, messages: Array<{ role: string; content: string }>): Promise<Completion> {
295
- let lastErr = ''
296
- for (let attempt = 1; attempt <= 4; attempt += 1) {
297
- if (attempt > 1) await new Promise((r) => setTimeout(r, 2000 * 2 ** attempt))
298
- try {
299
- const system = messages.find((message) => message.role === 'system')?.content
300
- const result = await runBenchRouterTurn(
301
- {
302
- routerBaseUrl: cfg.base,
303
- routerKey: cfg.key,
304
- profile: {
305
- name: 'supervisor-arena-agent',
306
- harness: 'cli-base',
307
- model: {
308
- provider: 'tangle-router',
309
- default: cfg.model,
310
- metadata: { temperature: cfg.temperature },
311
- maxVisibleOutputTokens: cfg.maxTokens,
312
- },
313
- ...(system ? { prompt: { systemPrompt: system } } : {}),
314
- },
315
- timeoutMs: Number(process.env.LLM_TIMEOUT_MS ?? 240_000),
316
- },
317
- { messages: messages.filter((message) => message.role !== 'system') },
318
- )
319
- if (result.usage.tokensKnown === false) throw new Error('provider omitted token usage')
320
- const content = result.finalText
321
- if (content.trim() === '') {
322
- lastErr = 'empty content'
323
- continue
324
- }
325
- return {
326
- content,
327
- attempts: attempt,
328
- tokensIn: result.usage.input,
329
- tokensOut: result.usage.output,
330
- }
331
- } catch (e) {
332
- lastErr = e instanceof Error ? e.message : String(e)
333
- }
334
- }
335
- throw new Error(`completion failed after retries: ${lastErr}`)
336
- }
337
-
338
- // zai 429s above ~4 concurrent requests — a dedicated semaphore, independent of the
339
- // task pool width, caps every glm call (plans in C, solo solves in D).
340
- let zaiSlots = 4
341
- let zaiInFlight = 0
342
- const zaiWaiters: Array<() => void> = []
343
- async function withZaiSlot<T>(fn: () => Promise<T>): Promise<T> {
344
- if (zaiInFlight >= zaiSlots) await new Promise<void>((r) => zaiWaiters.push(r))
345
- zaiInFlight += 1
346
- try {
347
- return await fn()
348
- } finally {
349
- zaiInFlight -= 1
350
- zaiWaiters.shift()?.()
351
- }
352
- }
353
-
354
- // ---------- CodeT-style test generation (visible info only, BEFORE any candidate; replicated) ----------
355
-
356
- const testGenInstruction = (count: number, entry: string) =>
357
- `Read the following Python function signature and docstring. Write exactly ${count} single-line assert statements that test the function \`${entry}\`, based ONLY on the behavior the docstring describes. Each assert must be one physical line of the form \`assert ${entry}(...) == expected\` (or a True/False check). Do NOT implement the function. Do NOT copy examples verbatim if you can test other cases too. Output ONLY the assert lines inside a single \`\`\`python code block.`
358
-
359
- async function generateTests(cfg: ClientCfg, task: HumanEvalTask, count: number): Promise<{ tests: string[]; completion: Completion }> {
360
- const c = await complete(cfg, [
361
- { role: 'user', content: `${testGenInstruction(count, task.entryPoint)}\n\n\`\`\`python\n${task.prompt}\`\`\`` },
362
- ])
363
- const block = extractCode(c.content)
364
- const balanced = (s: string) => {
365
- let d = 0
366
- for (const ch of s) {
367
- if (ch === '(' || ch === '[' || ch === '{') d += 1
368
- else if (ch === ')' || ch === ']' || ch === '}') d -= 1
369
- if (d < 0) return false
370
- }
371
- return d === 0
372
- }
373
- const tests = block
374
- .split('\n')
375
- .map((l) => l.trim())
376
- .filter((l) => l.startsWith('assert ') && l.includes(task.entryPoint) && balanced(l))
377
- .slice(0, count)
378
- return { tests, completion: c }
379
- }
380
-
381
- /** Prefer the LAST fenced block containing a `def` (repair replies echo the failure
382
- * report in a bare fence first), else the shared extractor. */
383
- function extractRepairCode(reply: string): string {
384
- const fences = [...reply.matchAll(/```(?:python|py)?\s*\n([\s\S]*?)```/gi)].map((m) => (m[1] ?? '').trim())
385
- for (let i = fences.length - 1; i >= 0; i -= 1) {
386
- if (/(^|\n)\s*def\s+\w+/.test(fences[i] as string)) return fences[i] as string
387
- }
388
- return extractCode(reply)
389
- }
390
-
391
- // ---------- evidence package (arms B/C) — visible fields of the committed run rows ONLY ----------
392
-
393
- /** The visible slice of a committed run row. hiddenSamples/hiddenFinal exist in the
394
- * file but are deliberately absent here: parsing narrows to these fields so hidden
395
- * info cannot reach a prompt by accident. */
396
- interface EvidenceRow {
397
- taskId: string
398
- samples: string[]
399
- honest: HonestResult[]
400
- repairs: Array<{ code: string; honest: HonestResult }>
401
- genTests: string[]
402
- selectedIdx: number
403
- }
404
-
405
- function loadEvidence(path: string): Map<string, EvidenceRow> {
406
- const rows = new Map<string, EvidenceRow>()
407
- for (const line of readFileSync(path, 'utf8').split('\n')) {
408
- if (line.trim() === '') continue
409
- const d = JSON.parse(line) as EvidenceRow & Record<string, unknown>
410
- if (!d.taskId || !Array.isArray(d.samples) || !Array.isArray(d.honest)) throw new Error(`malformed evidence row: ${line.slice(0, 120)}`)
411
- rows.set(d.taskId, {
412
- taskId: d.taskId,
413
- samples: d.samples,
414
- honest: d.honest,
415
- repairs: Array.isArray(d.repairs) ? d.repairs : [],
416
- genTests: Array.isArray(d.genTests) ? d.genTests : [],
417
- selectedIdx: Number(d.selectedIdx ?? 0),
418
- })
419
- }
420
- return rows
421
- }
422
-
423
- const clip = (s: string, n: number): string => {
424
- const t = s.trim()
425
- return t.length <= n ? t : `${t.slice(0, n)} …[+${t.length - n} chars trimmed]`
426
- }
427
-
428
- const firstLines = (code: string, n = 2): string =>
429
- code
430
- .split('\n')
431
- .filter((l) => l.trim() !== '')
432
- .slice(0, n)
433
- .join(' | ')
434
-
435
- const checkStatus = (h: HonestResult): string =>
436
- h.attempted < 0
437
- ? 'crashed before the visible checks could run'
438
- : h.attempted === 0
439
- ? 'no visible checks were runnable'
440
- : h.pass
441
- ? `passed all ${h.attempted} visible checks`
442
- : `failed ${h.failed}/${h.attempted} visible checks`
443
-
444
- /** Problem prompt + per-attempt one-line summary (first 2 code lines + trimmed
445
- * visible-check output) + authored asserts + repair outcomes, bounded to
446
- * ~3000 tokens (maxChars chars). Visible information only. */
447
- function renderEvidence(task: HumanEvalTask, ev: EvidenceRow, maxChars: number): string {
448
- const parts: string[] = []
449
- parts.push('The problem:', '```python', task.prompt.trimEnd(), '```', '')
450
- parts.push(`Previous attempts by the programmer, each with the result of the VISIBLE checks (docstring examples + the authored asserts listed below):`)
451
- ev.samples.forEach((code, i) => {
452
- const h = ev.honest[i] ?? { attempted: -1, failed: -1, failureOutput: '', pass: false }
453
- parts.push(`[attempt ${i + 1}]${i === ev.selectedIdx ? ' (selected as best)' : ''} starts: ${firstLines(code)}`)
454
- parts.push(` result: ${checkStatus(h)}`)
455
- const fo = clip(h.failureOutput ?? '', 350)
456
- if (fo !== '') parts.push(` check output: ${fo}`)
457
- })
458
- parts.push('', 'Authored asserts used as visible checks:')
459
- for (const t of ev.genTests) parts.push(` ${t}`)
460
- if (ev.genTests.length === 0) parts.push(' (none survived filtering)')
461
- if (ev.repairs.length > 0) {
462
- parts.push('', 'Repair attempts (revisions of the selected attempt, steered by the check output):')
463
- ev.repairs.forEach((r, i) => {
464
- parts.push(`[repair ${i + 1}] starts: ${firstLines(r.code)}`)
465
- parts.push(` result: ${checkStatus(r.honest)}`)
466
- const fo = clip(r.honest.failureOutput ?? '', 350)
467
- if (fo !== '') parts.push(` check output: ${fo}`)
468
- })
469
- } else {
470
- parts.push('', 'No repair attempts were made on this problem.')
471
- }
472
- let text = parts.join('\n')
473
- if (text.length > maxChars) text = `${text.slice(0, maxChars)}\n…[evidence truncated at ${maxChars} chars]`
474
- return text
475
- }
476
-
477
- // ---------- supervisor plan (arms B/C): diagnose + steer, never solve ----------
478
-
479
- const planContract =
480
- "Diagnose why every attempt failed and write a plan: the specific mistake, the correct approach, edge cases to handle. You may include at most 3 short illustrative expressions. Do NOT write the function; any fenced code block or line starting with 'def ' disqualifies the plan. Keep the plan under 400 tokens."
481
-
482
- const supervisorPrompt = (evidence: string): string =>
483
- ["You are reviewing a programmer's previous attempts at a Python problem.", '', evidence, '', planContract].join('\n')
484
-
485
- /** Enforce the no-code contract: strip fenced blocks and `def ` lines, record the
486
- * leak (leak RATE is a pre-registered measurement, so the stripped plan is still
487
- * used rather than the task being dropped). */
488
- function stripPlanCode(raw: string): { plan: string; leaked: boolean } {
489
- let leaked = false
490
- let s = raw
491
- if (s.includes('```')) {
492
- // an unterminated fence leaks to end-of-text, so strip greedily to the closer or EOF
493
- const stripped = s.replace(/```[a-zA-Z]*[^\n]*\n?[\s\S]*?(?:```|$)/g, '')
494
- if (stripped !== s) leaked = true
495
- s = stripped
496
- }
497
- const lines = s.split('\n')
498
- const kept = lines.filter((l) => !/^\s*def\s/.test(l))
499
- if (kept.length !== lines.length) leaked = true
500
- return { plan: kept.join('\n').trim(), leaked }
501
- }
502
-
503
- // ---------- Phase A worker loop — the hev-structural recipe verbatim (k samples temp 0.8,
504
- // fresh testgen, honest argmax select, <=R honest-grounded repairs); arms B/C prepend the plan ----------
505
-
506
- interface WorkerOutcome {
507
- samples: string[]
508
- honest: HonestResult[]
509
- selectedIdx: number
510
- repairs: Array<{ code: string; honest: HonestResult }>
511
- finalCode: string
512
- repairStop: string
513
- genTests: string[]
514
- calls: number
515
- attempts: number
516
- tokensIn: number
517
- tokensOut: number
518
- }
519
-
520
- async function runWorkerLoop(cfg: ClientCfg, task: HumanEvalTask, k: number, maxRepairs: number, testGen: number, planPreamble: string | null): Promise<WorkerOutcome> {
521
- const samplePrompt = planPreamble === null ? basePrompt(task) : `${planPreamble}\n\n${basePrompt(task)}`
522
- let calls = 0
523
- let attempts = 0
524
- let tokensIn = 0
525
- let tokensOut = 0
526
- const track = (c: Completion) => {
527
- calls += 1
528
- attempts += c.attempts
529
- tokensIn += c.tokensIn
530
- tokensOut += c.tokensOut
531
- }
532
-
533
- // asserts regenerated FRESH for this arm's round, from the prompt alone (plan-free:
534
- // testgen is oracle authorship, not solving — conditioning it would contaminate the oracle)
535
- let genTests: string[] = []
536
- if (testGen > 0) {
537
- const g = await generateTests(cfg, task, testGen)
538
- track(g.completion)
539
- genTests = g.tests
540
- }
541
-
542
- const samples: string[] = []
543
- for (let i = 0; i < k; i += 1) {
544
- const c = await complete(cfg, [{ role: 'user', content: samplePrompt }])
545
- track(c)
546
- samples.push(extractCode(c.content))
547
- }
548
- const honest: HonestResult[] = []
549
- for (const s of samples) honest.push(await runHonestOracle(task, s, genTests))
550
-
551
- let selectedIdx = 0
552
- for (let i = 1; i < k; i += 1) {
553
- if (honestScore(honest[i] as HonestResult) > honestScore(honest[selectedIdx] as HonestResult)) selectedIdx = i
554
- }
555
-
556
- const selHonest = honest[selectedIdx] as HonestResult
557
- let best = { code: samples[selectedIdx] as string, honest: selHonest }
558
- const repairs: WorkerOutcome['repairs'] = []
559
- let repairStop = 'already-passing'
560
- if (!selHonest.pass) {
561
- if (selHonest.attempted === 0) {
562
- repairStop = 'no-signal'
563
- } else {
564
- repairStop = 'rounds-exhausted'
565
- let current = best
566
- for (let r = 0; r < maxRepairs; r += 1) {
567
- const repairPrompt = [
568
- 'Your Python function failed some of the example checks shown in its own docstring.',
569
- 'Here is the task again:',
570
- '```python',
571
- task.prompt.trimEnd(),
572
- '```',
573
- 'Your current attempt:',
574
- '```python',
575
- current.code,
576
- '```',
577
- 'Result of running the docstring examples against your attempt:',
578
- '```',
579
- current.honest.failureOutput.trim() || '(the code crashed before the examples could run)',
580
- '```',
581
- 'Fix the function so the docstring examples pass. Output the COMPLETE corrected function definition inside a single ```python code block. Do not write tests or example calls.',
582
- ].join('\n')
583
- const c = await complete(cfg, [{ role: 'user', content: repairPrompt }])
584
- track(c)
585
- const code = extractRepairCode(c.content)
586
- const h = await runHonestOracle(task, code, genTests)
587
- repairs.push({ code, honest: h })
588
- if (honestScore(h) > honestScore(current.honest)) current = { code, honest: h }
589
- if (honestScore(current.honest) > honestScore(best.honest)) best = current
590
- if (h.pass) {
591
- repairStop = 'repaired-pass'
592
- break
593
- }
594
- }
595
- }
596
- }
597
-
598
- return { samples, honest, selectedIdx, repairs, finalCode: best.code, repairStop, genTests, calls, attempts, tokensIn, tokensOut }
599
- }
600
-
601
- // ---------- rows ----------
602
-
603
- interface ModelSpend {
604
- model: string
605
- calls: number
606
- attempts: number
607
- tokensIn: number
608
- tokensOut: number
609
- }
610
-
611
- interface ArenaRow {
612
- arm: string
613
- set: string
614
- taskId: string
615
- k: number
616
- maxRepairs: number
617
- temperature: number
618
- planRaw: string | null
619
- plan: string | null
620
- planLeaked: boolean | null
621
- planEmptyAfterStrip: boolean | null
622
- evidenceChars: number | null
623
- genTests: string[]
624
- samples: string[]
625
- honest: HonestResult[]
626
- selectedIdx: number
627
- repairs: Array<{ code: string; honest: HonestResult }>
628
- finalCode: string
629
- repairStop: string
630
- worker: ModelSpend
631
- supervisor: ModelSpend | null
632
- }
633
-
634
- interface GradedRow extends ArenaRow {
635
- hiddenSamples: number[]
636
- hiddenFinal: number
637
- }
638
-
639
- // ---------- main ----------
640
-
641
- const pct = (x: number) => `${(x * 100).toFixed(1)}%`
642
-
643
- function costLine(s: ModelSpend): string {
644
- const p = listPrices[s.model]
645
- const dollars = p ? (s.tokensIn / 1e6) * p.in + (s.tokensOut / 1e6) * p.out : null
646
- const d = dollars === null ? '$=null (no list price)' : `$${dollars.toFixed(4)} (list $${p?.in}/1M in, $${p?.out}/1M out)`
647
- return `${s.model}: in=${s.tokensIn} out=${s.tokensOut} calls=${s.calls} (attempts incl. retries=${s.attempts}) → ${d}`
648
- }
649
-
650
- async function main(): Promise<void> {
651
- const arm = must('ARM').toUpperCase()
652
- if (!['A', 'B', 'C', 'D'].includes(arm)) throw new Error(`ARM must be A|B|C|D, got ${arm}`)
653
- const setName = must('SET').toLowerCase()
654
- if (!['hard', 'control'].includes(setName)) throw new Error(`SET must be hard|control, got ${setName}`)
655
- const ids = (setName === 'hard' ? hardIds : controlIds).slice(0, Number(process.env.N ?? Number.POSITIVE_INFINITY))
656
- const out = must('OUT')
657
-
658
- const k = Number(process.env.K ?? 5)
659
- const maxRepairs = Number(process.env.REPAIRS ?? 2)
660
- const testGen = Number(process.env.TESTGEN ?? 6)
661
- const temperature = Number(process.env.TEMPERATURE ?? 0.8)
662
- const supTemperature = Number(process.env.SUPERVISOR_TEMPERATURE ?? 0.2)
663
- const solveConc = Number(process.env.CONCURRENCY ?? 6)
664
- dockerSlots = Number(process.env.DOCKER_CONCURRENCY ?? 6)
665
- zaiSlots = Math.min(4, Number(process.env.ZAI_CONCURRENCY ?? 4))
666
- const evidenceMaxChars = Number(process.env.EVIDENCE_MAX_CHARS ?? 12000)
667
-
668
- const workerModel = process.env.WORKER_MODEL ?? workerModelDefault
669
- const workerBase = process.env.ROUTER_BASE ?? 'https://api.together.xyz/v1'
670
- const glmModel = process.env.GLM_MODEL ?? glmModelDefault
671
- const glmBase = process.env.ZAI_BASE ?? 'https://api.z.ai/api/coding/paas/v4'
672
- const glmMaxTokens = Math.max(8000, Number(process.env.ZAI_MAX_TOKENS ?? 8000))
673
-
674
- const needsWorker = arm !== 'D'
675
- const needsGlm = arm === 'C' || arm === 'D'
676
- const workerCfg: ClientCfg | null = needsWorker
677
- ? { base: workerBase, key: process.env.TANGLE_API_KEY ?? must('TOGETHER_API_KEY'), model: workerModel, maxTokens: Number(process.env.MAX_TOKENS ?? 2500), temperature }
678
- : null
679
- const glmCfg: ClientCfg | null = needsGlm ? { base: glmBase, key: must('ZAI_API_KEY'), model: glmModel, maxTokens: glmMaxTokens, temperature: supTemperature } : null
680
-
681
- const all = await loadHumanEval(164, 0)
682
- const byId = new Map(all.map((t) => [t.taskId, t]))
683
- const tasks = ids.map((id) => {
684
- const t = byId.get(id)
685
- if (!t) throw new Error(`task ${id} not found in HumanEval`)
686
- return t
687
- })
688
-
689
- const needsEvidence = arm === 'B' || arm === 'C'
690
- let evidence: Map<string, EvidenceRow> | null = null
691
- if (needsEvidence) {
692
- evidence = loadEvidence(must('EVIDENCE'))
693
- for (const id of ids) if (!evidence.has(id)) throw new Error(`evidence row missing for ${id}`)
694
- }
695
-
696
- console.log(`=== supervisor-arena · ARM=${arm} SET=${setName} n=${tasks.length} · k=${k} repairs<=${maxRepairs} testgen=${testGen} temp=${temperature} ===`)
697
- console.log(` worker=${needsWorker ? `${workerModel} @ ${workerBase}` : '(none)'} glm=${needsGlm ? `${glmModel} @ ${glmBase} maxTokens=${glmMaxTokens} temp=${supTemperature} conc<=${zaiSlots}` : '(none)'}`)
698
- console.log(` llm-conc=${solveConc} docker-conc=${dockerSlots} evidence=${needsEvidence ? `${process.env.EVIDENCE} (<=${evidenceMaxChars} chars rendered)` : '(none)'}`)
699
- console.log(` Phase A (visible-only arm decisions) → Phase B (hidden nonce-judge grading, script-side)`)
700
-
701
- // Phase A — per-task faults become error rows (persisted, excluded), >15% aborts loud.
702
- let done = 0
703
- let errCount = 0
704
- const outcomes = await pool(tasks, solveConc, async (task): Promise<ArenaRow | { taskId: string; error: string }> => {
705
- try {
706
- let planRaw: string | null = null
707
- let plan: string | null = null
708
- let planLeaked: boolean | null = null
709
- let planEmptyAfterStrip: boolean | null = null
710
- let evidenceChars: number | null = null
711
- let supervisor: ModelSpend | null = null
712
-
713
- if (arm === 'B' || arm === 'C') {
714
- const ev = (evidence as Map<string, EvidenceRow>).get(task.taskId) as EvidenceRow
715
- const rendered = renderEvidence(task, ev, evidenceMaxChars)
716
- evidenceChars = rendered.length
717
- const supCfg: ClientCfg = arm === 'C' ? (glmCfg as ClientCfg) : { ...(workerCfg as ClientCfg), temperature: supTemperature }
718
- const call = () => complete(supCfg, [{ role: 'user', content: supervisorPrompt(rendered) }])
719
- const c = arm === 'C' ? await withZaiSlot(call) : await call()
720
- supervisor = { model: supCfg.model, calls: 1, attempts: c.attempts, tokensIn: c.tokensIn, tokensOut: c.tokensOut }
721
- planRaw = c.content
722
- const stripped = stripPlanCode(c.content)
723
- plan = stripped.plan
724
- planLeaked = stripped.leaked
725
- planEmptyAfterStrip = stripped.leaked && stripped.plan === ''
726
- }
727
-
728
- let row: ArenaRow
729
- if (arm === 'D') {
730
- const c = await withZaiSlot(() => complete(glmCfg as ClientCfg, [{ role: 'user', content: basePrompt(task) }]))
731
- const code = extractCode(c.content)
732
- row = {
733
- arm, set: setName, taskId: task.taskId, k: 1, maxRepairs: 0, temperature: supTemperature,
734
- planRaw: null, plan: null, planLeaked: null, planEmptyAfterStrip: null, evidenceChars: null,
735
- genTests: [], samples: [code], honest: [], selectedIdx: 0, repairs: [], finalCode: code, repairStop: 'solo',
736
- worker: { model: glmModel, calls: 1, attempts: c.attempts, tokensIn: c.tokensIn, tokensOut: c.tokensOut },
737
- supervisor: null,
738
- }
739
- } else {
740
- // A plan stripped to nothing carries no steering signal: the loop runs
741
- // unconditioned (= arm A) and the row records the degenerate plan.
742
- const preamble = plan !== null && plan !== '' ? `A reviewer analyzed previous failed attempts: ${plan}. Follow this guidance.` : null
743
- const w = await runWorkerLoop(workerCfg as ClientCfg, task, k, maxRepairs, testGen, preamble)
744
- row = {
745
- arm, set: setName, taskId: task.taskId, k, maxRepairs, temperature,
746
- planRaw, plan, planLeaked, planEmptyAfterStrip, evidenceChars,
747
- genTests: w.genTests, samples: w.samples, honest: w.honest, selectedIdx: w.selectedIdx,
748
- repairs: w.repairs, finalCode: w.finalCode, repairStop: w.repairStop,
749
- worker: { model: workerModel, calls: w.calls, attempts: w.attempts, tokensIn: w.tokensIn, tokensOut: w.tokensOut },
750
- supervisor,
751
- }
752
- }
753
- done += 1
754
- appendFileSync(`${out}.phaseA`, `${JSON.stringify(row)}\n`)
755
- process.stderr.write(
756
- ` [A ${done}/${tasks.length}] ${task.taskId}: sel=${row.selectedIdx} honest=${row.honest.map((h) => honestScore(h).toFixed(2)).join('/')} repairs=${row.repairs.length} stop=${row.repairStop}${row.planLeaked === null ? '' : ` planLeaked=${row.planLeaked}`}\n`,
757
- )
758
- return row
759
- } catch (e) {
760
- errCount += 1
761
- const error = e instanceof Error ? e.message : String(e)
762
- appendFileSync(`${out}.phaseA`, `${JSON.stringify({ arm, set: setName, taskId: task.taskId, error })}\n`)
763
- process.stderr.write(` [A ERROR] ${task.taskId}: ${error.slice(0, 160)}\n`)
764
- if (errCount > Math.max(3, 0.15 * tasks.length)) throw new Error(`aborting: ${errCount} task errors — harness-level fault, not task noise (last: ${error})`)
765
- return { taskId: task.taskId, error }
766
- }
767
- })
768
-
769
- const okRows = outcomes.filter((o): o is ArenaRow => !('error' in o))
770
- if (errCount > 0) console.log(` WARNING: ${errCount}/${tasks.length} task(s) errored in Phase A — excluded from stats, recorded in ${out}.phaseA`)
771
-
772
- console.log(`\n▶ Phase B: hidden grading (${okRows.length} tasks × samples + finals)`)
773
- const graded: GradedRow[] = await pool(okRows, 16, async (o) => {
774
- const task = byId.get(o.taskId) as HumanEvalTask
775
- const hiddenSamples: number[] = []
776
- for (const s of o.samples) hiddenSamples.push((await runHiddenJudge(task, s)).pass)
777
- const finalIsSelected = o.finalCode === o.samples[o.selectedIdx]
778
- const hiddenFinal = finalIsSelected ? (hiddenSamples[o.selectedIdx] as number) : (await runHiddenJudge(task, o.finalCode)).pass
779
- const g: GradedRow = { ...o, hiddenSamples, hiddenFinal }
780
- appendFileSync(out, `${JSON.stringify(g)}\n`)
781
- return g
782
- })
783
- console.log(` raw rows appended to ${out} (phase-A rows incl. errors: ${out}.phaseA)`)
784
-
785
- // ---------- per-arm summary ----------
786
- const passes = graded.filter((g) => g.hiddenFinal === 1)
787
- const rateName = setName === 'hard' ? 'rescue rate' : 'retention rate'
788
- console.log(`\n${'='.repeat(78)}`)
789
- console.log(`RESULTS · supervisor-arena · ARM=${arm} SET=${setName} n=${graded.length}`)
790
- console.log('='.repeat(78))
791
- console.log(` per-problem hiddenFinal (paired analysis input):`)
792
- console.log(` ${graded.map((g) => `${g.taskId.replace('HumanEval/', 'HE')}=${g.hiddenFinal}`).join(' ')}`)
793
- console.log(` ${rateName}: ${passes.length}/${graded.length} = ${pct(graded.length > 0 ? passes.length / graded.length : 0)}${setName === 'hard' ? ' (every task in this set was hiddenFinal=0 in the committed run)' : ' (every task in this set was hiddenFinal=1 in the committed run)'}`)
794
- if (arm === 'B' || arm === 'C') {
795
- const leaked = graded.filter((g) => g.planLeaked === true)
796
- const emptied = graded.filter((g) => g.planEmptyAfterStrip === true)
797
- console.log(` plan leak rate: ${leaked.length}/${graded.length} plans contained code (stripped before use; ${emptied.length} stripped to empty → ran unconditioned)`)
798
- const evChars = graded.map((g) => g.evidenceChars ?? 0)
799
- if (evChars.length > 0) console.log(` evidence rendered chars: min=${Math.min(...evChars)} max=${Math.max(...evChars)} (cap ${evidenceMaxChars})`)
800
- }
801
- const spend = new Map<string, ModelSpend>()
802
- const add = (s: ModelSpend | null) => {
803
- if (!s) return
804
- const cur = spend.get(s.model) ?? { model: s.model, calls: 0, attempts: 0, tokensIn: 0, tokensOut: 0 }
805
- cur.calls += s.calls
806
- cur.attempts += s.attempts
807
- cur.tokensIn += s.tokensIn
808
- cur.tokensOut += s.tokensOut
809
- spend.set(s.model, cur)
810
- }
811
- for (const g of graded) {
812
- add(g.worker)
813
- add(g.supervisor)
814
- }
815
- console.log(` spend per model:`)
816
- for (const s of spend.values()) console.log(` ${costLine(s)}`)
817
- const stops = [...new Set(graded.map((g) => g.repairStop))]
818
- console.log(` repair stops: ${stops.map((st) => `${st}=${graded.filter((g) => g.repairStop === st).length}`).join(', ')}`)
819
- }
820
-
821
- main().catch((e) => {
822
- reapContainers()
823
- console.error(`supervisor-arena: ${e instanceof Error ? (e.stack ?? e.message) : String(e)}`)
824
- process.exit(1)
825
- })