@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,697 +0,0 @@
1
- /**
2
- * HumanEval STRUCTURAL lever — best-of-k selection + self-repair grounded ONLY on the
3
- * VISIBLE docstring `>>>` examples (the honest oracle), graded on the HIDDEN check()
4
- * suite. This is the experiment the self-improvement push identified but never ran:
5
- * the existing gates (`humaneval-gate.mts`, `humaneval-repair-gate.mts`) select/steer
6
- * on the task's own grading test — defensible in a deployable-verifier framing, but
7
- * NOT a benchmark-lift claim. Here the harness sees nothing the model can't already
8
- * read in its prompt.
9
- *
10
- * Honesty by construction — two physically separated phases:
11
- * Phase A (harness): k samples/task at one temperature → honest doctest score per
12
- * sample (docker, --network=none) → argmax select → ≤R repair rounds steered by
13
- * the doctest FAILURE OUTPUT → final artifact locked. No access to task.test.
14
- * Phase B (grading): the hidden check() suite grades every sample and every locked
15
- * final. Nothing from this phase flows back.
16
- *
17
- * Judge integrity (adversarially reviewed; both spoof channels closed):
18
- * - both judges print a per-call random NONCE sentinel and the verdict is parsed
19
- * from that exact nonce — a candidate printing a forged summary line cannot win;
20
- * - the hidden judge requires the sentinel, not exit-0 — `sys.exit(0)` before
21
- * check() is a FAIL, not a pass;
22
- * - containers run under an in-container `timeout -s KILL` so a hung candidate
23
- * cannot outlive a crashed harness; a process-exit reaper force-removes strays.
24
- *
25
- * Estimators (paired across the same tasks, same sample batch):
26
- * blind1_mean — mean hidden-pass over ALL k samples = expected pass@1 at this
27
- * temperature (a built-in k-rep baseline; the primary control)
28
- * blind1_first — hidden-pass of sample 0 (single-rep reference only)
29
- * selected@1 — hidden-pass of the honest-oracle argmax sample (selection value)
30
- * repaired@1 — hidden-pass of the final after honest-grounded repair (full harness)
31
- * oracle@k — any sample passes hidden (the pass@k ceiling)
32
- * Every lift carries a 95% paired-bootstrap CI (B=10000, seeded) AND an exact
33
- * two-sided sign test — the bootstrap alone is anticonservative when few tasks move.
34
- *
35
- * CALIBRATE=1 skips the model entirely: canonical solutions vs both judges →
36
- * hidden-judge self-check (must be ~100%) + honest-oracle coverage & false-fail rate.
37
- *
38
- * TANGLE_API_KEY=… WORKER_MODEL=meta-llama/Meta-Llama-3-8B-Instruct-Lite \
39
- * ROUTER_BASE=https://api.together.xyz/v1 HUMANEVAL_GZ=/abs/HumanEval.jsonl.gz \
40
- * N=164 K=5 REPAIRS=2 TEMPERATURE=0.8 OUT=/abs/rows.jsonl tsx src/hev-structural.mts
41
- */
42
- import { execFile, execFileSync } from 'node:child_process'
43
- import { randomBytes } from 'node:crypto'
44
- import { appendFileSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
45
- import { tmpdir } from 'node:os'
46
- import { join } from 'node:path'
47
- import { type HumanEvalTask, extractCode, loadHumanEval } from './benchmarks/humaneval'
48
- import { composeStrategies } from './directives'
49
- import { runBenchRouterTurn } from './router-turn'
50
- import { type PairedLift, pairedLift, pool } from './stats.mts'
51
-
52
- const dockerImage = 'python:3.12-slim'
53
- const dockerTimeoutMs = Number(process.env.DOCKER_TIMEOUT_MS ?? 20000)
54
-
55
- const solveInstruction =
56
- 'Complete the following Python function. Output the COMPLETE function definition (signature, docstring optional, body) inside a single ```python code block. Include any imports the function needs. Do not write tests or example calls.'
57
-
58
- function must(name: string): string {
59
- const v = process.env[name]
60
- if (!v) throw new Error(`env ${name} is required`)
61
- return v
62
- }
63
-
64
- // ---------- docker semaphore + jailed runner (shared by BOTH judges) ----------
65
- // Phase A workers each run docker calls too, so the container count must be bounded
66
- // by ONE global semaphore, not by whichever pool happens to wrap the caller.
67
-
68
- let dockerSlots = 6
69
- let dockerInFlight = 0
70
- const dockerWaiters: Array<() => void> = []
71
- async function withDockerSlot<T>(fn: () => Promise<T>): Promise<T> {
72
- if (dockerInFlight >= dockerSlots) await new Promise<void>((r) => dockerWaiters.push(r))
73
- dockerInFlight += 1
74
- try {
75
- return await fn()
76
- } finally {
77
- dockerInFlight -= 1
78
- dockerWaiters.shift()?.()
79
- }
80
- }
81
-
82
- const containerPrefix = `hevs-${process.pid}`
83
- let containerSeq = 0
84
-
85
- // Best-effort stray-container reap on any exit path (crash, SIGINT, clean end).
86
- function reapContainers(): void {
87
- try {
88
- const ids = execFileSync('docker', ['ps', '-aq', '--filter', `name=${containerPrefix}`], { timeout: 10000 }).toString().trim()
89
- if (ids) execFileSync('docker', ['rm', '-f', ...ids.split('\n')], { timeout: 15000 })
90
- } catch {
91
- /* reaper is best-effort by design */
92
- }
93
- }
94
- process.on('SIGINT', () => {
95
- reapContainers()
96
- process.exit(130)
97
- })
98
- process.on('SIGTERM', () => {
99
- reapContainers()
100
- process.exit(143)
101
- })
102
-
103
- interface JailResult {
104
- exitCode: number
105
- stdout: string
106
- stderr: string
107
- }
108
-
109
- /** Run one python program in the jail: --network=none, cpu/mem caps, an IN-CONTAINER
110
- * `timeout -s KILL` (so a hung candidate's container self-terminates even if this
111
- * process dies), a client timeout, and a backstop. Docker INFRA faults (daemon,
112
- * image, permission) throw — a broken checker must fail loud, not score zeros. */
113
- function runJailed(program: string): Promise<JailResult> {
114
- return withDockerSlot(
115
- () =>
116
- new Promise<JailResult>((resolvePromise, reject) => {
117
- const dir = mkdtempSync(join(tmpdir(), 'hevs-'))
118
- writeFileSync(join(dir, 'p.py'), program)
119
- const name = `${containerPrefix}-${containerSeq++}`
120
- let settled = false
121
- const cleanup = () => {
122
- rmSync(dir, { recursive: true, force: true })
123
- execFile('docker', ['rm', '-f', name], () => {})
124
- }
125
- const finish = (res: JailResult) => {
126
- if (settled) return
127
- settled = true
128
- clearTimeout(backstop)
129
- cleanup()
130
- resolvePromise(res)
131
- }
132
- const fail = (e: Error) => {
133
- if (settled) return
134
- settled = true
135
- clearTimeout(backstop)
136
- cleanup()
137
- reject(e)
138
- }
139
- const backstop = setTimeout(() => finish({ exitCode: 124, stdout: '', stderr: 'backstop timeout (no output)' }), dockerTimeoutMs + 5000)
140
- const inContainerSecs = Math.ceil(dockerTimeoutMs / 1000) + 2
141
- execFile(
142
- 'docker',
143
- [
144
- 'run', '--rm', '--name', name, '--network=none', '--cpus=1', '--memory=512m',
145
- '-v', `${dir}:/w:ro`, '-w', '/w', dockerImage,
146
- 'timeout', '-s', 'KILL', String(inContainerSecs), 'python', '/w/p.py',
147
- ],
148
- { timeout: dockerTimeoutMs + 3000, killSignal: 'SIGKILL', maxBuffer: 4 * 1024 * 1024 },
149
- (err, stdout, stderr) => {
150
- if (err) {
151
- const e = err as NodeJS.ErrnoException & { code?: number | string }
152
- if (e.code === 'ENOENT') return fail(new Error('docker binary not found on PATH'))
153
- const se = stderr ?? ''
154
- if (/cannot connect to the docker daemon|is the docker daemon running|permission denied while trying to connect/i.test(se)) {
155
- return fail(new Error(`docker daemon unreachable: ${se.slice(0, 200)}`))
156
- }
157
- if (/(unable to find image|pull access denied|manifest unknown|error response from daemon).*(pull|repository|registry)/i.test(se)) {
158
- return fail(new Error(`docker image ${dockerImage} unavailable: ${se.slice(0, 200)}`))
159
- }
160
- const code = typeof e.code === 'number' ? e.code : 1
161
- return finish({ exitCode: code, stdout: stdout ?? '', stderr: se })
162
- }
163
- finish({ exitCode: 0, stdout: stdout ?? '', stderr: stderr ?? '' })
164
- },
165
- )
166
- }),
167
- )
168
- }
169
-
170
- // ---------- the honest oracle: doctest over the VISIBLE docstring examples ----------
171
-
172
- export interface HonestResult {
173
- /** total visible checks: doctest examples + model-generated asserts (0 = no
174
- * signal, -1 = the candidate crashed before the oracle could run) */
175
- attempted: number
176
- failed: number
177
- /** doctest's failure report — the ONLY feedback the repair loop may see */
178
- failureOutput: string
179
- /** attempted > 0 && failed === 0 */
180
- pass: boolean
181
- /** split for post-hoc audit: doctest vs generated-assert counts */
182
- dAttempted?: number
183
- dFailed?: number
184
- gAttempted?: number
185
- gFailed?: number
186
- }
187
-
188
- /** The honest program: candidate executes (prompt header first, for its imports;
189
- * candidate def shadows the stub), then doctest runs the examples taken from the
190
- * STUB's `__doc__` (parsing the raw prompt text instead swallows the closing `"""`
191
- * into the last example — caught by CALIBRATE=1). Verdict line carries a per-call
192
- * NONCE so candidate-printed forgeries can't be parsed as the summary. task.test
193
- * never appears here. */
194
- function buildHonestProgram(task: HumanEvalTask, candidate: string, nonce: string, genTests: string[] = []): string {
195
- const promptB64 = Buffer.from(task.prompt, 'utf8').toString('base64')
196
- const entryB64 = Buffer.from(task.entryPoint, 'utf8').toString('base64')
197
- const genB64 = Buffer.from(JSON.stringify(genTests), 'utf8').toString('base64')
198
- return `${task.prompt}\n${candidate}\n
199
- import ast as _ast, base64 as _b64, doctest as _doctest, io as _io, json as _json, sys as _sys
200
- _prompt_text = _b64.b64decode("${promptB64}").decode("utf8")
201
- _entry = _b64.b64decode("${entryB64}").decode("utf8")
202
- _gen_tests = _json.loads(_b64.b64decode("${genB64}").decode("utf8"))
203
- _stub_ns = {}
204
- exec(_prompt_text, _stub_ns)
205
- _doc = getattr(_stub_ns.get(_entry), "__doc__", None) or ""
206
- try:
207
- _examples = _doctest.DocTestParser().get_examples(_doc)
208
- except ValueError:
209
- _examples = [] # malformed docstring indentation -> no usable signal, not a crash
210
-
211
- # Dataset-quirk normalizations, all decidable from VISIBLE output alone:
212
- # assertion-style examples ("f(x) == 0" with no expected output) pass iff they print True;
213
- # quote-style repr mismatches ("21" vs '21') compare by literal value.
214
- class _Checker(_doctest.OutputChecker):
215
- def check_output(self, want, got, optionflags):
216
- if super().check_output(want, got, optionflags):
217
- return True
218
- if want.strip() == "" and got.strip() == "True":
219
- return True
220
- try:
221
- return _ast.literal_eval(want.strip()) == _ast.literal_eval(got.strip())
222
- except Exception:
223
- return False
224
-
225
- _test = _doctest.DocTest(_examples, globs=dict(globals()), name="visible", filename="p", lineno=0, docstring=_doc)
226
- _runner = _doctest.DocTestRunner(checker=_Checker(), verbose=False, optionflags=_doctest.NORMALIZE_WHITESPACE | _doctest.IGNORE_EXCEPTION_DETAIL)
227
- _buf = _io.StringIO()
228
- _res = _runner.run(_test, out=_buf.write)
229
-
230
- # Model-generated asserts (CodeT-style; written from the prompt BEFORE any candidate
231
- # existed). Each runs individually so one malformed assert doesn't zero the rest.
232
- _g_att, _g_fail = 0, 0
233
- for _t in _gen_tests:
234
- _g_att += 1
235
- try:
236
- exec(_t, dict(globals()))
237
- except Exception as _e:
238
- _g_fail += 1
239
- _buf.write("GENTEST FAILED: %s -> %s: %s\\n" % (_t.strip()[:200], type(_e).__name__, str(_e)[:200]))
240
-
241
- _att = _res.attempted + _g_att
242
- _fail = _res.failed + _g_fail
243
- 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))
244
- _sys.stdout.write(_buf.getvalue()[-1500:])
245
- _sys.exit(0 if _att > 0 and _fail == 0 else 1)
246
- `
247
- }
248
-
249
- export async function runHonestOracle(task: HumanEvalTask, candidate: string, genTests: string[] = []): Promise<HonestResult> {
250
- const nonce = randomBytes(8).toString('hex')
251
- const r = await runJailed(buildHonestProgram(task, candidate, nonce, genTests))
252
- const summary = new RegExp(`HONEST-${nonce} attempted=(\\d+) failed=(\\d+) datt=(\\d+) dfail=(\\d+) gatt=(\\d+) gfail=(\\d+)`).exec(r.stdout)
253
- if (!summary) {
254
- // candidate crashed / hung before the oracle scaffold could report
255
- const detail = (r.stderr || r.stdout).slice(-1500) || 'timed out (no output)'
256
- return { attempted: -1, failed: -1, failureOutput: detail, pass: false }
257
- }
258
- const attempted = Number(summary[1])
259
- const failed = Number(summary[2])
260
- // Strip the sentinel line from the feedback shown to the repair loop — the model
261
- // must never learn the summary format it could try to forge.
262
- const failureOutput = r.stdout.replace(summary[0], '').slice(-1500)
263
- return {
264
- attempted,
265
- failed,
266
- failureOutput,
267
- pass: attempted > 0 && failed === 0,
268
- dAttempted: Number(summary[3]),
269
- dFailed: Number(summary[4]),
270
- gAttempted: Number(summary[5]),
271
- gFailed: Number(summary[6]),
272
- }
273
- }
274
-
275
- // ---------- CodeT-style test generation (visible info only, BEFORE any candidate) ----------
276
-
277
- const testGenInstruction = (count: number, entry: string) =>
278
- `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.`
279
-
280
- /** One LLM call per task, before sampling. Keeps only single-line, paren-balanced
281
- * asserts that reference the entry point — malformed lines are dropped here rather
282
- * than poisoning every candidate's score identically. */
283
- async function generateTests(cfg: ClientCfg, task: HumanEvalTask, count: number): Promise<{ tests: string[]; completion: Completion }> {
284
- const c = await complete(cfg, [
285
- { role: 'user', content: `${testGenInstruction(count, task.entryPoint)}\n\n\`\`\`python\n${task.prompt}\`\`\`` },
286
- ])
287
- const block = extractCode(c.content)
288
- const balanced = (s: string) => {
289
- let d = 0
290
- for (const ch of s) {
291
- if (ch === '(' || ch === '[' || ch === '{') d += 1
292
- else if (ch === ')' || ch === ']' || ch === '}') d -= 1
293
- if (d < 0) return false
294
- }
295
- return d === 0
296
- }
297
- const tests = block
298
- .split('\n')
299
- .map((l) => l.trim())
300
- .filter((l) => l.startsWith('assert ') && l.includes(task.entryPoint) && balanced(l))
301
- .slice(0, count)
302
- return { tests, completion: c }
303
- }
304
-
305
- /** Honest score for ranking: fraction of visible examples passed; a candidate that
306
- * crashed before doctest ran ranks below one that ran and failed everything. */
307
- function honestScore(h: HonestResult): number {
308
- if (h.attempted <= 0) return h.attempted === 0 ? 0 : -1
309
- return (h.attempted - h.failed) / h.attempted
310
- }
311
-
312
- // ---------- the hidden judge (Phase B / calibration ONLY) ----------
313
- // Rig-local rather than the shared runChecker: pass requires the nonce sentinel that
314
- // check() prints AFTER succeeding — exit-0-before-check (sys.exit(0) in a candidate)
315
- // is a fail here, where trusting the exit code alone would score it a pass.
316
-
317
- function buildHiddenProgram(task: HumanEvalTask, candidate: string, nonce: string): string {
318
- return `${task.prompt}\n${candidate}\n\n${task.test}\n\ncheck(${task.entryPoint})\nprint("HIDDEN-${nonce} PASS")\n`
319
- }
320
-
321
- async function runHiddenJudge(task: HumanEvalTask, candidate: string): Promise<{ pass: number; detail?: string }> {
322
- const nonce = randomBytes(8).toString('hex')
323
- const r = await runJailed(buildHiddenProgram(task, candidate, nonce))
324
- if (r.exitCode === 0 && r.stdout.includes(`HIDDEN-${nonce} PASS`)) return { pass: 1 }
325
- return { pass: 0, detail: (r.stderr || r.stdout).slice(-600) || 'timed out (no output)' }
326
- }
327
-
328
- // ---------- model client (plain fetch; retries on transient HTTP + empty content) ----------
329
-
330
- interface ClientCfg {
331
- base: string
332
- key: string
333
- model: string
334
- maxTokens: number
335
- temperature: number
336
- }
337
-
338
- interface Completion {
339
- content: string
340
- attempts: number
341
- tokensIn: number
342
- tokensOut: number
343
- }
344
-
345
- async function complete(cfg: ClientCfg, messages: Array<{ role: string; content: string }>): Promise<Completion> {
346
- let lastErr = ''
347
- for (let attempt = 1; attempt <= 4; attempt += 1) {
348
- if (attempt > 1) await new Promise((r) => setTimeout(r, 2000 * 2 ** attempt))
349
- try {
350
- const system = messages.find((message) => message.role === 'system')?.content
351
- const result = await runBenchRouterTurn(
352
- {
353
- routerBaseUrl: cfg.base,
354
- routerKey: cfg.key,
355
- profile: {
356
- name: 'humaneval-structural-worker',
357
- harness: 'cli-base',
358
- model: {
359
- provider: 'tangle-router',
360
- default: cfg.model,
361
- metadata: { temperature: cfg.temperature },
362
- maxVisibleOutputTokens: cfg.maxTokens,
363
- },
364
- ...(system ? { prompt: { systemPrompt: system } } : {}),
365
- },
366
- timeoutMs: Number(process.env.LLM_TIMEOUT_MS ?? 240_000),
367
- },
368
- { messages: messages.filter((message) => message.role !== 'system') },
369
- )
370
- if (result.usage.tokensKnown === false) throw new Error('provider omitted token usage')
371
- const content = result.finalText
372
- // Reasoning models starve `content` when reasoning exhausts max_tokens — an
373
- // empty reply is a transient fault to retry, not a candidate to score.
374
- if (content.trim() === '') {
375
- lastErr = 'empty content'
376
- continue
377
- }
378
- return {
379
- content,
380
- attempts: attempt,
381
- tokensIn: result.usage.input,
382
- tokensOut: result.usage.output,
383
- }
384
- } catch (e) {
385
- lastErr = e instanceof Error ? e.message : String(e)
386
- }
387
- }
388
- throw new Error(`completion failed after retries: ${lastErr}`)
389
- }
390
-
391
- /** Repair replies often echo the failure report in a bare ``` block before the fixed
392
- * code — first-fence extraction would grab the echo. Prefer the LAST fenced block
393
- * that contains a `def`, else fall back to the shared extractor. Purely mechanical
394
- * parsing of the model's own reply; no task information involved. */
395
- function extractRepairCode(reply: string): string {
396
- const fences = [...reply.matchAll(/```(?:python|py)?\s*\n([\s\S]*?)```/gi)].map((m) => (m[1] ?? '').trim())
397
- for (let i = fences.length - 1; i >= 0; i -= 1) {
398
- if (/(^|\n)\s*def\s+\w+/.test(fences[i] as string)) return fences[i] as string
399
- }
400
- return extractCode(reply)
401
- }
402
-
403
- // ---------- Phase A: the harness (sees ONLY visible information) ----------
404
-
405
- interface HarnessOutcome {
406
- taskId: string
407
- samples: string[]
408
- honest: HonestResult[]
409
- selectedIdx: number
410
- repairs: Array<{ code: string; honest: HonestResult }>
411
- finalCode: string
412
- /** 'already-passing' | 'no-signal' | 'repaired-pass' | 'rounds-exhausted' */
413
- repairStop: string
414
- /** model-generated asserts used as extra oracle signal ([] when TESTGEN off) */
415
- genTests: string[]
416
- llmCalls: number
417
- llmAttempts: number
418
- tokensIn: number
419
- tokensOut: number
420
- }
421
-
422
- async function runHarnessForTask(cfg: ClientCfg, task: HumanEvalTask, k: number, maxRepairs: number, testGen: number, diverse: boolean): Promise<HarnessOutcome> {
423
- const basePrompt = `${solveInstruction}\n\n\`\`\`python\n${task.prompt}\`\`\``
424
- // DIVERSE mode: each sample slot gets a distinct strategy prefix — targets the
425
- // all-k-samples-fail bucket, where iid resampling keeps drawing the same bug.
426
- const slotPrompts = diverse ? composeStrategies(basePrompt, k) : Array.from({ length: k }, () => basePrompt)
427
- let llmCalls = 0
428
- let llmAttempts = 0
429
- let tokensIn = 0
430
- let tokensOut = 0
431
- const track = (c: Completion) => {
432
- llmCalls += 1
433
- llmAttempts += c.attempts
434
- tokensIn += c.tokensIn
435
- tokensOut += c.tokensOut
436
- }
437
-
438
- // Generated tests come from the prompt alone, BEFORE any candidate exists, and
439
- // are frozen for every sample and repair round of this task.
440
- let genTests: string[] = []
441
- if (testGen > 0) {
442
- const g = await generateTests(cfg, task, testGen)
443
- track(g.completion)
444
- genTests = g.tests
445
- }
446
-
447
- const samples: string[] = []
448
- for (let i = 0; i < k; i += 1) {
449
- const c = await complete(cfg, [{ role: 'user', content: slotPrompts[i] as string }])
450
- track(c)
451
- samples.push(extractCode(c.content))
452
- }
453
- const honest: HonestResult[] = []
454
- for (const s of samples) honest.push(await runHonestOracle(task, s, genTests))
455
-
456
- // argmax by honest score, first index wins ties (deterministic; with zero
457
- // coverage every sample ties at 0 → sample 0 = the blind pick)
458
- let selectedIdx = 0
459
- for (let i = 1; i < k; i += 1) {
460
- if (honestScore(honest[i] as HonestResult) > honestScore(honest[selectedIdx] as HonestResult)) selectedIdx = i
461
- }
462
-
463
- const selHonest = honest[selectedIdx] as HonestResult
464
- let best = { code: samples[selectedIdx] as string, honest: selHonest }
465
- const repairs: HarnessOutcome['repairs'] = []
466
- let repairStop = 'already-passing'
467
- if (!selHonest.pass) {
468
- if (selHonest.attempted === 0) {
469
- repairStop = 'no-signal' // no visible examples → nothing honest to steer on
470
- } else {
471
- repairStop = 'rounds-exhausted'
472
- let current = best
473
- for (let r = 0; r < maxRepairs; r += 1) {
474
- const repairPrompt = [
475
- 'Your Python function failed some of the example checks shown in its own docstring.',
476
- 'Here is the task again:',
477
- '```python',
478
- task.prompt.trimEnd(),
479
- '```',
480
- 'Your current attempt:',
481
- '```python',
482
- current.code,
483
- '```',
484
- 'Result of running the docstring examples against your attempt:',
485
- '```',
486
- current.honest.failureOutput.trim() || '(the code crashed before the examples could run)',
487
- '```',
488
- '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.',
489
- ].join('\n')
490
- const c = await complete(cfg, [{ role: 'user', content: repairPrompt }])
491
- track(c)
492
- const code = extractRepairCode(c.content)
493
- const h = await runHonestOracle(task, code, genTests)
494
- repairs.push({ code, honest: h })
495
- if (honestScore(h) > honestScore(current.honest)) current = { code, honest: h }
496
- if (honestScore(current.honest) > honestScore(best.honest)) best = current
497
- if (h.pass) {
498
- repairStop = 'repaired-pass'
499
- break
500
- }
501
- }
502
- }
503
- }
504
-
505
- return { taskId: task.taskId, samples, honest, selectedIdx, repairs, finalCode: best.code, repairStop, genTests, llmCalls, llmAttempts, tokensIn, tokensOut }
506
- }
507
-
508
- // ---------- statistics: exact sign test to pair with the bootstrap CI ----------
509
- // The percentile bootstrap is anticonservative when few tasks move (4 improved / 0
510
- // regressed at n=164 prints CI [+0.6, +4.9]pp while the exact test says p=0.125).
511
- // The verdict requires BOTH.
512
-
513
- function signTestP(deltas: number[]): { pos: number; neg: number; p: number } {
514
- const pos = deltas.filter((d) => d > 1e-9).length
515
- const neg = deltas.filter((d) => d < -1e-9).length
516
- const m = pos + neg
517
- if (m === 0) return { pos, neg, p: 1 }
518
- // two-sided exact binomial(m, 0.5) tail from the observed extreme
519
- const logC: number[] = [0]
520
- for (let i = 1; i <= m; i += 1) logC.push((logC[i - 1] as number) + Math.log(m - i + 1) - Math.log(i))
521
- const pmf = (x: number) => Math.exp((logC[x] as number) - m * Math.LN2)
522
- const extreme = Math.max(pos, neg)
523
- let p = 0
524
- for (let x = extreme; x <= m; x += 1) p += pmf(x)
525
- p *= 2
526
- if (pos === neg) p = 1
527
- return { pos, neg, p: Math.min(1, p) }
528
- }
529
-
530
- // ---------- calibration mode ----------
531
-
532
- async function calibrate(tasks: HumanEvalTask[]): Promise<void> {
533
- console.log(`=== CALIBRATION · canonical solutions vs both judges · n=${tasks.length} ===`)
534
- const usable = tasks.filter((t) => t.canonicalSolution)
535
- if (usable.length !== tasks.length) console.log(` WARNING: ${tasks.length - usable.length} task(s) missing canonical_solution`)
536
- const rows = await pool(usable, 16, async (t) => {
537
- const full = `${t.prompt}${t.canonicalSolution}`
538
- const hidden = await runHiddenJudge(t, full)
539
- const honest = await runHonestOracle(t, full)
540
- return { id: t.taskId, hidden: hidden.pass, attempted: honest.attempted, failed: honest.failed, honestPass: honest.pass }
541
- })
542
- const hiddenPass = rows.filter((r) => r.hidden === 1)
543
- const covered = rows.filter((r) => r.attempted > 0)
544
- const falseFail = covered.filter((r) => !r.honestPass)
545
- console.log(` hidden judge self-check: ${hiddenPass.length}/${rows.length} canonical solutions pass (must be ~100%)`)
546
- if (hiddenPass.length < rows.length) console.log(` hidden FAILS: ${rows.filter((r) => r.hidden !== 1).map((r) => r.id).join(', ')}`)
547
- console.log(` honest-oracle coverage: ${covered.length}/${rows.length} tasks have >=1 parseable docstring example`)
548
- console.log(` zero-coverage tasks: ${rows.filter((r) => r.attempted === 0).map((r) => r.id).join(', ') || '(none)'}`)
549
- console.log(` crashed-oracle tasks (attempted=-1): ${rows.filter((r) => r.attempted < 0).map((r) => r.id).join(', ') || '(none)'}`)
550
- console.log(` honest-oracle false-fail on canonical: ${falseFail.length}/${covered.length} covered tasks`)
551
- if (falseFail.length > 0) console.log(` false-fail ids: ${falseFail.map((r) => `${r.id}(${r.failed}/${r.attempted})`).join(', ')}`)
552
- const examplesTotal = covered.reduce((s, r) => s + r.attempted, 0)
553
- console.log(` examples per covered task: mean ${(examplesTotal / Math.max(1, covered.length)).toFixed(1)}`)
554
- }
555
-
556
- // ---------- main ----------
557
-
558
- const pct = (x: number) => `${(x * 100).toFixed(1)}%`
559
- const pp = (x: number) => `${x >= 0 ? '+' : ''}${(x * 100).toFixed(1)}pp`
560
-
561
- interface GradedRow extends HarnessOutcome {
562
- hiddenSamples: number[]
563
- hiddenFinal: number
564
- }
565
-
566
- async function main(): Promise<void> {
567
- const n = Number(process.env.N ?? 164)
568
- const k = Number(process.env.K ?? 5)
569
- const maxRepairs = Number(process.env.REPAIRS ?? 2)
570
- const offset = Number(process.env.OFFSET ?? 0)
571
- const temperature = Number(process.env.TEMPERATURE ?? 0.8)
572
- const model = process.env.WORKER_MODEL ?? 'meta-llama/Meta-Llama-3-8B-Instruct-Lite'
573
- const base = process.env.ROUTER_BASE ?? 'https://api.together.xyz/v1'
574
- const solveConc = Number(process.env.CONCURRENCY ?? 6)
575
- dockerSlots = Number(process.env.DOCKER_CONCURRENCY ?? 6)
576
- const testGen = Number(process.env.TESTGEN ?? 0)
577
- const diverse = process.env.DIVERSE === '1'
578
- const out = process.env.OUT
579
-
580
- const tasks = await loadHumanEval(n, offset)
581
-
582
- if (process.env.CALIBRATE === '1') {
583
- await calibrate(tasks)
584
- return
585
- }
586
-
587
- const cfg: ClientCfg = { base, key: must('TANGLE_API_KEY'), model, maxTokens: Number(process.env.MAX_TOKENS ?? 2500), temperature }
588
-
589
- console.log(`=== HumanEval STRUCTURAL lever · honest docstring oracle · n=${tasks.length} k=${k} repairs<=${maxRepairs} temp=${temperature} testgen=${testGen} diverse=${diverse ? 1 : 0} ===`)
590
- console.log(` model=${model} base=${base} llm-conc=${solveConc} docker-conc=${dockerSlots} (global semaphore)`)
591
- console.log(` Phase A (harness: sample->honest-select->honest-repair) then Phase B (hidden grading)`)
592
-
593
- // Phase A — all harness decisions locked before any hidden grading. A per-task
594
- // fault becomes an error row (persisted, excluded from stats), not a lost run;
595
- // >15% error rate aborts loud since that means the harness itself is broken.
596
- let done = 0
597
- let errCount = 0
598
- const outcomes = await pool(tasks, solveConc, async (task): Promise<HarnessOutcome | { taskId: string; error: string }> => {
599
- try {
600
- const o = await runHarnessForTask(cfg, task, k, maxRepairs, testGen, diverse)
601
- done += 1
602
- if (out) appendFileSync(`${out}.phaseA`, `${JSON.stringify({ model, temperature, k, maxRepairs, ...o })}\n`)
603
- process.stderr.write(
604
- ` [A ${done}/${tasks.length}] ${o.taskId}: sel=${o.selectedIdx} honest=${o.honest.map((h) => honestScore(h).toFixed(2)).join('/')} repairs=${o.repairs.length} stop=${o.repairStop}\n`,
605
- )
606
- return o
607
- } catch (e) {
608
- errCount += 1
609
- const error = e instanceof Error ? e.message : String(e)
610
- if (out) appendFileSync(`${out}.phaseA`, `${JSON.stringify({ model, taskId: task.taskId, error })}\n`)
611
- process.stderr.write(` [A ERROR] ${task.taskId}: ${error.slice(0, 160)}\n`)
612
- if (errCount > Math.max(3, 0.15 * tasks.length)) throw new Error(`aborting: ${errCount} task errors — harness-level fault, not task noise (last: ${error})`)
613
- return { taskId: task.taskId, error }
614
- }
615
- })
616
-
617
- const okOutcomes = outcomes.filter((o): o is HarnessOutcome => !('error' in o))
618
- const okTasks = okOutcomes.map((o) => tasks.find((t) => t.taskId === o.taskId) as HumanEvalTask)
619
- 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`)
620
-
621
- // Phase B — hidden grading of the locked artifacts.
622
- console.log(`\n▶ Phase B: hidden grading (${okOutcomes.length} tasks × ${k} samples + finals)`)
623
- const graded: GradedRow[] = await pool(okOutcomes, 16, async (o, ti) => {
624
- const task = okTasks[ti] as HumanEvalTask
625
- const hiddenSamples: number[] = []
626
- for (const s of o.samples) hiddenSamples.push((await runHiddenJudge(task, s)).pass)
627
- const finalIsSelected = o.finalCode === o.samples[o.selectedIdx]
628
- const hiddenFinal = finalIsSelected ? (hiddenSamples[o.selectedIdx] as number) : (await runHiddenJudge(task, o.finalCode)).pass
629
- const g: GradedRow = { ...o, hiddenSamples, hiddenFinal }
630
- if (out) appendFileSync(out, `${JSON.stringify({ model, temperature, k, maxRepairs, ...g })}\n`)
631
- return g
632
- })
633
- if (out) console.log(` raw rows appended to ${out} (phase-A rows incl. errors: ${out}.phaseA)`)
634
-
635
- // Estimators (all paired over the same graded tasks).
636
- const blind1First = graded.map((g) => g.hiddenSamples[0] as number)
637
- const blind1Mean = graded.map((g) => g.hiddenSamples.reduce((s, x) => s + x, 0) / g.hiddenSamples.length)
638
- const selected = graded.map((g) => g.hiddenSamples[g.selectedIdx] as number)
639
- const repaired = graded.map((g) => g.hiddenFinal)
640
- const oracleK = graded.map((g) => (g.hiddenSamples.some((x) => x === 1) ? 1 : 0))
641
- // coverage is a task-level property; any non-crashed sample's oracle run proves it
642
- const covered = graded.map((g) => (g.honest.some((h) => h.attempted > 0) ? 1 : 0))
643
- const rate = (xs: number[]) => xs.reduce((s, x) => s + x, 0) / xs.length
644
- const llmCallsTotal = graded.reduce((s, g) => s + g.llmCalls, 0)
645
- const llmAttemptsTotal = graded.reduce((s, g) => s + g.llmAttempts, 0)
646
- const tokensInTotal = graded.reduce((s, g) => s + g.tokensIn, 0)
647
- const tokensOutTotal = graded.reduce((s, g) => s + g.tokensOut, 0)
648
- const repairFired = graded.filter((g) => g.repairs.length > 0)
649
-
650
- console.log(`\n${'='.repeat(78)}`)
651
- console.log(`RESULTS · HumanEval structural lever · n=${graded.length} · k=${k} · repairs<=${maxRepairs} · temp=${temperature} · ${model}`)
652
- console.log('='.repeat(78))
653
- console.log(` honest-oracle coverage ${pct(rate(covered))} of tasks (>=1 docstring example)`)
654
- console.log(` blind pass@1 (mean of k) ${pct(rate(blind1Mean))} [PRIMARY baseline — ${k}-rep estimator]`)
655
- console.log(` blind pass@1 (first sample) ${pct(rate(blind1First))} [single-rep reference]`)
656
- console.log(` selected@1 (honest argmax) ${pct(rate(selected))}`)
657
- console.log(` repaired@1 (full harness) ${pct(rate(repaired))}`)
658
- console.log(` oracle pass@${k} (ceiling) ${pct(rate(oracleK))}`)
659
- console.log(
660
- ` compute: ${llmCallsTotal} llm calls (${llmAttemptsTotal} incl. retries) = ${(llmCallsTotal / graded.length).toFixed(2)}/task; tokens in/out ${tokensInTotal}/${tokensOutTotal} (blind@1 spends 1 call/task)`,
661
- )
662
- 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(', ')})`)
663
-
664
- const row = (label: string, baseline: number[], treatment: number[]) => {
665
- const l = pairedLift(baseline, treatment)
666
- const st = signTestP(baseline.map((b, i) => (treatment[i] as number) - b))
667
- console.log(
668
- ` ${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})`,
669
- )
670
- return { l, st }
671
- }
672
-
673
- console.log(`\n PAIRED LIFTS vs blind pass@1 (mean-of-${k}) · 95% bootstrap CI (B=10000) + exact sign test:`)
674
- const sel = row('selected@1 − blind@1 (selection)', blind1Mean, selected)
675
- const rep = row('repaired@1 − blind@1 (full harness)', blind1Mean, repaired)
676
- row('repaired@1 − selected@1 (repair)', selected, repaired)
677
- row(`oracle@${k} − repaired@1 (unrealized)`, repaired, oracleK)
678
-
679
- // Subgroup views (report-only; the primary claim is the unconditional lift):
680
- const coveredIdx = graded.map((_, i) => i).filter((i) => covered[i] === 1)
681
- if (coveredIdx.length > 0 && coveredIdx.length < graded.length) {
682
- const pick = (xs: number[]) => coveredIdx.map((i) => xs[i] as number)
683
- console.log(`\n COVERED-ONLY subgroup (n=${coveredIdx.length} tasks with visible examples; oracle can only act here):`)
684
- row(' selected@1 − blind@1', pick(blind1Mean), pick(selected))
685
- row(' repaired@1 − blind@1', pick(blind1Mean), pick(repaired))
686
- }
687
-
688
- const verdict = (name: string, r: { l: PairedLift; st: { p: number } }) =>
689
- `${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.'}`
690
- console.log(`\n VERDICT: ${verdict('full harness', rep)}; ${verdict('selection alone', sel)}`)
691
- }
692
-
693
- main().catch((e) => {
694
- reapContainers()
695
- console.error(`hev-structural: ${e instanceof Error ? (e.stack ?? e.message) : String(e)}`)
696
- process.exit(1)
697
- })