@tangle-network/agent-bench 0.14.2 → 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 (218) hide show
  1. package/CHANGELOG.md +48 -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/scripts/verify-packed-consumer.mjs +0 -1
  118. package/src/atom-mcp-e2e.mts +16 -4
  119. package/src/benchmarks/frames.ts +10 -44
  120. package/src/benchmarks/hotpotqa.ts +9 -29
  121. package/src/benchmarks/rag-shared.ts +12 -0
  122. package/src/benchmarks/simpleqa.ts +2 -36
  123. package/src/commit0-prereqs.sh +0 -0
  124. package/src/corpus-replay.mts +8 -8
  125. package/src/corpus-report.mts +21 -21
  126. package/src/corpus.test.mts +5 -5
  127. package/src/corpus.ts +16 -16
  128. package/src/directives.ts +0 -38
  129. package/src/examples/lean-verify.ts +1 -1
  130. package/src/gate.ts +8 -8
  131. package/src/generate-eval/certify.ts +2 -2
  132. package/src/index.ts +1 -0
  133. package/src/refine-loop.ts +5 -5
  134. package/src/resolve-client.ts +1 -1
  135. package/src/router-turn.ts +3 -11
  136. package/src/run-benchmarks.test.mts +0 -4
  137. package/src/run-pool.ts +1 -1
  138. package/src/runtime-hook-recorder.ts +2 -2
  139. package/src/search-bench/tasks.ts +1 -1
  140. package/src/selector.test.mts +13 -13
  141. package/src/selector.ts +19 -19
  142. package/src/swe-bench-env.ts +4 -12
  143. package/src/swe-jail.ts +5 -156
  144. package/src/swe-structural-judge-policy.ts +3 -3
  145. package/src/swe-structural-policy.ts +3 -3
  146. package/src/swe-structural-provenance.ts +4 -4
  147. package/src/terminal-compare.ts +10 -10
  148. package/src/worker-blender.ts +2 -106
  149. package/src/worker-build123d.ts +2 -81
  150. package/tb_agents/opencode_router_agent.py +1 -1
  151. package/dist/cadbench-BRF-59Mt.js.map +0 -1
  152. package/dist/cadgenbench-DXtGkuW3.js.map +0 -1
  153. package/dist/router-turn-uTYO6KQ1.js.map +0 -1
  154. package/scripts/cadbench_prepare.py +0 -22
  155. package/scripts/cadgenbench_hard_parts.py +0 -48
  156. package/scripts/clbench_codebase_judge.py +0 -73
  157. package/scripts/render-gate-chart.mjs +0 -176
  158. package/scripts/trata-hedge/README.md +0 -57
  159. package/scripts/trata-hedge/run.sh +0 -64
  160. package/src/browser/adapters/bad-design-audit.ts +0 -153
  161. package/src/browser/adapters/bad-design-audit.verify.ts +0 -85
  162. package/src/browser/adapters/bad.ts +0 -165
  163. package/src/browser/agent-adapter.ts +0 -145
  164. package/src/browser/process-adapter.ts +0 -146
  165. package/src/browser/run-to-spans.ts +0 -105
  166. package/src/browser/run-to-spans.verify.ts +0 -89
  167. package/src/browser/ui-reviewer.ts +0 -200
  168. package/src/browser/ui-reviewer.verify.ts +0 -94
  169. package/src/browser/verify.ts +0 -96
  170. package/src/clbench-codebase-gate.mts +0 -314
  171. package/src/clbench-context-gate.mts +0 -341
  172. package/src/cloud-loop.mts +0 -156
  173. package/src/commit0-env-run.mts +0 -62
  174. package/src/commit0-env.ts +0 -172
  175. package/src/commit0-gate.mts +0 -558
  176. package/src/coordination-mcp-container-reach.mts +0 -182
  177. package/src/egress-probe.mts +0 -26
  178. package/src/fleet.mts +0 -143
  179. package/src/hev-structural.mts +0 -697
  180. package/src/humaneval-gate.mts +0 -220
  181. package/src/humaneval-repair-gate.mts +0 -182
  182. package/src/mbpp-structural.mts +0 -676
  183. package/src/mcp-mount-probe.mts +0 -139
  184. package/src/profile-coordinates.ts +0 -134
  185. package/src/profiles.ts +0 -128
  186. package/src/research-gate.mts +0 -132
  187. package/src/research-shot.ts +0 -144
  188. package/src/router-executor.ts +0 -51
  189. package/src/run-benchmarks-report.ts +0 -66
  190. package/src/sandbox-run.ts +0 -108
  191. package/src/search-bench/bridge.ts +0 -182
  192. package/src/search-bench/export.mts +0 -0
  193. package/src/search-bench/parametric-check.mts +0 -78
  194. package/src/search-bench/profiles.ts +0 -113
  195. package/src/search-bench/run.mts +0 -286
  196. package/src/search-bench/tasks-fresh.ts +0 -688
  197. package/src/skill-sandbox-smoke.mts +0 -101
  198. package/src/smoke-structural-rollout.mts +0 -415
  199. package/src/stats.mts +0 -90
  200. package/src/supervisor-arena.mts +0 -825
  201. package/src/swe-code-improve.mts +0 -306
  202. package/src/swe-emit-patch.mts +0 -125
  203. package/src/swe-improve.mts +0 -284
  204. package/src/swe-local-proof.mts +0 -265
  205. package/src/swe-repro-calibrate.mts +0 -451
  206. package/src/swe-stream.mts +0 -1561
  207. package/src/swe-structural.mts +0 -707
  208. package/src/tb-container-executor.mts +0 -266
  209. package/src/tb-container-executor.test.mts +0 -134
  210. package/src/tb-supervisor-sidecar.mts +0 -208
  211. package/src/trajectory-assemble.mjs +0 -130
  212. package/src/trata-gepa.mts +0 -381
  213. package/src/trata-hedge-solve.mts +0 -81
  214. package/src/worker-browser.ts +0 -115
  215. package/src/worker-cad.ts +0 -470
  216. package/src/workspace-loop.mts +0 -133
  217. package/tb_agents/opencode_refine_agent.py +0 -117
  218. package/tb_agents/opencode_supervisor_agent.py +0 -239
@@ -1,306 +0,0 @@
1
- /**
2
- * META-HARNESS on the SWE scaffold — improve({ surface: 'code' }).
3
- *
4
- * A Pi coding agent REWRITES the scaffold LOGIC under bench/src (the seed prompt/playbook,
5
- * runAgentic strategy/params, context handling, retry/patch synthesis) with the MODEL (glm worker) +
6
- * the TOOL surface (list/read/edit[/run]) + the JUDGE held FIXED, judged on the official swebench
7
- * Docker verdict, gated on a held-out instance split. This is the DGM/meta-harness recipe: let the
8
- * SYSTEM find the scaffold lever from the RAW failure traces, not hand-build it.
9
- *
10
- * Wiring (all verified in this worktree):
11
- * - improve()/codeProposerFor + rawTraceContext come from the LOCAL agent-runtime build, linked into
12
- * this bench's node_modules (bench/node_modules/@tangle-network/agent-runtime -> /home/drew/code/agent-runtime).
13
- * - The candidate proposer supplies one exact Pi AgentProfile and runs it through Runtime's
14
- * bridge executor. No local CLI shortcut or ambient model default exists.
15
- * - Each candidate is a git worktree the driver forks off baseRef; Pi edits bench/src in place;
16
- * `verify` (an import smoke of the edited scaffold) gates it before the expensive measurement.
17
- * - MEASUREMENT: the code-aware agent fn shells into the candidate scaffold's OWN judge-free emit
18
- * entrypoint (swe-emit-patch.mts) with cwd = the worktree, captures the unified diff, and returns
19
- * it. improve()'s FIXED swebench judge scores that diff OUTSIDE the candidate, so the scaffold can
20
- * never game its own axis. Baseline (empty surface) runs the UNEDITED scaffold from the main tree.
21
- *
22
- * Run (router WAF: keep example commands OUT of backticks):
23
- * TANGLE_API_KEY=... dotenvx run --quiet -f .../agent-state.env --
24
- * TRAIN_IDS=... HOLDOUT_IDS=... WORKER_MODEL=glm-4.6 GENERATIONS=1 POPULATION=2
25
- * RUN_DIR=/abs/run BASE_REF=meta/swe-scaffold-baseline
26
- * node_modules/.bin/tsx bench/src/swe-code-improve.mts
27
- */
28
- import { spawn, spawnSync } from 'node:child_process'
29
- import { existsSync, mkdirSync, symlinkSync } from 'node:fs'
30
- import { join } from 'node:path'
31
- import { improve, agenticGenerator } from '@tangle-network/agent-runtime'
32
- import type { ProposalFinding } from '@tangle-network/agent-eval'
33
- import type { DispatchContext, JudgeConfig, Scenario } from '@tangle-network/agent-eval/contract'
34
- import { agentProfileSchema } from '@tangle-network/agent-interface'
35
- import { createSweBenchAdapter } from './benchmarks/swe-bench'
36
- import type { BenchTask } from './benchmarks/types'
37
-
38
- /** The agent-runtime repo the worktree adapter forks candidate checkouts from (agent-runtime-swe is a
39
- * worktree of it, so bench/src is tracked here). */
40
- const REPO_ROOT = process.env.REPO_ROOT ?? '/home/drew/code/agent-runtime'
41
- /** The main working tree = the baseline scaffold (its bench has the linked node_modules). */
42
- const SWE_MAIN_ROOT = process.env.SWE_MAIN_ROOT ?? '/home/drew/code/agent-runtime-swe'
43
- const MAIN_BENCH = join(SWE_MAIN_ROOT, 'bench')
44
- const TSX_BIN = join(MAIN_BENCH, 'node_modules/.bin/tsx')
45
-
46
- /** A candidate worktree is a fresh checkout with NO node_modules. Symlink the main bench's (already
47
- * carrying the linked local runtime) so both the verifier and the measurement can run the scaffold. */
48
- function ensureNodeModules(rootDir: string): void {
49
- const target = join(rootDir, 'bench', 'node_modules')
50
- if (existsSync(target)) return
51
- try {
52
- symlinkSync(join(MAIN_BENCH, 'node_modules'), target, 'dir')
53
- } catch {
54
- /* concurrent create / already exists — fine */
55
- }
56
- }
57
-
58
- /** Run the scaffold's judge-free emit entrypoint on ONE instance, from `rootDir`'s bench/src. Returns
59
- * the unified diff (stdout, kept clean of any banner) + the tokens the worker reported (parsed from
60
- * the [emit] stderr line). NO judge — the judge is held outside, in this file. */
61
- function runEmit(
62
- rootDir: string,
63
- id: string,
64
- env: Record<string, string>,
65
- timeoutMs: number,
66
- ): Promise<{ patch: string; tokIn: number; tokOut: number; usd: number; code: number | null }> {
67
- ensureNodeModules(rootDir)
68
- const benchDir = join(rootDir, 'bench')
69
- return new Promise((resolve) => {
70
- const child = spawn(TSX_BIN, [join(benchDir, 'src/swe-emit-patch.mts')], {
71
- cwd: benchDir,
72
- env: { ...process.env, ...env, IDS: id },
73
- stdio: ['ignore', 'pipe', 'pipe'],
74
- })
75
- let out = ''
76
- let err = ''
77
- child.stdout.on('data', (d) => (out += String(d)))
78
- child.stderr.on('data', (d) => (err += String(d)))
79
- const timer = setTimeout(() => {
80
- if (!child.killed) child.kill('SIGKILL')
81
- }, timeoutMs)
82
- ;(timer as { unref?: () => void }).unref?.()
83
- child.on('error', () => {
84
- clearTimeout(timer)
85
- resolve({ patch: '', tokIn: 0, tokOut: 0, usd: 0, code: 1 })
86
- })
87
- child.on('close', (code) => {
88
- clearTimeout(timer)
89
- const m = /tok=in:(\d+)\/out:(\d+)/.exec(err)
90
- const u = /usd=([0-9.]+)/.exec(err)
91
- if (code !== 0) console.error(` [emit ${id}] exit=${code} stderr: ${err.slice(-400).replace(/\n/g, ' ')}`)
92
- resolve({
93
- patch: out,
94
- tokIn: m ? Number(m[1]) : 0,
95
- tokOut: m ? Number(m[2]) : 0,
96
- usd: u ? Number(u[1]) : 0,
97
- code,
98
- })
99
- })
100
- })
101
- }
102
-
103
- async function main(): Promise<void> {
104
- const routerKey = process.env.TANGLE_API_KEY
105
- if (!routerKey) throw new Error('TANGLE_API_KEY required (worker calls the router)')
106
- const routerBaseUrl = process.env.ROUTER_BASE ?? 'https://router.tangle.tools/v1'
107
- const workerModel = process.env.WORKER_MODEL ?? 'glm-4.6'
108
- const trainIds = (process.env.TRAIN_IDS ?? 'psf__requests-2931,pallets__flask-5014').split(',').map((s) => s.trim()).filter(Boolean)
109
- const holdoutIds = (process.env.HOLDOUT_IDS ?? 'psf__requests-1142,psf__requests-1921').split(',').map((s) => s.trim()).filter(Boolean)
110
- const generations = Number(process.env.GENERATIONS ?? 1)
111
- const population = Number(process.env.POPULATION ?? 2)
112
- const innerTurns = Number(process.env.INNER_TURNS ?? 40)
113
- const maxTokens = Number(process.env.MAX_TOKENS ?? 12000)
114
- const enableRun = ['1', 'true', 'yes'].includes((process.env.RUN_TOOL ?? '').toLowerCase())
115
- const baseRef = process.env.BASE_REF ?? 'meta/swe-scaffold-baseline'
116
- const worktreeDir = process.env.WORKTREE_DIR ?? '/tmp/claude-1000/-home-drew-code-supervisor-lab/9ee6a456-a94f-474c-9888-b4afc9bc26bd/scratchpad/mh-worktrees'
117
- const runDir = process.env.RUN_DIR ?? '/tmp/claude-1000/-home-drew-code-supervisor-lab/9ee6a456-a94f-474c-9888-b4afc9bc26bd/scratchpad/mh-run'
118
- const emitTimeoutMs = Number(process.env.EMIT_TIMEOUT_MS ?? 600_000)
119
- const harnessTimeoutMs = Number(process.env.HARNESS_TIMEOUT_MS ?? 900_000)
120
- const bridgeUrl = process.env.CLI_BRIDGE_URL ?? process.env.BRIDGE_URL
121
- const bridgeBearer = process.env.CLI_BRIDGE_BEARER ?? process.env.BRIDGE_BEARER
122
- if (!bridgeUrl || !bridgeBearer) {
123
- throw new Error('CLI_BRIDGE_URL/BRIDGE_URL and CLI_BRIDGE_BEARER/BRIDGE_BEARER are required')
124
- }
125
- const authorProfile = agentProfileSchema.parse({
126
- name: 'swe-scaffold-author',
127
- harness: 'pi',
128
- model: {
129
- provider: process.env.AUTHOR_PROVIDER ?? 'tangle-router',
130
- default: process.env.AUTHOR_MODEL ?? 'glm-5.2',
131
- },
132
- prompt: {
133
- systemPrompt: 'Improve the candidate worktree from measured failure evidence and verify it.',
134
- },
135
- })
136
- mkdirSync(worktreeDir, { recursive: true })
137
- mkdirSync(runDir, { recursive: true })
138
-
139
- const allIds = [...new Set([...trainIds, ...holdoutIds])]
140
-
141
- console.log('=== META-HARNESS on the SWE scaffold — improve(surface:code) ===')
142
- console.log(`worker=${workerModel} router=${routerBaseUrl} runTool=${enableRun}`)
143
- console.log(`train=[${trainIds.join(', ')}] holdout=[${holdoutIds.join(', ')}]`)
144
- console.log(`generations=${generations} population=${population} innerTurns=${innerTurns} maxTokens=${maxTokens}`)
145
- console.log(`repoRoot=${REPO_ROOT} baseRef=${baseRef}`)
146
- console.log(`runDir=${runDir} worktreeDir=${worktreeDir}`)
147
-
148
- // Fixed swebench Docker judge (held OUTSIDE every candidate) + task pool.
149
- const adapter = createSweBenchAdapter()
150
- const pool = await adapter.loadTasks({ ids: allIds, split: 'test' })
151
- const byId = new Map<string, BenchTask>(pool.map((t) => [t.id, t]))
152
- for (const id of allIds) if (!byId.has(id)) throw new Error(`instance not found in Verified: ${id}`)
153
-
154
- const workerEnv: Record<string, string> = {
155
- WORKER_MODEL: workerModel,
156
- MAX_TOKENS: String(maxTokens),
157
- INNER_TURNS: String(innerTurns),
158
- ROUTER_BASE: routerBaseUrl,
159
- TANGLE_API_KEY: routerKey,
160
- RUN_TOOL: enableRun ? '1' : '0',
161
- }
162
-
163
- // The code-aware measurement agent. A CodeSurface -> run the candidate scaffold in its worktree; an
164
- // empty/string surface (the baseline arm) -> run the UNEDITED scaffold from the main tree. Same path,
165
- // so baseline and candidates are measured identically.
166
- const agent = async (surface: unknown, scenario: Scenario, ctx: DispatchContext): Promise<string | null> => {
167
- const isCode = !!surface && typeof surface === 'object' && (surface as { kind?: string }).kind === 'code'
168
- const worktreeRef = isCode ? String((surface as { worktreeRef?: string }).worktreeRef ?? '') : ''
169
- const rootDir = isCode && worktreeRef && existsSync(worktreeRef) ? worktreeRef : SWE_MAIN_ROOT
170
- const t0 = Date.now()
171
- const paid = await ctx.cost.runPaidCall({
172
- channel: 'agent',
173
- actor: 'swe-scaffold-worker',
174
- model: workerModel,
175
- execute: () => runEmit(rootDir, scenario.id, workerEnv, emitTimeoutMs),
176
- receipt: (result) => {
177
- const usageUnknown = result.tokIn === 0 && result.tokOut === 0
178
- return {
179
- model: workerModel,
180
- inputTokens: result.tokIn,
181
- outputTokens: result.tokOut,
182
- ...(result.usd > 0 ? { actualCostUsd: result.usd } : {}),
183
- ...(usageUnknown ? { usageUnknown: true, costUnknown: result.usd <= 0 } : {}),
184
- }
185
- },
186
- })
187
- if (!paid.succeeded) throw paid.error
188
- const r = paid.value
189
- const hasPatch = r.patch.trim().length > 0
190
- const files = hasPatch ? [...r.patch.matchAll(/^diff --git a\/(\S+)/gm)].map((m) => m[1]) : []
191
- console.log(
192
- ` [measure] ${isCode ? 'cand' : 'base'} ${scenario.id} patch=${r.patch.length}b files=[${files.join(', ') || 'none'}] ` +
193
- `tok=in:${r.tokIn}/out:${r.tokOut} ${Math.round((Date.now() - t0) / 1000)}s${isCode ? ` @ ${worktreeRef}` : ''}`,
194
- )
195
- return hasPatch ? r.patch : null
196
- }
197
-
198
- const judge: JudgeConfig<string | null, Scenario> = {
199
- name: 'swebench-docker',
200
- dimensions: [{ key: 'resolved', description: 'FAIL_TO_PASS + PASS_TO_PASS resolved by the official swebench Docker harness' }],
201
- async score({ artifact, scenario }) {
202
- const patch = String(artifact ?? '')
203
- if (!patch.trim()) {
204
- console.log(` [judge] ${scenario.id} resolved=0 (no patch)`)
205
- return { dimensions: { resolved: 0 }, composite: 0, notes: 'no patch emitted' }
206
- }
207
- const bt = byId.get(scenario.id)
208
- if (!bt) throw new Error(`judge: unknown scenario ${scenario.id}`)
209
- const s = await adapter.judge(bt, patch)
210
- console.log(` [judge] ${scenario.id} resolved=${s.resolved ? 1 : 0}`)
211
- return { dimensions: { resolved: s.resolved ? 1 : 0 }, composite: s.resolved ? 1 : 0, notes: (s.detail ?? '').slice(0, 200) }
212
- },
213
- }
214
-
215
- // Domain prompt: name the EDIT BOUNDARY (scaffold logic only) + keep the raw-trace evidence discipline
216
- // (agenticGenerator discards a raw-trace candidate that doesn't inspect a trace + write the diagnosis).
217
- const buildPrompt = (args: { findings: ReadonlyArray<ProposalFinding> }): string => {
218
- const lines: string[] = [
219
- 'You are improving a SWE-bench coding SCAFFOLD: a harness that drives a FIXED worker model to fix real GitHub bugs via list_files/read_file/edit_file tools. Your job is to rewrite the SCAFFOLD LOGIC so the SAME worker model resolves MORE instances on a held-out split.',
220
- '',
221
- 'EDIT ONLY the scaffold logic under bench/src:',
222
- ' - the seed prompt / playbook: SWE_SEED_PROMPT and SWE_SEED_PROMPT_WITH_RUN in bench/src/swe-bench-env.ts',
223
- ' - the exploration/context handling in bench/src/swe-bench-env.ts: list_files walk depth and 240-entry cap, the read_file 24000-char truncation, edit_file retry messaging, patch synthesis (git diff)',
224
- ' - the runAgentic strategy/params in bench/src/swe-emit-patch.mts: innerTurns default, budget, how the patch is captured',
225
- '',
226
- 'DO NOT change (FIXED for this search):',
227
- ' - the TOOL surface: the list_files/read_file/edit_file/run tool NAMES, JSON signatures, or the path jail. Do not add or remove a tool.',
228
- ' - the worker MODEL or MAX_TOKENS (passed via env — never hardcode a different model).',
229
- ' - the swebench Docker JUDGE.',
230
- ' - the swe-emit-patch.mts I/O contract: it still reads IDS + WORKER_MODEL + router env and prints ONLY the unified diff to stdout (diagnostics to stderr). You may change HOW the patch is produced, never this stdin/stdout contract.',
231
- '',
232
- 'Make the smallest set of edits that addresses the failure evidence below, then stop. Leave changes in the working tree; do NOT commit.',
233
- '',
234
- 'Failure evidence from the previous generation (its RAW run traces are on disk):',
235
- ]
236
- for (const f of args.findings) {
237
- lines.push(`- (${f.severity ?? 'info'}) ${f.claim ?? ''}`)
238
- if (f.recommended_action) lines.push(` -> ${f.recommended_action}`)
239
- }
240
- lines.push(
241
- '',
242
- 'Raw-trace evidence requirement (enforced — a candidate that skips this is discarded):',
243
- ' - Inspect at least one raw trace path named above (grep/cat/ls it) BEFORE editing.',
244
- ' - Write .improve/raw-trace-diagnosis.md in this worktree containing: the exact trace path(s) you inspected, the failure mechanism you found, and the scaffold-logic change you made.',
245
- ' - A candidate with ONLY that file changed (no real scaffold edit) is discarded.',
246
- )
247
- return lines.join('\n')
248
- }
249
-
250
- const verify = (worktreePath: string): { ok: boolean; feedback?: string } => {
251
- ensureNodeModules(worktreePath)
252
- const res = spawnSync(TSX_BIN, [join(worktreePath, 'bench/src/swe-emit-patch.mts')], {
253
- cwd: join(worktreePath, 'bench'),
254
- env: { ...process.env, SWE_EMIT_SMOKE: '1' },
255
- encoding: 'utf-8',
256
- timeout: 180_000,
257
- })
258
- if (res.status === 0) return { ok: true }
259
- const out = `${res.stdout ?? ''}${res.stderr ?? ''}`.trim()
260
- return { ok: false, feedback: `edited scaffold failed import smoke (tsx swe-emit-patch SWE_EMIT_SMOKE=1):\n${out.slice(0, 3000)}` }
261
- }
262
-
263
- const generator = agenticGenerator({
264
- profile: authorProfile,
265
- executorForWorktree: (cwd) => ({
266
- backend: 'bridge',
267
- bridgeUrl,
268
- bridgeBearer,
269
- cwd,
270
- }),
271
- verify,
272
- timeoutMs: harnessTimeoutMs,
273
- buildPrompt,
274
- })
275
-
276
- const scenarios: Scenario[] = allIds.map((id) => ({ id, kind: 'swe-bench-verified' }))
277
- const holdoutScenarios: Scenario[] = holdoutIds.map((id) => ({ id, kind: 'swe-bench-verified' }))
278
-
279
- const out = await improve({
280
- surface: 'code',
281
- gate: 'holdout',
282
- code: { repoRoot: REPO_ROOT, baseRef, worktreeDir, profile: authorProfile, generator },
283
- rawTraceContext: true,
284
- runDir,
285
- scenarios,
286
- judge,
287
- agent,
288
- expectUsage: 'warn',
289
- budget: { generations, populationSize: population, holdoutScenarios, maxConcurrency: 1, reps: 1 },
290
- })
291
-
292
- console.log('\n=== RESULT ===')
293
- console.log(`decision=${out.decision} lift=${out.lift}`)
294
- console.log(`baseline holdout composite = ${out.raw.baseline.compositeMean}`)
295
- console.log(`winner holdout composite = ${out.raw.winner.compositeMean}`)
296
- console.log(`baseline per-scenario: ${JSON.stringify(out.raw.baseline.perScenario)}`)
297
- console.log(`winner per-scenario: ${JSON.stringify(out.raw.winner.perScenario)}`)
298
- if (out.raw.winner.label) console.log(`winner label: ${out.raw.winner.label}`)
299
- if (out.raw.winner.rationale) console.log(`winner rationale: ${out.raw.winner.rationale}`)
300
- console.log(`generations explored: ${out.generationsExplored ?? 0}`)
301
- }
302
-
303
- main().catch((e) => {
304
- console.error(e instanceof Error ? (e.stack ?? e.message) : String(e))
305
- process.exit(1)
306
- })
@@ -1,125 +0,0 @@
1
- /**
2
- * Judge-FREE patch emitter for the SWE scaffold — the FIXED measurement entrypoint.
3
- *
4
- * Given ONE instance id (IDS) + worker model + router env, this runs the candidate scaffold's OWN
5
- * `createSweBenchEnvironment` + `runAgentic` IN THIS worktree and prints the unified `git diff` of
6
- * the agent's edits to STDOUT. It does NOT judge — the swebench Docker judge is held OUTSIDE the
7
- * candidate (in swe-code-improve.mts) so the scaffold can never grade its own axis.
8
- *
9
- * This is the seam the code-aware improve() agent shells into. Its I/O contract is FIXED and the
10
- * scaffold proposer must NOT change it:
11
- * IN (env): IDS=<one instance id>, WORKER_MODEL, MAX_TOKENS, ROUTER_BASE, TANGLE_API_KEY,
12
- * INNER_TURNS, BUDGET, RUN_TOOL
13
- * OUT (fd1): the unified diff (empty string when the agent made no edit)
14
- * diagnostics go to STDERR only, so stdout stays a clean patch.
15
- *
16
- * SWE_EMIT_SMOKE=1 → import/wiring check only: the module (and swe-bench-env) loaded, print READY on
17
- * stderr and exit 0 WITHOUT a clone / model call / dataset read. This is what the candidate verifier
18
- * runs to discard a scaffold edit that no longer imports.
19
- *
20
- * Command examples in prompts are kept OUT of backticks on purpose (router WAF 403s backtick-wrapped
21
- * command text) — see swe-bench-env.ts.
22
- */
23
- import { execFile } from 'node:child_process'
24
- import { promisify } from 'node:util'
25
- import type { AgenticSurface, ArtifactHandle, SurfaceScore } from '@tangle-network/agent-runtime/kernel'
26
- import { defaultAnalystInstruction, refine, runAgentic } from '@tangle-network/agent-runtime/kernel'
27
- import { createSweBenchEnvironment, SWE_SEED_PROMPT, SWE_SEED_PROMPT_WITH_RUN } from './swe-bench-env'
28
- import { benchRouterProfile, withBenchProfile } from './router-turn'
29
-
30
- const exec = promisify(execFile)
31
-
32
- async function main(): Promise<void> {
33
- const smoke = ['1', 'true', 'yes'].includes((process.env.SWE_EMIT_SMOKE ?? '').toLowerCase())
34
- if (smoke) {
35
- // The import graph (this file + swe-bench-env + the linked runtime) resolved by the time we get
36
- // here. That is the whole check — no clone, no model call, no dataset read.
37
- console.error('SWE_EMIT_SMOKE ok: swe-emit-patch + swe-bench-env import graph loaded')
38
- return
39
- }
40
-
41
- const routerKey = process.env.TANGLE_API_KEY
42
- if (!routerKey) throw new Error('TANGLE_API_KEY required (the worker calls the router)')
43
- const routerBaseUrl = process.env.ROUTER_BASE ?? 'https://router.tangle.tools/v1'
44
- const model = process.env.WORKER_MODEL ?? 'glm-5.2'
45
- const ids = (process.env.IDS ?? '').split(',').map((s) => s.trim()).filter(Boolean)
46
- if (ids.length !== 1) throw new Error(`swe-emit-patch: exactly one IDS required, got [${ids.join(', ')}]`)
47
- const id = ids[0]!
48
- const innerTurns = Number(process.env.INNER_TURNS ?? 40)
49
- const maxTokens = Number(process.env.MAX_TOKENS ?? 12000)
50
- const budget = Number(process.env.BUDGET ?? 1)
51
- const enableRun = ['1', 'true', 'yes'].includes((process.env.RUN_TOOL ?? '').toLowerCase())
52
-
53
- const { environment, adapter } = await createSweBenchEnvironment(1, { ids, enableRun })
54
- const pool = await adapter.loadTasks({ ids, split: 'test' })
55
- const bt = pool.find((t) => t.id === id)
56
- if (!bt) throw new Error(`swe-emit-patch: instance not found in Verified: ${id}`)
57
-
58
- const task = {
59
- id: bt.id,
60
- userPrompt: bt.prompt,
61
- meta: { instanceId: bt.id },
62
- }
63
- const workerProfile = withBenchProfile(
64
- {
65
- name: 'swe-emit-patch-worker',
66
- harness: 'cli-base',
67
- model: { provider: 'tangle-router', default: model },
68
- tools: {
69
- list_files: true,
70
- read_file: true,
71
- edit_file: true,
72
- ...(enableRun ? { run: true } : {}),
73
- },
74
- },
75
- {
76
- systemPrompt: enableRun ? SWE_SEED_PROMPT_WITH_RUN : SWE_SEED_PROMPT,
77
- maxTokens,
78
- maxTurns: innerTurns,
79
- },
80
- )
81
- const analystProfile = benchRouterProfile('swe-emit-patch-analyst', model, {
82
- systemPrompt: defaultAnalystInstruction,
83
- maxTokens,
84
- })
85
-
86
- // Capture the patch from inside score() (called during the refine loop, BEFORE the surface closes
87
- // and rms the checkout). Keep the LATEST non-empty diff so accumulated refinements win and a later
88
- // empty read never clobbers a real patch.
89
- let capturedPatch = ''
90
- const proxy: AgenticSurface = {
91
- ...environment,
92
- async score(_t, handle: ArtifactHandle): Promise<SurfaceScore> {
93
- try {
94
- const d = await exec('git', ['-C', handle.id, 'diff'], { maxBuffer: 40_000_000, timeout: 60_000 })
95
- if (d.stdout.trim()) capturedPatch = d.stdout
96
- } catch {
97
- /* workspace gone or git error → keep whatever we already captured */
98
- }
99
- return { passes: capturedPatch.trim() ? 1 : 0, total: 1, errored: 0 }
100
- },
101
- }
102
-
103
- const t0 = Date.now()
104
- const r = await runAgentic({
105
- surface: proxy,
106
- task,
107
- strategy: refine,
108
- routerBaseUrl,
109
- routerKey,
110
- workerProfile,
111
- analystProfile,
112
- budget,
113
- })
114
- const files = capturedPatch ? [...capturedPatch.matchAll(/^diff --git a\/(\S+)/gm)].map((m) => m[1]) : []
115
- console.error(
116
- `[emit] ${id} shots=${r.shots} completions=${r.completions} tok=in:${r.tokens.input}/out:${r.tokens.output} ` +
117
- `patch=${capturedPatch.length}b files=[${files.join(', ') || 'none'}] ${Math.round((Date.now() - t0) / 1000)}s`,
118
- )
119
- process.stdout.write(capturedPatch)
120
- }
121
-
122
- main().catch((e) => {
123
- console.error(e instanceof Error ? (e.stack ?? e.message) : String(e))
124
- process.exit(1)
125
- })