@tangle-network/agent-bench 0.3.6 → 0.3.7

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 (91) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/dist/adapters.js +2 -2
  3. package/dist/benchmarks/humaneval.d.ts +10 -1
  4. package/dist/benchmarks/humaneval.js +5 -3
  5. package/dist/{chunk-PPYSEKFM.js → chunk-5H5XV76F.js} +73 -15
  6. package/dist/chunk-5H5XV76F.js.map +1 -0
  7. package/dist/{chunk-5SBJCB6W.js → chunk-PWQVGAJB.js} +2 -2
  8. package/dist/index.js +2 -2
  9. package/package.json +5 -4
  10. package/scripts/run-package-tests.mjs +30 -8
  11. package/scripts/verify-pier-agent.mts +1 -0
  12. package/src/benchmarks/humaneval.test.mts +122 -0
  13. package/src/benchmarks/humaneval.ts +100 -27
  14. package/src/david-attribution.mts +78 -0
  15. package/src/david-goliath.mts +149 -0
  16. package/src/hev-improve.mts +25 -6
  17. package/src/humaneval-object-ablation.mts +201 -0
  18. package/src/live-improve-campaign-mbpp.mts +641 -0
  19. package/src/live-improve-campaign.mts +500 -0
  20. package/src/mbpp-structural.mts +12 -7
  21. package/src/stream-observe.py +45 -0
  22. package/src/stream-observe.tpl.html +247 -0
  23. package/src/supervisor-arena.mts +816 -0
  24. package/src/swe-arena/analyze.ts +211 -0
  25. package/src/swe-arena/arms.ts +788 -0
  26. package/src/swe-arena/bootstrap-meta.mts +188 -0
  27. package/src/swe-arena/bootstrap-meta.test.mts +51 -0
  28. package/src/swe-arena/calibrate.ts +116 -0
  29. package/src/swe-arena/capabilities.mts +76 -0
  30. package/src/swe-arena/capabilities.test.mts +57 -0
  31. package/src/swe-arena/capacity.ts +194 -0
  32. package/src/swe-arena/cell-evidence.mts +405 -0
  33. package/src/swe-arena/cell-evidence.test.mts +248 -0
  34. package/src/swe-arena/diagnosis-ensemble.test.mts +210 -0
  35. package/src/swe-arena/diagnosis-ensemble.ts +520 -0
  36. package/src/swe-arena/execution.test.mts +1170 -0
  37. package/src/swe-arena/fixtures/analyze.py +80 -0
  38. package/src/swe-arena/fixtures/excludes.txt +8 -0
  39. package/src/swe-arena/fixtures/gen1-salvage/README.md +45 -0
  40. package/src/swe-arena/fixtures/gen1-salvage/cand0-e6d7361.diff +116 -0
  41. package/src/swe-arena/fixtures/gen1-salvage/cand1-76a8590.diff +293 -0
  42. package/src/swe-arena/fixtures/holdout-preregister.log +12 -0
  43. package/src/swe-arena/fixtures/holdout.json +44 -0
  44. package/src/swe-arena/fixtures/instances.json +146 -0
  45. package/src/swe-arena/fixtures/ledger.jsonl +12 -0
  46. package/src/swe-arena/fixtures/patches/pallets__flask-5014.solo.patch +36 -0
  47. package/src/swe-arena/fixtures/patches/pydata__xarray-4687.sup.patch +33 -0
  48. package/src/swe-arena/fixtures/rejudge.jsonl +15 -0
  49. package/src/swe-arena/fixtures/rematch.jsonl +3 -0
  50. package/src/swe-arena/fixtures/rematch2.jsonl +3 -0
  51. package/src/swe-arena/fixtures/rematch3.jsonl +3 -0
  52. package/src/swe-arena/fixtures/sup-journal-true.json +19 -0
  53. package/src/swe-arena/fixtures/verify/astropy__astropy-13033.sh +48 -0
  54. package/src/swe-arena/fixtures/verify/django__django-11532.sh +50 -0
  55. package/src/swe-arena/fixtures/verify/matplotlib__matplotlib-20826.sh +76 -0
  56. package/src/swe-arena/fixtures/verify/pydata__xarray-4687.sh +44 -0
  57. package/src/swe-arena/fixtures/verify/pytest-dev__pytest-6197.sh +32 -0
  58. package/src/swe-arena/fixtures/verify/sphinx-doc__sphinx-9658.sh +51 -0
  59. package/src/swe-arena/fixtures/worker-tokens.json +42 -0
  60. package/src/swe-arena/fixtures.ts +104 -0
  61. package/src/swe-arena/holdout-certify.mts +408 -0
  62. package/src/swe-arena/holdout-certify.test.mts +160 -0
  63. package/src/swe-arena/judge-child.mts +37 -0
  64. package/src/swe-arena/manifest.mts +293 -0
  65. package/src/swe-arena/manifest.test.mts +169 -0
  66. package/src/swe-arena/materialize.ts +142 -0
  67. package/src/swe-arena/outer-loop.mts +2145 -0
  68. package/src/swe-arena/outer-loop.test.mts +696 -0
  69. package/src/swe-arena/parity.test.mts +87 -0
  70. package/src/swe-arena/proc.test.mts +174 -0
  71. package/src/swe-arena/proc.ts +260 -0
  72. package/src/swe-arena/profiles/default-author.profile.json +4 -0
  73. package/src/swe-arena/proposer-fanout.mts +489 -0
  74. package/src/swe-arena/proposer-fanout.test.mts +372 -0
  75. package/src/swe-arena/reconcile.ts +0 -0
  76. package/src/swe-arena/replay.mts +183 -0
  77. package/src/swe-arena/replay.test.mts +300 -0
  78. package/src/swe-arena/run-experiment.mts +361 -0
  79. package/src/swe-arena/run-supervisor.mjs +297 -0
  80. package/src/swe-arena/run-supervisor.test.mts +498 -0
  81. package/src/swe-arena/serialized-judge.ts +414 -0
  82. package/src/swe-arena/types.ts +166 -0
  83. package/src/swe-code-improve.mts +328 -0
  84. package/src/swe-emit-patch.mts +104 -0
  85. package/src/swe-improve.mts +232 -0
  86. package/src/swe-jail.ts +2 -2
  87. package/src/swe-local-proof.mts +169 -0
  88. package/src/swe-repro-calibrate.mts +446 -0
  89. package/src/swe-stream.mts +1497 -0
  90. package/dist/chunk-PPYSEKFM.js.map +0 -1
  91. /package/dist/{chunk-5SBJCB6W.js.map → chunk-PWQVGAJB.js.map} +0 -0
@@ -0,0 +1,201 @@
1
+ /**
2
+ * OBJECT-OF-IMPROVEMENT ablation on HumanEval — the head-on test of the claim our
3
+ * whole self-improvement line rests on: at EQUAL budget, does adding CAPABILITY
4
+ * (a real code-execution tool) beat adding IMPROVER-cleverness (blind prompt
5
+ * self-refinement)? Both arms get the same model, the same K rounds per task, the
6
+ * same held-out tasks. The ONLY difference is what the budget buys:
7
+ *
8
+ * IMPROVER arm — K rounds of "critique your own function and rewrite it",
9
+ * with NO execution. The classic reflect-without-a-tool loop.
10
+ * CAPABILITY arm — K rounds WITH a `run_python` tool: the agent executes its
11
+ * function on inputs it chooses, sees real output/errors, fixes.
12
+ *
13
+ * Grading is a DETERMINISTIC hidden test (never shown): the task's own `check`.
14
+ * If the capability arm wins the held-out pass rate, the object of improvement
15
+ * (what you can DO) dominates the improver (how cleverly you rewrite) — the
16
+ * finding the prompt-only self-improvement runs kept nulling on.
17
+ *
18
+ * Fast by construction: HumanEval tasks are tiny, graded in an isolated Python
19
+ * container with a hard timeout — seconds per task. Paired
20
+ * McNemar over the per-task pass/fail difference gives the significance.
21
+ *
22
+ * Run from cwd=bench: env WORKER_MODEL=google/gemini-2.5-flash-lite N=60 K=3 \
23
+ * REPS=2 node_modules/.bin/tsx src/humaneval-object-ablation.mts
24
+ */
25
+ import {
26
+ loadHumanEval,
27
+ extractCode,
28
+ runPythonProgram,
29
+ type HumanEvalTask,
30
+ } from './benchmarks/humaneval'
31
+
32
+ const ROUTER = process.env.ROUTER_BASE ?? 'https://router.tangle.tools/v1'
33
+ const KEY = process.env.TANGLE_API_KEY
34
+ if (!KEY) throw new Error('TANGLE_API_KEY required')
35
+ const MODEL = process.env.WORKER_MODEL ?? 'google/gemini-2.5-flash-lite'
36
+ const N = Number(process.env.N ?? 60)
37
+ const OFFSET = Number(process.env.OFFSET ?? 0)
38
+ const K = Number(process.env.K ?? 3) // rounds/budget per task (equal for both arms)
39
+ const REPS = Number(process.env.REPS ?? 2)
40
+ const CONC = Number(process.env.CONCURRENCY ?? 6)
41
+ const EXEC_TIMEOUT = Number(process.env.EXEC_TIMEOUT_MS ?? 8000)
42
+
43
+ interface ChatMsg { role: string; content: string; tool_calls?: unknown; tool_call_id?: string; name?: string }
44
+ interface Tool { type: 'function'; function: { name: string; description: string; parameters: unknown } }
45
+
46
+ async function router(messages: ChatMsg[], tools?: Tool[]): Promise<{ content: string; toolCalls: { id: string; name: string; args: Record<string, unknown> }[] }> {
47
+ const body: Record<string, unknown> = { model: MODEL, messages, temperature: 0.4 }
48
+ if (tools) { body.tools = tools; body.tool_choice = 'auto' }
49
+ for (let attempt = 0; ; attempt++) {
50
+ let res: Response
51
+ try {
52
+ res = await fetch(`${ROUTER}/chat/completions`, { method: 'POST', headers: { 'content-type': 'application/json', authorization: `Bearer ${KEY}` }, body: JSON.stringify(body), signal: AbortSignal.timeout(60_000) })
53
+ } catch (e) { if (attempt >= 5) throw e; await sleep(800 * 2 ** attempt); continue }
54
+ if ([408, 429, 500, 502, 503, 504, 520, 522, 524].includes(res.status)) { if (attempt >= 5) throw new Error(`router ${res.status} exhausted`); await sleep(800 * 2 ** attempt); continue }
55
+ if (!res.ok) throw new Error(`router ${res.status}: ${(await res.text()).slice(0, 200)}`)
56
+ const j = (await res.json()) as { choices?: { message?: { content?: string; tool_calls?: { id: string; function: { name: string; arguments: string } }[] } }[] }
57
+ const m = j.choices?.[0]?.message
58
+ const toolCalls = (m?.tool_calls ?? []).map((t) => { let args: Record<string, unknown> = {}; try { args = JSON.parse(t.function.arguments) } catch { /* keep {} */ } return { id: t.id, name: t.function.name, args } })
59
+ return { content: m?.content ?? '', toolCalls }
60
+ }
61
+ }
62
+ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))
63
+ /** Run model-written Python in the shared networkless, resource-capped container. */
64
+ async function runPython(program: string): Promise<{ stdout: string; stderr: string; ok: boolean }> {
65
+ const result = await runPythonProgram(program, EXEC_TIMEOUT)
66
+ return {
67
+ stdout: result.stdout.slice(0, 2000),
68
+ stderr: result.stderr.slice(0, 2000),
69
+ ok: result.exitCode === 0,
70
+ }
71
+ }
72
+
73
+ /** The HIDDEN judge: candidate full function + the task's own check. Never shown. */
74
+ async function judge(task: HumanEvalTask, candidate: string): Promise<boolean> {
75
+ if (!candidate.trim()) return false
76
+ const program = `${candidate}\n\n${task.test}\n\ncheck(${task.entryPoint})\nprint("PASS")\n`
77
+ const r = await runPython(program)
78
+ return r.ok && r.stdout.includes('PASS')
79
+ }
80
+
81
+ const SYSTEM = 'You are an expert Python programmer. Output the COMPLETE function definition (signature + body, plus any imports) in a single ```python block. No tests, no prose outside the block.'
82
+ const userPrompt = (t: HumanEvalTask) => `Complete this function:\n\n\`\`\`python\n${t.prompt}\`\`\``
83
+
84
+ /** IMPROVER arm: K rounds of blind self-refinement — no execution, just "review and rewrite". */
85
+ async function improverArm(task: HumanEvalTask): Promise<string> {
86
+ const messages: ChatMsg[] = [{ role: 'system', content: SYSTEM }, { role: 'user', content: userPrompt(task) }]
87
+ let code = ''
88
+ for (let round = 0; round < K; round++) {
89
+ const { content } = await router(messages)
90
+ code = extractCode(content) || content
91
+ if (round < K - 1) {
92
+ messages.push({ role: 'assistant', content })
93
+ messages.push({ role: 'user', content: 'Carefully review your function for correctness bugs and edge cases. If it can be improved, output the corrected COMPLETE function in a python block; if it is already correct, output it again unchanged.' })
94
+ }
95
+ }
96
+ return code
97
+ }
98
+
99
+ const RUN_TOOL: Tool = { type: 'function', function: { name: 'run_python', description: 'Execute a Python snippet and return its stdout/stderr. Use it to test your function on example inputs from the docstring before finalizing.', parameters: { type: 'object', properties: { code: { type: 'string', description: 'python source to run' } }, required: ['code'] } } }
100
+
101
+ /** CAPABILITY arm: K rounds WITH a real code-execution tool — write, run, see real output, fix. */
102
+ async function capabilityArm(task: HumanEvalTask): Promise<string> {
103
+ const messages: ChatMsg[] = [
104
+ { role: 'system', content: `${SYSTEM}\nYou have a run_python tool: test your function on the docstring's example inputs before giving your final answer. Fix any failures you observe.` },
105
+ { role: 'user', content: userPrompt(task) },
106
+ ]
107
+ let code = ''
108
+ // (K-1) tool-exploration rounds + 1 forced final answer = K calls total, matching
109
+ // the improver arm's K blind-refine rounds (equal budget).
110
+ for (let round = 0; round < Math.max(1, K - 1); round++) {
111
+ const { content, toolCalls } = await router(messages, [RUN_TOOL])
112
+ if (content && extractCode(content)) code = extractCode(content)
113
+ messages.push({ role: 'assistant', content: content || '', ...(toolCalls.length ? { tool_calls: toolCalls.map((t) => ({ id: t.id, type: 'function', function: { name: t.name, arguments: JSON.stringify(t.args) } })) } : {}) })
114
+ if (toolCalls.length) {
115
+ for (const tc of toolCalls) {
116
+ const snippet = String(tc.args.code ?? '')
117
+ const r = await runPython(snippet)
118
+ messages.push({ role: 'tool', tool_call_id: tc.id, name: tc.name, content: `stdout:\n${r.stdout}\nstderr:\n${r.stderr}\nexit_ok=${r.ok}` })
119
+ }
120
+ } else {
121
+ messages.push({ role: 'user', content: 'Test your function with run_python on the docstring examples before finalizing.' })
122
+ }
123
+ }
124
+ // FAIR FINAL ANSWER: the tool rounds are exploration; force one no-tool call to
125
+ // emit the complete function. Without this, an agent that ends mid-tool-call
126
+ // yields empty code and is unfairly scored 0 (an extraction artifact, not a
127
+ // real "the tool hurt" signal). Only override if it produces a real block.
128
+ {
129
+ messages.push({ role: 'user', content: 'Now output your FINAL complete function in a single ```python block, no tools, no prose.' })
130
+ const { content } = await router(messages)
131
+ const finalCode = extractCode(content)
132
+ if (finalCode.trim()) code = finalCode
133
+ }
134
+ return code
135
+ }
136
+
137
+ async function pool<T, R>(items: T[], limit: number, fn: (t: T, i: number) => Promise<R>): Promise<R[]> {
138
+ const out = new Array<R>(items.length)
139
+ let next = 0
140
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
141
+ while (next < items.length) { const i = next++; out[i] = await fn(items[i]!, i) }
142
+ }))
143
+ return out
144
+ }
145
+
146
+ // McNemar exact (paired): b = capability-only wins, c = improver-only wins.
147
+ function mcnemarP(b: number, c: number): number {
148
+ const n = b + c; if (n === 0) return 1
149
+ const k = Math.min(b, c)
150
+ const lf = (x: number) => { let s = 0; for (let i = 2; i <= x; i++) s += Math.log(i); return s }
151
+ let tail = 0; for (let i = 0; i <= k; i++) tail += Math.exp(lf(n) - lf(i) - lf(n - i) - n * Math.log(2))
152
+ return Math.min(1, 2 * tail)
153
+ }
154
+
155
+ async function main(): Promise<void> {
156
+ if (['1', 'true'].includes((process.env.SMOKE ?? '').toLowerCase())) { console.error('SMOKE ok: humaneval-object-ablation loaded'); return }
157
+ const tasks = await loadHumanEval(N, OFFSET)
158
+ console.error(`=== OBJECT-OF-IMPROVEMENT ablation · HumanEval n=${tasks.length} (offset ${OFFSET}) · model=${MODEL} · K=${K} rounds · reps=${REPS} · equal budget ===`)
159
+ // self-check the local grader on the gold solution of task 0 (never shown to the model)
160
+ if (tasks[0]?.canonicalSolution) {
161
+ const gold = `${tasks[0].prompt}${tasks[0].canonicalSolution}`
162
+ console.error(` grader self-check (gold passes): ${await judge(tasks[0], gold)}`)
163
+ }
164
+
165
+ // per (task, rep): run both arms; record pass/fail.
166
+ const units = tasks.flatMap((task) => Array.from({ length: REPS }, (_, rep) => ({ task, rep })))
167
+ let done = 0
168
+ let capEmpty = 0
169
+ const results = await pool(units, CONC, async ({ task }) => {
170
+ // Per-unit resilience: a transient model failure (e.g. a weak model emitting a
171
+ // malformed tool call → router 400) scores that arm 0 for this unit, never
172
+ // crashes the whole run. Both arms wrapped identically so neither is favored.
173
+ const safe = async (fn: () => Promise<string>) => { try { return await fn() } catch { return '' } }
174
+ const [impCode, capCode] = await Promise.all([safe(() => improverArm(task)), safe(() => capabilityArm(task))])
175
+ const [imp, cap] = await Promise.all([judge(task, impCode), judge(task, capCode)])
176
+ done++
177
+ // AUTOPSY: a capability-arm failure with EMPTY final code is an extraction
178
+ // artifact (ended mid-tool-call, never emitted a final function), NOT a real
179
+ // "the tool hurt" signal. Count it so the effect can be separated.
180
+ if (!cap && !capCode.trim()) { capEmpty++; if (imp) console.error(` [cap-empty] ${task.taskId} (improver passed)`) }
181
+ if (done % 20 === 0) console.error(` ${done}/${units.length} units`)
182
+ return { id: task.taskId, imp, cap }
183
+ })
184
+ console.error(` capability-arm empty-final-code (artifact) count: ${capEmpty}/${results.length}`)
185
+
186
+ const impPass = results.filter((r) => r.imp).length
187
+ const capPass = results.filter((r) => r.cap).length
188
+ const b = results.filter((r) => r.cap && !r.imp).length // capability-only wins
189
+ const c = results.filter((r) => !r.cap && r.imp).length // improver-only wins
190
+ const p = mcnemarP(b, c)
191
+ const n = results.length
192
+ const liftPp = ((capPass - impPass) / n) * 100
193
+
194
+ console.log('')
195
+ console.log('=== RESULT (held-out HumanEval, equal budget) ===')
196
+ console.log(` IMPROVER (blind self-refine, no tool): ${impPass}/${n} = ${((impPass / n) * 100).toFixed(1)}%`)
197
+ console.log(` CAPABILITY (self-built execution tool) : ${capPass}/${n} = ${((capPass / n) * 100).toFixed(1)}%`)
198
+ console.log(` lift = ${liftPp >= 0 ? '+' : ''}${liftPp.toFixed(1)}pp paired McNemar: capability-only=${b} improver-only=${c} p=${p.toFixed(4)}`)
199
+ console.log(` verdict: ${p < 0.05 && capPass > impPass ? 'CAPABILITY > IMPROVER (significant)' : p < 0.05 && impPass > capPass ? 'IMPROVER > CAPABILITY (significant)' : 'no significant difference'}`)
200
+ }
201
+ main().catch((e) => { console.error('MAIN:', e instanceof Error ? (e.stack ?? e.message) : e); process.exit(1) })