@tangle-network/agent-bench 0.14.4 → 1.0.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 (187) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +2 -3
  3. package/dist/adapters.d.ts +2 -5
  4. package/dist/adapters.js +3 -4
  5. package/dist/benchmarks/_harness.d.ts +17 -20
  6. package/dist/benchmarks/_harness.js +4 -4
  7. package/dist/benchmarks/_harness.js.map +1 -1
  8. package/dist/benchmarks/aec-bench.d.ts +1 -4
  9. package/dist/benchmarks/aec-bench.js +1 -2
  10. package/dist/benchmarks/agentbench.d.ts +2 -5
  11. package/dist/benchmarks/agentbench.js +1 -2
  12. package/dist/benchmarks/appworld.d.ts +8 -10
  13. package/dist/benchmarks/appworld.js +23 -23
  14. package/dist/benchmarks/appworld.js.map +1 -1
  15. package/dist/benchmarks/bfcl.d.ts +2 -5
  16. package/dist/benchmarks/bfcl.js +1 -2
  17. package/dist/benchmarks/cad-design.d.ts +2 -5
  18. package/dist/benchmarks/cad-design.js +2 -3
  19. package/dist/benchmarks/cad-design.js.map +1 -1
  20. package/dist/benchmarks/cadbench.d.ts +1 -4
  21. package/dist/benchmarks/cadbench.js +1 -2
  22. package/dist/benchmarks/cadgenbench.d.ts +1 -4
  23. package/dist/benchmarks/cadgenbench.js +1 -2
  24. package/dist/benchmarks/commit0.d.ts +2 -5
  25. package/dist/benchmarks/commit0.js +1 -2
  26. package/dist/benchmarks/crag.d.ts +1 -4
  27. package/dist/benchmarks/crag.js +3 -3
  28. package/dist/benchmarks/crag.js.map +1 -1
  29. package/dist/benchmarks/dabstep.d.ts +2 -5
  30. package/dist/benchmarks/dabstep.js +2 -3
  31. package/dist/benchmarks/dabstep.js.map +1 -1
  32. package/dist/benchmarks/enterpriseops-gym.d.ts +2 -5
  33. package/dist/benchmarks/enterpriseops-gym.js +1 -2
  34. package/dist/benchmarks/finresearchbench.d.ts +2 -5
  35. package/dist/benchmarks/finresearchbench.js +2 -3
  36. package/dist/benchmarks/finsearchcomp.d.ts +2 -5
  37. package/dist/benchmarks/finsearchcomp.js +4 -4
  38. package/dist/benchmarks/finsearchcomp.js.map +1 -1
  39. package/dist/benchmarks/frames.d.ts +3 -19
  40. package/dist/benchmarks/frames.js +13 -39
  41. package/dist/benchmarks/frames.js.map +1 -1
  42. package/dist/benchmarks/hotpotqa.d.ts +4 -14
  43. package/dist/benchmarks/hotpotqa.js +12 -32
  44. package/dist/benchmarks/hotpotqa.js.map +1 -1
  45. package/dist/benchmarks/humaneval.d.ts +9 -12
  46. package/dist/benchmarks/humaneval.js +2 -3
  47. package/dist/benchmarks/humaneval.js.map +1 -1
  48. package/dist/benchmarks/mcad-bench.d.ts +13 -16
  49. package/dist/benchmarks/mcad-bench.js +2 -3
  50. package/dist/benchmarks/mcad-bench.js.map +1 -1
  51. package/dist/benchmarks/mcad-cq-bench.d.ts +17 -20
  52. package/dist/benchmarks/mcad-cq-bench.js +2 -3
  53. package/dist/benchmarks/mcad-cq-bench.js.map +1 -1
  54. package/dist/benchmarks/mcad-cq-golds.d.ts +2 -5
  55. package/dist/benchmarks/mcad-cq-golds.js +1 -2
  56. package/dist/benchmarks/mcad-golds.d.ts +1 -4
  57. package/dist/benchmarks/mcad-golds.js +0 -1
  58. package/dist/benchmarks/mcad-tasks.d.ts +5 -8
  59. package/dist/benchmarks/mcad-tasks.js +7 -8
  60. package/dist/benchmarks/mcad-tasks.js.map +1 -1
  61. package/dist/benchmarks/mind2web.d.ts +3 -5
  62. package/dist/benchmarks/mind2web.js +2 -3
  63. package/dist/benchmarks/mind2web.js.map +1 -1
  64. package/dist/benchmarks/nomiracl.d.ts +1 -4
  65. package/dist/benchmarks/nomiracl.js +1 -2
  66. package/dist/benchmarks/open-rag-bench.d.ts +1 -4
  67. package/dist/benchmarks/open-rag-bench.js +3 -3
  68. package/dist/benchmarks/open-rag-bench.js.map +1 -1
  69. package/dist/benchmarks/programbench.d.ts +2 -5
  70. package/dist/benchmarks/programbench.js +1 -2
  71. package/dist/benchmarks/rag-shared.d.ts +30 -22
  72. package/dist/benchmarks/rag-shared.js +8 -2
  73. package/dist/benchmarks/rag-shared.js.map +1 -1
  74. package/dist/benchmarks/ragbench.d.ts +1 -4
  75. package/dist/benchmarks/ragbench.js +3 -3
  76. package/dist/benchmarks/ragbench.js.map +1 -1
  77. package/dist/benchmarks/simpleqa.d.ts +2 -18
  78. package/dist/benchmarks/simpleqa.js +5 -31
  79. package/dist/benchmarks/simpleqa.js.map +1 -1
  80. package/dist/benchmarks/swe-bench.d.ts +7 -10
  81. package/dist/benchmarks/swe-bench.js +4 -4
  82. package/dist/benchmarks/swe-bench.js.map +1 -1
  83. package/dist/benchmarks/t2-ragbench.d.ts +1 -4
  84. package/dist/benchmarks/t2-ragbench.js +3 -3
  85. package/dist/benchmarks/t2-ragbench.js.map +1 -1
  86. package/dist/benchmarks/tau-bench-shared.d.ts +5 -8
  87. package/dist/benchmarks/tau-bench-shared.js +4 -4
  88. package/dist/benchmarks/tau-bench-shared.js.map +1 -1
  89. package/dist/benchmarks/tau2-bench.d.ts +2 -5
  90. package/dist/benchmarks/tau2-bench.js +1 -2
  91. package/dist/benchmarks/tau3-banking.d.ts +1 -4
  92. package/dist/benchmarks/tau3-banking.js +1 -2
  93. package/dist/benchmarks/terminal-bench.d.ts +1 -4
  94. package/dist/benchmarks/terminal-bench.js +4 -4
  95. package/dist/benchmarks/terminal-bench.js.map +1 -1
  96. package/dist/benchmarks/toollm.d.ts +2 -5
  97. package/dist/benchmarks/toollm.js +1 -2
  98. package/dist/benchmarks/trata-hedge.d.ts +1 -4
  99. package/dist/benchmarks/trata-hedge.js +2 -3
  100. package/dist/benchmarks/types.d.ts +6 -9
  101. package/dist/benchmarks/webarena-verified.d.ts +2 -5
  102. package/dist/benchmarks/webarena-verified.js +1 -2
  103. package/dist/{cadbench-BRF-59Mt.js → cadbench-DhAndllg.js} +4 -6
  104. package/dist/cadbench-DhAndllg.js.map +1 -0
  105. package/dist/{cadgenbench-DXtGkuW3.js → cadgenbench-Tvk16YKT.js} +15 -5
  106. package/dist/cadgenbench-Tvk16YKT.js.map +1 -0
  107. package/dist/index.d.ts +8 -18
  108. package/dist/index.js +16 -24
  109. package/dist/index.js.map +1 -1
  110. package/dist/{router-turn-uTYO6KQ1.js → router-turn-DNbQ_GjQ.js} +2 -3
  111. package/dist/router-turn-DNbQ_GjQ.js.map +1 -0
  112. package/fixtures/pier-agent/no-model-task/pre_artifacts.sh +0 -0
  113. package/fixtures/pier-agent/no-model-task/tests/test.sh +0 -0
  114. package/package.json +10 -10
  115. package/pier_agents/tangle_candidate.py +15 -23
  116. package/scripts/run-package-tests.mjs +8 -15
  117. package/src/atom-mcp-e2e.mts +2 -2
  118. package/src/benchmarks/frames.ts +10 -44
  119. package/src/benchmarks/hotpotqa.ts +9 -29
  120. package/src/benchmarks/rag-shared.ts +12 -0
  121. package/src/benchmarks/simpleqa.ts +2 -36
  122. package/src/commit0-prereqs.sh +0 -0
  123. package/src/corpus-replay.mts +8 -8
  124. package/src/corpus-report.mts +21 -21
  125. package/src/corpus.test.mts +5 -5
  126. package/src/corpus.ts +16 -16
  127. package/src/directives.ts +0 -38
  128. package/src/examples/lean-verify.ts +1 -1
  129. package/src/gate.ts +7 -7
  130. package/src/generate-eval/certify.ts +2 -2
  131. package/src/index.ts +1 -0
  132. package/src/refine-loop.ts +5 -5
  133. package/src/resolve-client.ts +1 -1
  134. package/src/router-turn.ts +3 -11
  135. package/src/run-pool.ts +1 -1
  136. package/src/runtime-hook-recorder.ts +2 -2
  137. package/src/search-bench/tasks.ts +1 -1
  138. package/src/selector.test.mts +13 -13
  139. package/src/selector.ts +19 -19
  140. package/src/swe-bench-env.ts +4 -12
  141. package/src/swe-jail.ts +5 -156
  142. package/src/swe-structural-judge-policy.ts +3 -3
  143. package/src/swe-structural-policy.ts +3 -3
  144. package/src/swe-structural-provenance.ts +4 -4
  145. package/src/terminal-compare.ts +10 -10
  146. package/src/worker-blender.ts +2 -106
  147. package/src/worker-build123d.ts +2 -81
  148. package/tb_agents/opencode_router_agent.py +1 -1
  149. package/dist/cadbench-BRF-59Mt.js.map +0 -1
  150. package/dist/cadgenbench-DXtGkuW3.js.map +0 -1
  151. package/dist/router-turn-uTYO6KQ1.js.map +0 -1
  152. package/scripts/cadbench_prepare.py +0 -22
  153. package/scripts/cadgenbench_hard_parts.py +0 -48
  154. package/scripts/clbench_codebase_judge.py +0 -73
  155. package/scripts/render-gate-chart.mjs +0 -176
  156. package/scripts/trata-hedge/README.md +0 -57
  157. package/scripts/trata-hedge/run.sh +0 -64
  158. package/src/cloud-loop.mts +0 -156
  159. package/src/coordination-mcp-container-reach.mts +0 -182
  160. package/src/fleet.mts +0 -143
  161. package/src/hev-structural.mts +0 -697
  162. package/src/humaneval-gate.mts +0 -220
  163. package/src/mbpp-structural.mts +0 -676
  164. package/src/mcp-mount-probe.mts +0 -141
  165. package/src/profiles.ts +0 -128
  166. package/src/research-gate.mts +0 -132
  167. package/src/research-shot.ts +0 -144
  168. package/src/router-executor.ts +0 -51
  169. package/src/sandbox-run.ts +0 -108
  170. package/src/search-bench/bridge.ts +0 -182
  171. package/src/search-bench/export.mts +0 -0
  172. package/src/search-bench/parametric-check.mts +0 -78
  173. package/src/search-bench/profiles.ts +0 -113
  174. package/src/search-bench/run.mts +0 -286
  175. package/src/search-bench/tasks-fresh.ts +0 -688
  176. package/src/smoke-structural-rollout.mts +0 -415
  177. package/src/stats.mts +0 -90
  178. package/src/swe-code-improve.mts +0 -306
  179. package/src/swe-improve.mts +0 -284
  180. package/src/swe-structural.mts +0 -707
  181. package/src/tb-container-executor.mts +0 -266
  182. package/src/tb-container-executor.test.mts +0 -134
  183. package/src/tb-supervisor-sidecar.mts +0 -208
  184. package/src/trata-gepa.mts +0 -381
  185. package/src/trata-hedge-solve.mts +0 -81
  186. package/tb_agents/opencode_refine_agent.py +0 -117
  187. package/tb_agents/opencode_supervisor_agent.py +0 -239
@@ -1,676 +0,0 @@
1
- /**
2
- * MBPP STRUCTURAL lever — the transfer test for the HumanEval result in
3
- * `hev-structural.mts`: best-of-k selection + self-repair grounded ONLY on
4
- * VISIBLE checks, graded on HIDDEN tests the harness never shows the model.
5
- *
6
- * MBPP (sanitized, 427 tasks) has no docstring examples; the standard protocol
7
- * shows the model test_list[0] (it pins the function name/signature). So:
8
- * VISIBLE = test_list[0] (+ TESTGEN model-written asserts, generated from the
9
- * description BEFORE any candidate exists)
10
- * HIDDEN = test_list[1:] (with test_imports) — the grading suite
11
- * A task with <2 asserts cannot split visible/hidden and is dropped at load.
12
- *
13
- * Architecture is hev-structural.mts verbatim (kept self-contained on purpose —
14
- * the HumanEval rig is frozen post-verification): Phase A (harness: sample →
15
- * visible-check select → visible-grounded repair, all decisions locked) then
16
- * Phase B (hidden grading); per-call NONCE sentinels on both judges; global
17
- * docker semaphore; in-container timeout + exit reaper; incremental OUT jsonl;
18
- * per-task error rows with >15% abort; paired bootstrap + exact sign test.
19
- *
20
- * CALIBRATE=1: reference solutions through both judges (hidden self-check must
21
- * be ~100%; failures listed — some MBPP references are known-defective).
22
- *
23
- * TANGLE_API_KEY=… WORKER_MODEL=meta-llama/Meta-Llama-3-8B-Instruct-Lite \
24
- * ROUTER_BASE=https://api.together.xyz/v1 MBPP_JSON=/abs/sanitized-mbpp.json \
25
- * N=427 K=5 REPAIRS=2 TESTGEN=6 TEMPERATURE=0.8 OUT=/abs/rows.jsonl \
26
- * tsx src/mbpp-structural.mts
27
- */
28
- import { execFile, execFileSync } from 'node:child_process'
29
- import { randomBytes } from 'node:crypto'
30
- import { appendFileSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
31
- import { tmpdir } from 'node:os'
32
- import { join, resolve } from 'node:path'
33
- import { fileURLToPath } from 'node:url'
34
- import { extractCode } from './benchmarks/humaneval'
35
- import { runBenchRouterTurn } from './router-turn'
36
- import { type PairedLift, pairedLift, pool } from './stats.mts'
37
-
38
- const dockerImage = 'python:3.12-slim'
39
- const dockerTimeoutMs = Number(process.env.DOCKER_TIMEOUT_MS ?? 20000)
40
-
41
- function must(name: string): string {
42
- const v = process.env[name]
43
- if (!v) throw new Error(`env ${name} is required`)
44
- return v
45
- }
46
-
47
- // ---------- dataset ----------
48
-
49
- export interface MbppTask {
50
- taskId: number
51
- description: string
52
- /** test_list[0] — shown to the model; pins the function name/signature */
53
- shownAssert: string
54
- /** test_list[1:] — the hidden grading suite */
55
- hiddenAsserts: string[]
56
- testImports: string[]
57
- entryPoint: string
58
- /** reference solution — judge self-check only, never shown to the model */
59
- referenceCode: string
60
- }
61
-
62
- interface RawMbpp {
63
- task_id: number
64
- prompt: string
65
- code: string
66
- test_imports?: string[]
67
- test_list: string[]
68
- }
69
-
70
- /** Load sanitized MBPP, sorted by task_id. Drops (and counts) tasks that cannot
71
- * split visible/hidden (<2 asserts) or whose entry point cannot be resolved.
72
- * Entry point = the FIRST called name in test_list[0] that also has a
73
- * `def <name>` in the reference code — `assert set(f(...)) == …` must resolve
74
- * to f, not set. */
75
- export function loadMbpp(limit: number, offset = 0): { tasks: MbppTask[]; droppedShort: number[]; droppedEntry: number[] } {
76
- const path = process.env.MBPP_JSON
77
- if (!path) throw new Error('env MBPP_JSON is required (path to sanitized-mbpp.json)')
78
- const raw = JSON.parse(readFileSync(path, 'utf8')) as RawMbpp[]
79
- raw.sort((a, b) => a.task_id - b.task_id)
80
- const tasks: MbppTask[] = []
81
- const droppedShort: number[] = []
82
- const droppedEntry: number[] = []
83
- for (const d of raw) {
84
- if (!d.test_list || d.test_list.length < 2) {
85
- droppedShort.push(d.task_id)
86
- continue
87
- }
88
- const shown = d.test_list[0] as string
89
- const calls = [...shown.matchAll(/(\w+)\s*\(/g)].map((m) => m[1] as string)
90
- const entry = calls.find((c) => new RegExp(`def\\s+${c}\\s*\\(`).test(d.code))
91
- if (!entry) {
92
- droppedEntry.push(d.task_id)
93
- continue
94
- }
95
- tasks.push({
96
- taskId: d.task_id,
97
- description: d.prompt,
98
- shownAssert: shown,
99
- hiddenAsserts: d.test_list.slice(1),
100
- testImports: d.test_imports ?? [],
101
- entryPoint: entry,
102
- referenceCode: d.code,
103
- })
104
- }
105
- if (offset >= tasks.length) throw new Error(`OFFSET ${offset} >= usable dataset size ${tasks.length}`)
106
- return { tasks: tasks.slice(offset, offset + limit), droppedShort, droppedEntry }
107
- }
108
-
109
- const solveInstruction =
110
- 'Write a Python function for the following task. Output the COMPLETE function definition (plus any imports it needs) inside a single ```python code block. Do not write tests or example calls.'
111
-
112
- export function basePrompt(task: MbppTask): string {
113
- return `${solveInstruction}\n\nTask: ${task.description}\nYour function must satisfy this example test:\n\`\`\`python\n${task.shownAssert}\n\`\`\``
114
- }
115
-
116
- // ---------- docker semaphore + jailed runner (mirrors hev-structural) ----------
117
-
118
- let dockerSlots = 6
119
- let dockerInFlight = 0
120
- const dockerWaiters: Array<() => void> = []
121
- async function withDockerSlot<T>(fn: () => Promise<T>): Promise<T> {
122
- if (dockerInFlight >= dockerSlots) await new Promise<void>((r) => dockerWaiters.push(r))
123
- dockerInFlight += 1
124
- try {
125
- return await fn()
126
- } finally {
127
- dockerInFlight -= 1
128
- dockerWaiters.shift()?.()
129
- }
130
- }
131
-
132
- const containerPrefix = `mbpps-${process.pid}`
133
- let containerSeq = 0
134
-
135
- function reapContainers(): void {
136
- try {
137
- const ids = execFileSync('docker', ['ps', '-aq', '--filter', `name=${containerPrefix}`], { timeout: 10000 }).toString().trim()
138
- if (ids) execFileSync('docker', ['rm', '-f', ...ids.split('\n')], { timeout: 15000 })
139
- } catch {
140
- /* reaper is best-effort by design */
141
- }
142
- }
143
- process.on('SIGINT', () => {
144
- reapContainers()
145
- process.exit(130)
146
- })
147
- process.on('SIGTERM', () => {
148
- reapContainers()
149
- process.exit(143)
150
- })
151
-
152
- interface JailResult {
153
- exitCode: number
154
- stdout: string
155
- stderr: string
156
- }
157
-
158
- function runJailed(program: string): Promise<JailResult> {
159
- return withDockerSlot(
160
- () =>
161
- new Promise<JailResult>((resolvePromise, reject) => {
162
- const dir = mkdtempSync(join(tmpdir(), 'mbpps-'))
163
- writeFileSync(join(dir, 'p.py'), program)
164
- const name = `${containerPrefix}-${containerSeq++}`
165
- let settled = false
166
- const cleanup = () => {
167
- rmSync(dir, { recursive: true, force: true })
168
- execFile('docker', ['rm', '-f', name], () => {})
169
- }
170
- const finish = (res: JailResult) => {
171
- if (settled) return
172
- settled = true
173
- clearTimeout(backstop)
174
- cleanup()
175
- resolvePromise(res)
176
- }
177
- const fail = (e: Error) => {
178
- if (settled) return
179
- settled = true
180
- clearTimeout(backstop)
181
- cleanup()
182
- reject(e)
183
- }
184
- const backstop = setTimeout(() => finish({ exitCode: 124, stdout: '', stderr: 'backstop timeout (no output)' }), dockerTimeoutMs + 5000)
185
- const inContainerSecs = Math.ceil(dockerTimeoutMs / 1000) + 2
186
- execFile(
187
- 'docker',
188
- [
189
- 'run', '--rm', '--name', name, '--network=none', '--cpus=1', '--memory=512m',
190
- '-v', `${dir}:/w:ro`, '-w', '/w', dockerImage,
191
- 'timeout', '-s', 'KILL', String(inContainerSecs), 'python', '/w/p.py',
192
- ],
193
- { timeout: dockerTimeoutMs + 3000, killSignal: 'SIGKILL', maxBuffer: 4 * 1024 * 1024 },
194
- (err, stdout, stderr) => {
195
- if (err) {
196
- const e = err as NodeJS.ErrnoException & { code?: number | string }
197
- if (e.code === 'ENOENT') return fail(new Error('docker binary not found on PATH'))
198
- const se = stderr ?? ''
199
- if (/cannot connect to the docker daemon|is the docker daemon running|permission denied while trying to connect/i.test(se)) {
200
- return fail(new Error(`docker daemon unreachable: ${se.slice(0, 200)}`))
201
- }
202
- if (/(unable to find image|pull access denied|manifest unknown|error response from daemon).*(pull|repository|registry)/i.test(se)) {
203
- return fail(new Error(`docker image ${dockerImage} unavailable: ${se.slice(0, 200)}`))
204
- }
205
- const code = typeof e.code === 'number' ? e.code : 1
206
- return finish({ exitCode: code, stdout: stdout ?? '', stderr: se })
207
- }
208
- finish({ exitCode: 0, stdout: stdout ?? '', stderr: stderr ?? '' })
209
- },
210
- )
211
- }),
212
- )
213
- }
214
-
215
- // ---------- the visible-check judge (Phase A's ONLY signal) ----------
216
-
217
- export interface VisibleResult {
218
- /** total visible checks run: shown assert + generated asserts (-1 = crashed) */
219
- attempted: number
220
- failed: number
221
- failureOutput: string
222
- pass: boolean
223
- sAttempted?: number
224
- sFailed?: number
225
- gAttempted?: number
226
- gFailed?: number
227
- }
228
-
229
- /** Each visible assert runs INDIVIDUALLY in try/except so one malformed line
230
- * cannot zero the rest; per-assert failure text is the repair feedback. The
231
- * hidden asserts (test_list[1:]) never appear here. */
232
- function buildVisibleProgram(task: MbppTask, candidate: string, nonce: string, genTests: string[]): string {
233
- const shownB64 = Buffer.from(JSON.stringify([task.shownAssert]), 'utf8').toString('base64')
234
- const genB64 = Buffer.from(JSON.stringify(genTests), 'utf8').toString('base64')
235
- return `${task.testImports.join('\n')}\n${candidate}\n
236
- import base64 as _b64, json as _json, sys as _sys
237
- _shown = _json.loads(_b64.b64decode("${shownB64}").decode("utf8"))
238
- _gen = _json.loads(_b64.b64decode("${genB64}").decode("utf8"))
239
- _out = []
240
- def _run(_tests):
241
- _att, _fail = 0, 0
242
- for _t in _tests:
243
- _att += 1
244
- try:
245
- exec(_t, dict(globals()))
246
- except Exception as _e:
247
- _fail += 1
248
- _out.append("CHECK FAILED: %s -> %s: %s" % (_t.strip()[:200], type(_e).__name__, str(_e)[:200]))
249
- return _att, _fail
250
- _s_att, _s_fail = _run(_shown)
251
- _g_att, _g_fail = _run(_gen)
252
- _att, _fail = _s_att + _g_att, _s_fail + _g_fail
253
- print("VISIBLE-${nonce} attempted=%d failed=%d satt=%d sfail=%d gatt=%d gfail=%d" % (_att, _fail, _s_att, _s_fail, _g_att, _g_fail))
254
- _sys.stdout.write("\\n".join(_out)[-1500:])
255
- _sys.exit(0 if _att > 0 and _fail == 0 else 1)
256
- `
257
- }
258
-
259
- export async function runVisibleJudge(task: MbppTask, candidate: string, genTests: string[]): Promise<VisibleResult> {
260
- const nonce = randomBytes(8).toString('hex')
261
- const r = await runJailed(buildVisibleProgram(task, candidate, nonce, genTests))
262
- const summary = new RegExp(`VISIBLE-${nonce} attempted=(\\d+) failed=(\\d+) satt=(\\d+) sfail=(\\d+) gatt=(\\d+) gfail=(\\d+)`).exec(r.stdout)
263
- if (!summary) {
264
- const detail = (r.stderr || r.stdout).slice(-1500) || 'timed out (no output)'
265
- return { attempted: -1, failed: -1, failureOutput: detail, pass: false }
266
- }
267
- const attempted = Number(summary[1])
268
- const failed = Number(summary[2])
269
- const failureOutput = r.stdout.replace(summary[0], '').slice(-1500)
270
- return {
271
- attempted,
272
- failed,
273
- failureOutput,
274
- pass: attempted > 0 && failed === 0,
275
- sAttempted: Number(summary[3]),
276
- sFailed: Number(summary[4]),
277
- gAttempted: Number(summary[5]),
278
- gFailed: Number(summary[6]),
279
- }
280
- }
281
-
282
- function visibleScore(h: VisibleResult): number {
283
- if (h.attempted <= 0) return h.attempted === 0 ? 0 : -1
284
- // The shown assert is OFFICIAL (printed in the model's prompt); generated asserts
285
- // are the model's own guesses and run ~70% wrong on MBPP's one-sentence specs
286
- // (measured on the pilot: 71/102 failed on officially-passing code). Rank by the
287
- // official signal first; guesses only break ties — otherwise 6 noisy guesses
288
- // outvote the one reliable check and selection goes NEGATIVE.
289
- const sA = h.sAttempted ?? 0
290
- const gA = h.gAttempted ?? 0
291
- const sFrac = sA > 0 ? (sA - (h.sFailed ?? 0)) / sA : 0
292
- const gFrac = gA > 0 ? (gA - (h.gFailed ?? 0)) / gA : 0
293
- return sFrac + 0.001 * gFrac
294
- }
295
-
296
- // ---------- the hidden judge (Phase B / calibration ONLY) ----------
297
-
298
- function buildHiddenProgram(task: MbppTask, candidate: string, nonce: string): string {
299
- return `${task.testImports.join('\n')}\n${candidate}\n\n${task.hiddenAsserts.join('\n')}\nprint("HIDDEN-${nonce} PASS")\n`
300
- }
301
-
302
- async function runHiddenJudge(task: MbppTask, candidate: string): Promise<{ pass: number; detail?: string }> {
303
- const nonce = randomBytes(8).toString('hex')
304
- const r = await runJailed(buildHiddenProgram(task, candidate, nonce))
305
- if (r.exitCode === 0 && r.stdout.includes(`HIDDEN-${nonce} PASS`)) return { pass: 1 }
306
- return { pass: 0, detail: (r.stderr || r.stdout).slice(-600) || 'timed out (no output)' }
307
- }
308
-
309
- // ---------- model client (mirrors hev-structural) ----------
310
-
311
- interface ClientCfg {
312
- base: string
313
- key: string
314
- model: string
315
- maxTokens: number
316
- temperature: number
317
- }
318
-
319
- interface Completion {
320
- content: string
321
- attempts: number
322
- tokensIn: number
323
- tokensOut: number
324
- }
325
-
326
- async function complete(cfg: ClientCfg, messages: Array<{ role: string; content: string }>): Promise<Completion> {
327
- let lastErr = ''
328
- for (let attempt = 1; attempt <= 4; attempt += 1) {
329
- if (attempt > 1) await new Promise((r) => setTimeout(r, 2000 * 2 ** attempt))
330
- try {
331
- const system = messages.find((message) => message.role === 'system')?.content
332
- const result = await runBenchRouterTurn(
333
- {
334
- routerBaseUrl: cfg.base,
335
- routerKey: cfg.key,
336
- profile: {
337
- name: 'mbpp-structural-worker',
338
- harness: 'cli-base',
339
- model: {
340
- provider: 'tangle-router',
341
- default: cfg.model,
342
- metadata: { temperature: cfg.temperature },
343
- maxVisibleOutputTokens: cfg.maxTokens,
344
- },
345
- ...(system ? { prompt: { systemPrompt: system } } : {}),
346
- },
347
- timeoutMs: Number(process.env.LLM_TIMEOUT_MS ?? 240_000),
348
- },
349
- { messages: messages.filter((message) => message.role !== 'system') },
350
- )
351
- if (result.usage.tokensKnown === false) throw new Error('provider omitted token usage')
352
- const content = result.finalText
353
- if (content.trim() === '') {
354
- lastErr = 'empty content'
355
- continue
356
- }
357
- return {
358
- content,
359
- attempts: attempt,
360
- tokensIn: result.usage.input,
361
- tokensOut: result.usage.output,
362
- }
363
- } catch (e) {
364
- lastErr = e instanceof Error ? e.message : String(e)
365
- }
366
- }
367
- throw new Error(`completion failed after retries: ${lastErr}`)
368
- }
369
-
370
- function extractRepairCode(reply: string): string {
371
- const fences = [...reply.matchAll(/```(?:python|py)?\s*\n([\s\S]*?)```/gi)].map((m) => (m[1] ?? '').trim())
372
- for (let i = fences.length - 1; i >= 0; i -= 1) {
373
- if (/(^|\n)\s*def\s+\w+/.test(fences[i] as string)) return fences[i] as string
374
- }
375
- return extractCode(reply)
376
- }
377
-
378
- // ---------- TESTGEN (mirrors hev-structural; description + shown assert only) ----------
379
-
380
- const testGenInstruction = (count: number, entry: string) =>
381
- `Read the following task description and example test. Write exactly ${count} single-line assert statements that test the function \`${entry}\`, based ONLY on the described behavior. Match the EXACT output type and format the example test shows (if it expects a string, expect a string; if a tuple, a tuple). 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 repeat the example test verbatim if you can test other cases too. Output ONLY the assert lines inside a single \`\`\`python code block.`
382
-
383
- async function generateTests(cfg: ClientCfg, task: MbppTask, count: number): Promise<{ tests: string[]; completion: Completion }> {
384
- const c = await complete(cfg, [
385
- { role: 'user', content: `${testGenInstruction(count, task.entryPoint)}\n\nTask: ${task.description}\nExample test:\n\`\`\`python\n${task.shownAssert}\n\`\`\`` },
386
- ])
387
- const block = extractCode(c.content)
388
- const balanced = (s: string) => {
389
- let d = 0
390
- for (const ch of s) {
391
- if (ch === '(' || ch === '[' || ch === '{') d += 1
392
- else if (ch === ')' || ch === ']' || ch === '}') d -= 1
393
- if (d < 0) return false
394
- }
395
- return d === 0
396
- }
397
- const tests = block
398
- .split('\n')
399
- .map((l) => l.trim())
400
- .filter((l) => l.startsWith('assert ') && l.includes(task.entryPoint) && balanced(l))
401
- .slice(0, count)
402
- return { tests, completion: c }
403
- }
404
-
405
- // ---------- Phase A: the harness (sees ONLY visible information) ----------
406
-
407
- interface HarnessOutcome {
408
- taskId: number
409
- samples: string[]
410
- visible: VisibleResult[]
411
- selectedIdx: number
412
- repairs: Array<{ code: string; visible: VisibleResult }>
413
- finalCode: string
414
- repairStop: string
415
- genTests: string[]
416
- llmCalls: number
417
- llmAttempts: number
418
- tokensIn: number
419
- tokensOut: number
420
- }
421
-
422
- async function runHarnessForTask(cfg: ClientCfg, task: MbppTask, k: number, maxRepairs: number, testGen: number): Promise<HarnessOutcome> {
423
- let llmCalls = 0
424
- let llmAttempts = 0
425
- let tokensIn = 0
426
- let tokensOut = 0
427
- const track = (c: Completion) => {
428
- llmCalls += 1
429
- llmAttempts += c.attempts
430
- tokensIn += c.tokensIn
431
- tokensOut += c.tokensOut
432
- }
433
-
434
- let genTests: string[] = []
435
- if (testGen > 0) {
436
- const g = await generateTests(cfg, task, testGen)
437
- track(g.completion)
438
- genTests = g.tests
439
- }
440
-
441
- const samples: string[] = []
442
- for (let i = 0; i < k; i += 1) {
443
- const c = await complete(cfg, [{ role: 'user', content: basePrompt(task) }])
444
- track(c)
445
- samples.push(extractCode(c.content))
446
- }
447
- const visible: VisibleResult[] = []
448
- for (const s of samples) visible.push(await runVisibleJudge(task, s, genTests))
449
-
450
- let selectedIdx = 0
451
- for (let i = 1; i < k; i += 1) {
452
- if (visibleScore(visible[i] as VisibleResult) > visibleScore(visible[selectedIdx] as VisibleResult)) selectedIdx = i
453
- }
454
-
455
- const selVisible = visible[selectedIdx] as VisibleResult
456
- let best = { code: samples[selectedIdx] as string, visible: selVisible }
457
- const repairs: HarnessOutcome['repairs'] = []
458
- let repairStop = 'already-passing'
459
- if (!selVisible.pass) {
460
- if (selVisible.attempted === 0) {
461
- repairStop = 'no-signal'
462
- } else {
463
- repairStop = 'rounds-exhausted'
464
- let current = best
465
- for (let r = 0; r < maxRepairs; r += 1) {
466
- const repairPrompt = [
467
- 'Your Python function failed some of its checks.',
468
- 'The task:',
469
- task.description,
470
- 'It must satisfy this example test:',
471
- '```python',
472
- task.shownAssert,
473
- '```',
474
- 'Your current attempt:',
475
- '```python',
476
- current.code,
477
- '```',
478
- 'Result of running the checks against your attempt:',
479
- '```',
480
- current.visible.failureOutput.trim() || '(the code crashed before the checks could run)',
481
- '```',
482
- 'Fix the function so the checks pass. Output the COMPLETE corrected function definition inside a single ```python code block. Do not write tests or example calls.',
483
- ].join('\n')
484
- const c = await complete(cfg, [{ role: 'user', content: repairPrompt }])
485
- track(c)
486
- const code = extractRepairCode(c.content)
487
- const h = await runVisibleJudge(task, code, genTests)
488
- repairs.push({ code, visible: h })
489
- if (visibleScore(h) > visibleScore(current.visible)) current = { code, visible: h }
490
- if (visibleScore(current.visible) > visibleScore(best.visible)) best = current
491
- if (h.pass) {
492
- repairStop = 'repaired-pass'
493
- break
494
- }
495
- }
496
- }
497
- }
498
-
499
- return { taskId: task.taskId, samples, visible, selectedIdx, repairs, finalCode: best.code, repairStop, genTests, llmCalls, llmAttempts, tokensIn, tokensOut }
500
- }
501
-
502
- // ---------- statistics (mirrors hev-structural) ----------
503
-
504
- function signTestP(deltas: number[]): { pos: number; neg: number; p: number } {
505
- const pos = deltas.filter((d) => d > 1e-9).length
506
- const neg = deltas.filter((d) => d < -1e-9).length
507
- const m = pos + neg
508
- if (m === 0) return { pos, neg, p: 1 }
509
- const logC: number[] = [0]
510
- for (let i = 1; i <= m; i += 1) logC.push((logC[i - 1] as number) + Math.log(m - i + 1) - Math.log(i))
511
- const pmf = (x: number) => Math.exp((logC[x] as number) - m * Math.LN2)
512
- const extreme = Math.max(pos, neg)
513
- let p = 0
514
- for (let x = extreme; x <= m; x += 1) p += pmf(x)
515
- p *= 2
516
- if (pos === neg) p = 1
517
- return { pos, neg, p: Math.min(1, p) }
518
- }
519
-
520
- // ---------- calibration mode ----------
521
-
522
- async function calibrate(tasks: MbppTask[]): Promise<void> {
523
- console.log(`=== CALIBRATION · MBPP reference solutions vs both judges · n=${tasks.length} ===`)
524
- const rows = await pool(tasks, 16, async (t) => {
525
- const hidden = await runHiddenJudge(t, t.referenceCode)
526
- const visible = await runVisibleJudge(t, t.referenceCode, [])
527
- return { id: t.taskId, hidden: hidden.pass, hiddenDetail: hidden.detail, vAttempted: visible.attempted, vFailed: visible.failed, visiblePass: visible.pass }
528
- })
529
- const hiddenPass = rows.filter((r) => r.hidden === 1)
530
- const visibleFail = rows.filter((r) => !r.visiblePass)
531
- console.log(` hidden judge self-check: ${hiddenPass.length}/${rows.length} reference solutions pass (must be ~100%)`)
532
- if (hiddenPass.length < rows.length) {
533
- for (const r of rows.filter((x) => x.hidden !== 1)) console.log(` hidden FAIL ${r.id}: ${(r.hiddenDetail ?? '').replace(/\n/g, ' | ').slice(0, 160)}`)
534
- }
535
- console.log(` visible-check false-fail on reference: ${visibleFail.length}/${rows.length}`)
536
- if (visibleFail.length > 0) console.log(` visible false-fail ids: ${visibleFail.map((r) => `${r.id}(${r.vFailed}/${r.vAttempted})`).join(', ')}`)
537
- }
538
-
539
- // ---------- main ----------
540
-
541
- const pct = (x: number) => `${(x * 100).toFixed(1)}%`
542
- const pp = (x: number) => `${x >= 0 ? '+' : ''}${(x * 100).toFixed(1)}pp`
543
-
544
- interface GradedRow extends HarnessOutcome {
545
- hiddenSamples: number[]
546
- hiddenFinal: number
547
- }
548
-
549
- async function main(): Promise<void> {
550
- const n = Number(process.env.N ?? 427)
551
- const k = Number(process.env.K ?? 5)
552
- const maxRepairs = Number(process.env.REPAIRS ?? 2)
553
- const offset = Number(process.env.OFFSET ?? 0)
554
- const temperature = Number(process.env.TEMPERATURE ?? 0.8)
555
- const model = process.env.WORKER_MODEL ?? 'meta-llama/Meta-Llama-3-8B-Instruct-Lite'
556
- const base = process.env.ROUTER_BASE ?? 'https://api.together.xyz/v1'
557
- const solveConc = Number(process.env.CONCURRENCY ?? 6)
558
- dockerSlots = Number(process.env.DOCKER_CONCURRENCY ?? 6)
559
- const testGen = Number(process.env.TESTGEN ?? 0)
560
- const out = process.env.OUT
561
-
562
- const { tasks, droppedShort, droppedEntry } = loadMbpp(n, offset)
563
- console.log(`loaded ${tasks.length} MBPP task(s); dropped ${droppedShort.length} (<2 asserts: ${droppedShort.join(',') || '-'}), ${droppedEntry.length} (entry unresolved: ${droppedEntry.join(',') || '-'})`)
564
-
565
- if (process.env.CALIBRATE === '1') {
566
- await calibrate(tasks)
567
- return
568
- }
569
-
570
- const cfg: ClientCfg = { base, key: must('TANGLE_API_KEY'), model, maxTokens: Number(process.env.MAX_TOKENS ?? 2500), temperature }
571
-
572
- console.log(`=== MBPP STRUCTURAL lever · visible=test_list[0]+gen · hidden=test_list[1:] · n=${tasks.length} k=${k} repairs<=${maxRepairs} temp=${temperature} testgen=${testGen} ===`)
573
- console.log(` model=${model} base=${base} llm-conc=${solveConc} docker-conc=${dockerSlots} (global semaphore)`)
574
-
575
- let done = 0
576
- let errCount = 0
577
- const outcomes = await pool(tasks, solveConc, async (task): Promise<HarnessOutcome | { taskId: number; error: string }> => {
578
- try {
579
- const o = await runHarnessForTask(cfg, task, k, maxRepairs, testGen)
580
- done += 1
581
- if (out) appendFileSync(`${out}.phaseA`, `${JSON.stringify({ model, temperature, k, maxRepairs, ...o })}\n`)
582
- process.stderr.write(
583
- ` [A ${done}/${tasks.length}] mbpp/${o.taskId}: sel=${o.selectedIdx} visible=${o.visible.map((h) => visibleScore(h).toFixed(2)).join('/')} repairs=${o.repairs.length} stop=${o.repairStop}\n`,
584
- )
585
- return o
586
- } catch (e) {
587
- errCount += 1
588
- const error = e instanceof Error ? e.message : String(e)
589
- if (out) appendFileSync(`${out}.phaseA`, `${JSON.stringify({ model, taskId: task.taskId, error })}\n`)
590
- process.stderr.write(` [A ERROR] mbpp/${task.taskId}: ${error.slice(0, 160)}\n`)
591
- if (errCount > Math.max(3, 0.15 * tasks.length)) throw new Error(`aborting: ${errCount} task errors — harness-level fault, not task noise (last: ${error})`)
592
- return { taskId: task.taskId, error }
593
- }
594
- })
595
-
596
- const okOutcomes = outcomes.filter((o): o is HarnessOutcome => !('error' in o))
597
- const okTasks = okOutcomes.map((o) => tasks.find((t) => t.taskId === o.taskId) as MbppTask)
598
- if (errCount > 0) console.log(` WARNING: ${errCount}/${tasks.length} task(s) errored in Phase A — excluded from stats, recorded in ${out ?? '(no OUT set)'}.phaseA`)
599
-
600
- console.log(`\n▶ Phase B: hidden grading (${okOutcomes.length} tasks × ${k} samples + finals)`)
601
- const graded: GradedRow[] = await pool(okOutcomes, 16, async (o, ti) => {
602
- const task = okTasks[ti] as MbppTask
603
- const hiddenSamples: number[] = []
604
- for (const s of o.samples) hiddenSamples.push((await runHiddenJudge(task, s)).pass)
605
- const finalIsSelected = o.finalCode === o.samples[o.selectedIdx]
606
- const hiddenFinal = finalIsSelected ? (hiddenSamples[o.selectedIdx] as number) : (await runHiddenJudge(task, o.finalCode)).pass
607
- const g: GradedRow = { ...o, hiddenSamples, hiddenFinal }
608
- if (out) appendFileSync(out, `${JSON.stringify({ model, temperature, k, maxRepairs, ...g })}\n`)
609
- return g
610
- })
611
- if (out) console.log(` raw rows appended to ${out} (phase-A rows incl. errors: ${out}.phaseA)`)
612
-
613
- const blind1First = graded.map((g) => g.hiddenSamples[0] as number)
614
- const blind1Mean = graded.map((g) => g.hiddenSamples.reduce((s, x) => s + x, 0) / g.hiddenSamples.length)
615
- const selected = graded.map((g) => g.hiddenSamples[g.selectedIdx] as number)
616
- const repaired = graded.map((g) => g.hiddenFinal)
617
- const oracleK = graded.map((g) => (g.hiddenSamples.some((x) => x === 1) ? 1 : 0))
618
- const covered = graded.map((g) => (g.visible.some((h) => h.attempted > 0) ? 1 : 0))
619
- const rate = (xs: number[]) => xs.reduce((s, x) => s + x, 0) / xs.length
620
- const llmCallsTotal = graded.reduce((s, g) => s + g.llmCalls, 0)
621
- const llmAttemptsTotal = graded.reduce((s, g) => s + g.llmAttempts, 0)
622
- const tokensInTotal = graded.reduce((s, g) => s + g.tokensIn, 0)
623
- const tokensOutTotal = graded.reduce((s, g) => s + g.tokensOut, 0)
624
- const repairFired = graded.filter((g) => g.repairs.length > 0)
625
-
626
- console.log(`\n${'='.repeat(78)}`)
627
- console.log(`RESULTS · MBPP structural lever · n=${graded.length} · k=${k} · repairs<=${maxRepairs} · temp=${temperature} · ${model}`)
628
- console.log('='.repeat(78))
629
- console.log(` visible-check coverage ${pct(rate(covered))} of tasks (shown assert always present)`)
630
- console.log(` blind pass@1 (mean of k) ${pct(rate(blind1Mean))} [PRIMARY baseline — ${k}-rep estimator]`)
631
- console.log(` blind pass@1 (first sample) ${pct(rate(blind1First))} [single-rep reference]`)
632
- console.log(` selected@1 (visible argmax) ${pct(rate(selected))}`)
633
- console.log(` repaired@1 (full harness) ${pct(rate(repaired))}`)
634
- console.log(` oracle pass@${k} (ceiling) ${pct(rate(oracleK))}`)
635
- console.log(
636
- ` compute: ${llmCallsTotal} llm calls (${llmAttemptsTotal} incl. retries) = ${(llmCallsTotal / graded.length).toFixed(2)}/task; tokens in/out ${tokensInTotal}/${tokensOutTotal} (blind@1 spends 1 call/task)`,
637
- )
638
- console.log(` repair fired on ${repairFired.length}/${graded.length} tasks (stop: ${['already-passing', 'no-signal', 'repaired-pass', 'rounds-exhausted'].map((s) => `${s}=${graded.filter((g) => g.repairStop === s).length}`).join(', ')})`)
639
-
640
- const row = (label: string, baseline: number[], treatment: number[]) => {
641
- const l = pairedLift(baseline, treatment)
642
- const st = signTestP(baseline.map((b, i) => (treatment[i] as number) - b))
643
- console.log(
644
- ` ${label.padEnd(36)} ${pp(l.point).padStart(7)} CI [${pp(l.low)}, ${pp(l.high)}] sign-test p=${st.p < 0.001 ? st.p.toExponential(1) : st.p.toFixed(3)} (+${st.pos}/−${st.neg}) (pairs ${l.pairs})`,
645
- )
646
- return { l, st }
647
- }
648
-
649
- console.log(`\n PAIRED LIFTS vs blind pass@1 (mean-of-${k}) · 95% bootstrap CI (B=10000) + exact sign test:`)
650
- const sel = row('selected@1 − blind@1 (selection)', blind1Mean, selected)
651
- const rep = row('repaired@1 − blind@1 (full harness)', blind1Mean, repaired)
652
- row('repaired@1 − selected@1 (repair)', selected, repaired)
653
- row(`oracle@${k} − repaired@1 (unrealized)`, repaired, oracleK)
654
-
655
- const coveredIdx = graded.map((_, i) => i).filter((i) => covered[i] === 1)
656
- if (coveredIdx.length > 0 && coveredIdx.length < graded.length) {
657
- const pick = (xs: number[]) => coveredIdx.map((i) => xs[i] as number)
658
- console.log(`\n COVERED-ONLY subgroup (n=${coveredIdx.length}):`)
659
- row(' selected@1 − blind@1', pick(blind1Mean), pick(selected))
660
- row(' repaired@1 − blind@1', pick(blind1Mean), pick(repaired))
661
- }
662
-
663
- const verdict = (name: string, r: { l: PairedLift; st: { p: number } }) =>
664
- `${name}: ${pp(r.l.point)} — ${r.l.low > 0 && r.st.p < 0.05 ? 'POSITIVE (CI excludes 0 AND sign-test p<0.05)' : r.l.high < 0 && r.st.p < 0.05 ? 'NEGATIVE' : 'n.s.'}`
665
- console.log(`\n VERDICT: ${verdict('full harness', rep)}; ${verdict('selection alone', sel)}`)
666
- }
667
-
668
- // Entrypoint guard (corpus-replay.mts precedent): campaign scripts import this module
669
- // for loadMbpp/basePrompt; the benchmark itself only runs when executed directly.
670
- if (process.argv[1] && fileURLToPath(import.meta.url) === resolve(process.argv[1])) {
671
- main().catch((e) => {
672
- reapContainers()
673
- console.error(`mbpp-structural: ${e instanceof Error ? (e.stack ?? e.message) : String(e)}`)
674
- process.exit(1)
675
- })
676
- }