@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,284 +0,0 @@
1
- /**
2
- * Official GEPA prompt optimization on the local SWE-bench path.
3
- *
4
- * Composes three pieces:
5
- * 1. `improve({ method: officialGepa(...) })` runs GEPA's upstream
6
- * Optimize Anything engine on explicit train and selection partitions.
7
- * 2. Per candidate + scenario, the `agent` fn runs the LOCAL SWE env
8
- * (`createSweBenchEnvironment` + `runAgentic`): clone the instance repo to a
9
- * host tmpdir, run the jailed list/read/edit tool loop with the CANDIDATE
10
- * prompt as the system prompt, and return the `git diff` as the artifact.
11
- * 3. The `judge` scores that patch with the OFFICIAL swebench Docker harness
12
- * (`adapter.judge` → resolved 0/1). The only remote call is the model
13
- * completion via the router; nothing touches sandbox.tangle.tools.
14
- *
15
- * IN-LOOP score is a cheap patch-exists proxy (NOT the Docker judge) so the ONLY
16
- * Docker run per cell is the improve judge — one deterministic verdict per cell.
17
- *
18
- * TANGLE_API_KEY=... dotenvx run -f .../agent-state.env -- \
19
- * TRAIN_IDS=psf__requests-2931 SELECTION_IDS=pallets__flask-5014 \
20
- * TEST_IDS=psf__requests-1142,psf__requests-1921 \
21
- * MAX_EVALUATIONS=4 MAX_PROPOSER_COST_USD=2 \
22
- * node_modules/.bin/tsx bench/src/swe-improve.mts
23
- */
24
- import { execFile } from 'node:child_process'
25
- import { promisify } from 'node:util'
26
- import {
27
- improve,
28
- officialGepa,
29
- type ReadonlyAgentProfile,
30
- } from '@tangle-network/agent-runtime'
31
- import {
32
- canonicalCandidateDigest,
33
- agentProfileSchema,
34
- type AgentProfile,
35
- } from '@tangle-network/agent-interface'
36
- import type { AgenticSurface, ArtifactHandle, SurfaceScore } from '@tangle-network/agent-runtime/kernel'
37
- import { defaultAnalystInstruction, refine, runAgentic } from '@tangle-network/agent-runtime/kernel'
38
- import type { DispatchContext, JudgeConfig, Scenario } from '@tangle-network/agent-eval/contract'
39
- import { createSweBenchAdapter } from './benchmarks/swe-bench'
40
- import type { BenchTask } from './benchmarks/types'
41
- import {
42
- assertCompleteCost,
43
- officialOptimizerModel,
44
- requiredTokenPricing,
45
- } from './official-optimizer-config.mjs'
46
- import { createSweBenchEnvironment, SWE_SEED_PROMPT, SWE_SEED_PROMPT_WITH_RUN } from './swe-bench-env'
47
- import { benchRouterProfile, withBenchProfile } from './router-turn'
48
-
49
- const exec = promisify(execFile)
50
-
51
- async function main(): Promise<void> {
52
- const routerKey = process.env.TANGLE_API_KEY
53
- if (!routerKey) throw new Error('TANGLE_API_KEY required (the worker + reflection call the router)')
54
- const routerBaseUrl = process.env.ROUTER_BASE ?? 'https://router.tangle.tools/v1'
55
- const workerModel = process.env.WORKER_MODEL ?? 'glm-4.6'
56
- const reflectBase = process.env.REFLECT_BASE ?? routerBaseUrl
57
- const reflectKey = process.env.REFLECT_KEY ?? routerKey
58
- const reflectModel = process.env.REFLECT_MODEL ?? 'glm-4.6'
59
- const trainIds = (process.env.TRAIN_IDS ?? 'psf__requests-2931').split(',').map((s) => s.trim()).filter(Boolean)
60
- const selectionIds = (process.env.SELECTION_IDS ?? 'pallets__flask-5014').split(',').map((s) => s.trim()).filter(Boolean)
61
- const testIds = (process.env.TEST_IDS ?? 'psf__requests-1142,psf__requests-1921').split(',').map((s) => s.trim()).filter(Boolean)
62
- const maxEvaluations = Number(process.env.MAX_EVALUATIONS ?? 4)
63
- const maxProposerCostUsd = Number(process.env.MAX_PROPOSER_COST_USD ?? 2)
64
- const innerTurns = Number(process.env.INNER_TURNS ?? 40)
65
- const workerMaxTokens = Number(process.env.MAX_TOKENS ?? 8000)
66
- const reflectMaxTokens = Number(process.env.REFLECT_MAX_TOKENS ?? 12000)
67
- const maxConcurrency = Number(process.env.MAX_CONCURRENCY ?? 1)
68
- const budgetShots = Number(process.env.BUDGET ?? 1)
69
- const runDir = process.env.RUN_DIR ?? '.runs/swe-official-gepa'
70
- // WITH-TOOLS arm: RUN_TOOL=1 exposes the jailed `run` tool AND swaps the seed to the run-aware prompt.
71
- // Default OFF ⇒ reproduces the read/edit-only baseline denominator unchanged.
72
- const enableRun = ['1', 'true', 'yes'].includes((process.env.RUN_TOOL ?? '').toLowerCase())
73
- const SEED_PROMPT = enableRun ? SWE_SEED_PROMPT_WITH_RUN : SWE_SEED_PROMPT
74
- const allIds = [...new Set([...trainIds, ...selectionIds, ...testIds])]
75
- const workerProfile = withBenchProfile(
76
- {
77
- name: 'swe-agent-worker',
78
- harness: 'cli-base',
79
- model: { provider: 'tangle-router', default: workerModel },
80
- tools: {
81
- list_files: true,
82
- read_file: true,
83
- edit_file: true,
84
- ...(enableRun ? { run: true } : {}),
85
- },
86
- },
87
- { systemPrompt: SEED_PROMPT, maxTokens: workerMaxTokens, maxTurns: innerTurns },
88
- )
89
- const analystProfile = benchRouterProfile('swe-agent-analyst', workerModel, {
90
- systemPrompt: defaultAnalystInstruction,
91
- maxTokens: workerMaxTokens,
92
- })
93
-
94
- console.log('=== SWE-bench prompt optimization with official GEPA ===')
95
- console.log(`worker=${workerModel} reflect=${reflectModel} router=${routerBaseUrl}`)
96
- console.log(`train=[${trainIds.join(', ')}] selection=[${selectionIds.join(', ')}] test=[${testIds.join(', ')}]`)
97
- console.log(`maxEvaluations=${maxEvaluations} maxProposerCostUsd=${maxProposerCostUsd} innerTurns=${innerTurns} workerMaxTokens=${workerMaxTokens} runTool=${enableRun}`)
98
- console.log(`runDir=${runDir}\n`)
99
-
100
- if (process.env.DRYRUN) {
101
- // Import + wiring smoke: prove every module resolves and the plan is well-formed
102
- // WITHOUT paying for a clone / model call / Docker judge.
103
- console.log(`DRYRUN: imports OK (improve=${typeof improve}, officialGepa=${typeof officialGepa}, runAgentic=${typeof runAgentic}, refine=${typeof refine})`)
104
- return
105
- }
106
- const workerPricing = requiredTokenPricing(process.env, 'WORKER')
107
- const optimizer = officialOptimizerModel({
108
- env: process.env,
109
- model: reflectModel,
110
- baseUrl: reflectBase,
111
- apiKey: reflectKey,
112
- maxCostUsd: maxProposerCostUsd,
113
- maxOutputTokensPerRequest: reflectMaxTokens,
114
- })
115
-
116
- const { environment, adapter } = await createSweBenchEnvironment(allIds.length, { ids: allIds, enableRun })
117
- const pool = await adapter.loadTasks({ ids: allIds, split: 'test' })
118
- const byId = new Map<string, BenchTask>(pool.map((t) => [t.id, t]))
119
- for (const id of allIds) if (!byId.has(id)) throw new Error(`instance not found in Verified: ${id}`)
120
-
121
- // The agent under improvement: run the LOCAL SWE env with the CANDIDATE prompt on
122
- // one instance, return the git-diff patch. A per-call proxy captures the patch in
123
- // score() BEFORE runAgentic closes (rm) the workspace; its score is a cheap
124
- // patch-exists proxy so the ONLY Docker run per cell is the improve judge.
125
- const agent = async (candidate: ReadonlyAgentProfile, scenario: Scenario, ctx: DispatchContext): Promise<string | null> => {
126
- const exactCandidate = agentProfileSchema.parse(candidate)
127
- const promptText = exactCandidate.prompt?.systemPrompt
128
- if (promptText === undefined) throw new Error('agent: candidate profile has no system prompt')
129
- const bt = byId.get(scenario.id)
130
- if (!bt) throw new Error(`agent: unknown scenario ${scenario.id}`)
131
- const task = { id: bt.id, userPrompt: bt.prompt, meta: { instanceId: bt.id } }
132
- let capturedPatch = ''
133
- const stats = { list: 0, read: 0, edit_ok: 0, edit_fail: 0, run: 0, run_err: 0 }
134
- const proxy: AgenticSurface = {
135
- ...environment,
136
- async call(handle, name, args) {
137
- const res = await environment.call(handle, name, args)
138
- const r = String(res)
139
- if (name === 'list_files') stats.list += 1
140
- else if (name === 'read_file') stats.read += 1
141
- else if (name === 'edit_file') r.startsWith('edited ') ? (stats.edit_ok += 1) : (stats.edit_fail += 1)
142
- else if (name === 'run') r.startsWith('ERROR:') ? (stats.run_err += 1) : (stats.run += 1)
143
- return res
144
- },
145
- async score(_t, handle: ArtifactHandle): Promise<SurfaceScore> {
146
- try {
147
- const diff = await exec('git', ['-C', handle.id, 'diff'], { maxBuffer: 40_000_000, timeout: 60_000 })
148
- if (!capturedPatch.trim() && diff.stdout.trim()) capturedPatch = diff.stdout
149
- } catch {
150
- /* workspace gone or git error → treat as no patch */
151
- }
152
- return { passes: capturedPatch.trim() ? 1 : 0, total: 1, errored: 0 }
153
- },
154
- }
155
- const t0 = Date.now()
156
- const paid = await ctx.cost.runPaidCall({
157
- channel: 'agent',
158
- actor: 'swe-worker',
159
- model: workerModel,
160
- execute: () =>
161
- runAgentic({
162
- surface: proxy,
163
- task,
164
- strategy: refine,
165
- routerBaseUrl,
166
- routerKey,
167
- workerProfile: exactCandidate,
168
- analystProfile,
169
- budget: budgetShots,
170
- }),
171
- receipt: (result) => {
172
- const inputTokens = result.tokens.input ?? 0
173
- const outputTokens = result.tokens.output ?? 0
174
- const usageUnknown = inputTokens === 0 && outputTokens === 0
175
- return {
176
- model: workerModel,
177
- inputTokens,
178
- outputTokens,
179
- customTokenPricing: workerPricing,
180
- ...(usageUnknown ? { usageUnknown: true } : {}),
181
- }
182
- },
183
- })
184
- if (!paid.succeeded) throw paid.error
185
- const r = paid.value
186
- const zeroUsage = (r.tokens.input ?? 0) === 0 && (r.tokens.output ?? 0) === 0
187
- const hasPatch = capturedPatch.trim().length > 0
188
- const files = capturedPatch ? [...capturedPatch.matchAll(/^diff --git a\/(\S+)/gm)].map((m) => m[1]) : []
189
- console.log(
190
- ` [agent] ${scenario.id} prompt=${promptText.length}c tools(l/r/e+/e-/run/run!)=${stats.list}/${stats.read}/${stats.edit_ok}/${stats.edit_fail}/${stats.run}/${stats.run_err} ` +
191
- `patch=${capturedPatch.length}b files=[${files.join(', ') || 'none'}] tok=in:${r.tokens.input}/out:${r.tokens.output} ${Math.round((Date.now() - t0) / 1000)}s` +
192
- `${zeroUsage ? ' [provider usage unavailable]' : ''}`,
193
- )
194
- // A cell with no patch produced NO artifact. Return null (not '') so the
195
- // backend-integrity guard's own contract (`artifact == null → skip`) applies:
196
- // a glm-4.6 empty-content turn is scored 0 like the baseline, instead of
197
- // aborting the whole campaign as a false-positive "stub cell". Any cell that
198
- // DOES produce a patch still returns it and must report real usage or fire.
199
- return capturedPatch.trim() ? capturedPatch : null
200
- }
201
-
202
- // The judge: the OFFICIAL swebench Docker harness. Deterministic FAIL_TO_PASS +
203
- // PASS_TO_PASS → resolved 0/1. This is the held-out gate's scoring axis.
204
- const judge: JudgeConfig<string | null, Scenario> = {
205
- name: 'swebench-docker',
206
- dimensions: [{ key: 'resolved', description: 'FAIL_TO_PASS + PASS_TO_PASS resolved by the official swebench Docker harness' }],
207
- async score({ artifact, scenario }) {
208
- const patch = String(artifact ?? '')
209
- if (!patch.trim()) {
210
- console.log(` [judge] ${scenario.id} resolved=0 (no patch)`)
211
- return { dimensions: { resolved: 0 }, composite: 0, notes: 'no patch emitted' }
212
- }
213
- const bt = byId.get(scenario.id)
214
- if (!bt) throw new Error(`judge: unknown scenario ${scenario.id}`)
215
- const s = await adapter.judge(bt, patch)
216
- console.log(` [judge] ${scenario.id} resolved=${s.resolved ? 1 : 0}`)
217
- // 1500 chars keeps the whole swebench report JSON (a flat summary object —
218
- // it has no separate failure section to extract); the old 200 clipped it to
219
- // an uninformative head, leaving GEPA reflection trace-blind.
220
- return { dimensions: { resolved: s.resolved ? 1 : 0 }, composite: s.resolved ? 1 : 0, notes: (s.detail ?? '').slice(0, 1500) }
221
- },
222
- }
223
-
224
- const scenario = (id: string): Scenario => ({ id, kind: 'swe-bench-verified' })
225
-
226
- const out = await improve(workerProfile, {
227
- surface: 'prompt',
228
- executionRef: canonicalCandidateDigest({
229
- callback: 'bench/swe-improve',
230
- model: workerModel,
231
- endpoint: new URL(routerBaseUrl).origin,
232
- innerTurns,
233
- maxTokens: workerMaxTokens,
234
- budgetShots,
235
- enableRun,
236
- }),
237
- method: officialGepa<Scenario, string | null>({
238
- objective:
239
- 'Improve the system prompt of a coding agent that fixes real GitHub bugs with list_files, read_file, edit_file, and optional run tools.',
240
- background:
241
- 'Return the complete system prompt. Preserve tool names and require evidence from repository files and tests.',
242
- recipe: {
243
- kind: 'engine',
244
- run: {
245
- engine: 'gepa',
246
- maxEvaluations,
247
- maxProposerCostUsd,
248
- },
249
- },
250
- optimizer,
251
- resume: 'if-compatible',
252
- trustResumeState: true,
253
- describeScenario: (item) => ({ prompt: byId.get(item.id)?.prompt ?? item.id }),
254
- }),
255
- trainScenarios: trainIds.map(scenario),
256
- selectionScenarios: selectionIds.map(scenario),
257
- testScenarios: testIds.map(scenario),
258
- judges: [judge],
259
- agent,
260
- expectUsage: 'warn',
261
- maxConcurrency,
262
- reps: 1,
263
- runDir,
264
- optimizationRunOptions: {
265
- expectUsage: 'warn',
266
- maxConcurrency,
267
- reps: 1,
268
- },
269
- })
270
-
271
- assertCompleteCost('SWE-bench official GEPA run', out.cost)
272
- console.log('\n=== RESULT ===')
273
- console.log(`decision=${out.decision} lift=${out.lift} interval=[${out.liftInterval.low}, ${out.liftInterval.high}]`)
274
- console.log(`baseline test composite=${out.raw.best.baselineComposite}`)
275
- console.log(`winner test composite=${out.raw.best.winnerComposite}`)
276
- console.log(`test scenarios=${JSON.stringify(out.raw.best.scenarioScores)}`)
277
- console.log(`cost=${JSON.stringify(out.cost)}`)
278
- console.log(`candidate prompt:\n${String(out.candidate.value).slice(0, 2000)}`)
279
- }
280
-
281
- main().catch((e) => {
282
- console.error(e instanceof Error ? (e.stack ?? e.message) : String(e))
283
- process.exit(1)
284
- })
@@ -1,265 +0,0 @@
1
- /**
2
- * SEE-able LOCAL proof of the SWE-bench Verified pipeline — NO tangle sandbox.
3
- *
4
- * The whole loop runs on infra we can watch: the repo is cloned into a host tmpdir, the agent is a
5
- * router-driven tool loop (`runAgentic` + the swe-bench `AgenticSurface`'s list/read/edit tools —
6
- * jailed to the checkout), the patch is a plain `git diff` of the agent's edits, and the score is
7
- * the OFFICIAL swebench Docker harness (`adapter.judge`). The only remote call is the model
8
- * completion via the router. Nothing touches sandbox.tangle.tools.
9
- *
10
- * We proxy the surface's `score()` so we can SEE the exact bytes the judge grades: the extracted
11
- * patch, whether it applies to a clean base checkout (`git apply --check`), and the swebench verdict.
12
- * With TRACE=1 we also log every tool call so we can tell "agent never edited" from "agent can't edit".
13
- *
14
- * TANGLE_API_KEY=… dotenvx run -f …/agent-state.env -- \
15
- * IDS=django__django-12419 WORKER_MODEL=glm-4.6 \
16
- * node_modules/.bin/tsx bench/src/swe-local-proof.mts
17
- */
18
- import { execFile } from 'node:child_process'
19
- import { appendFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
20
- import { tmpdir } from 'node:os'
21
- import { join } from 'node:path'
22
- import { promisify } from 'node:util'
23
- import type { AgenticSurface, ArtifactHandle, SurfaceScore } from '@tangle-network/agent-runtime/kernel'
24
- import { defaultAnalystInstruction, refine, runAgentic } from '@tangle-network/agent-runtime/kernel'
25
- import type { BenchScore } from './benchmarks/types'
26
- import { createSweBenchEnvironment, SWE_SEED_PROMPT, SWE_SEED_PROMPT_WITH_RUN } from './swe-bench-env'
27
- import { benchRouterProfile, withBenchProfile } from './router-turn'
28
-
29
- const exec = promisify(execFile)
30
-
31
- async function main(): Promise<void> {
32
- const routerKey = process.env.TANGLE_API_KEY
33
- if (!routerKey) throw new Error('TANGLE_API_KEY required (the worker calls the router)')
34
- const routerBaseUrl = process.env.ROUTER_BASE ?? 'https://router.tangle.tools/v1'
35
- const model = process.env.WORKER_MODEL ?? 'glm-4.6'
36
- const ids = (process.env.IDS ?? 'django__django-12419').split(',').map((s) => s.trim()).filter(Boolean)
37
- const innerTurns = Number(process.env.INNER_TURNS ?? 40)
38
- const maxTokens = Number(process.env.MAX_TOKENS ?? 8000)
39
- const budget = Number(process.env.BUDGET ?? 1)
40
- // WITH-TOOLS arm: RUN_TOOL=1 exposes the jailed `run` tool + the run-aware prompt. Default OFF ⇒
41
- // the read/edit-only baseline (glm-5.2 7/12) unchanged.
42
- const enableRun = ['1', 'true', 'yes'].includes((process.env.RUN_TOOL ?? '').toLowerCase())
43
- const artifactDir = process.env.RUN_ARTIFACT_DIR
44
- if (artifactDir) mkdirSync(artifactDir, { recursive: true })
45
-
46
- console.log(`═══ SWE-bench Verified — SEE-able LOCAL proof (no tangle sandbox) ═══`)
47
- console.log(`model=${model} ids=${ids.join(',')} innerTurns=${innerTurns} maxTokens=${maxTokens} budget=${budget} runTool=${enableRun}`)
48
- console.log(`router=${routerBaseUrl}`)
49
-
50
- const { environment, tasks, adapter } = await createSweBenchEnvironment(ids.length, {
51
- ids,
52
- enableRun,
53
- ...(artifactDir ? {
54
- adapterOptions: {
55
- captureEvaluatorArtifacts: ({ taskId, attemptSequence }) => ({
56
- destination: join(artifactDir, taskId, `judge-${attemptSequence}`),
57
- }),
58
- },
59
- } : {}),
60
- })
61
- const workerProfile = withBenchProfile(
62
- {
63
- name: 'swe-local-proof-worker',
64
- harness: 'cli-base',
65
- model: { provider: 'tangle-router', default: model },
66
- tools: {
67
- list_files: true,
68
- read_file: true,
69
- edit_file: true,
70
- ...(enableRun ? { run: true } : {}),
71
- },
72
- },
73
- {
74
- systemPrompt: enableRun ? SWE_SEED_PROMPT_WITH_RUN : SWE_SEED_PROMPT,
75
- maxTokens,
76
- maxTurns: innerTurns,
77
- },
78
- )
79
- const analystProfile = benchRouterProfile('swe-local-proof-analyst', model, {
80
- systemPrompt: defaultAnalystInstruction,
81
- maxTokens,
82
- })
83
- const taskList = await tasks(0, ids.length)
84
- const benchTaskById = new Map(
85
- (await adapter.loadTasks({ ids, split: 'test' })).map((task) => [task.id, task]),
86
- )
87
-
88
- // One shot per pinned id: proxy score() to capture the exact judged bytes + a NON-DESTRUCTIVE
89
- // apply-coherence check, then delegate the verdict to the real Docker judge.
90
- //
91
- // CRITICAL: score() is called MORE THAN ONCE per task by the driver — the shotExecutor scores
92
- // the handle to drive its loop, and depthStrategy scores it again at the end. So this proxy MUST
93
- // be non-destructive (never mutate the working tree the agent edited) and idempotent (never
94
- // clobber a captured non-empty patch with a later empty read). It also caches the judge by patch
95
- // so we don't run the Docker harness twice for the identical diff.
96
- type Rec = { patch: string; applied: boolean; applyErr?: string; applyChecked?: boolean; score?: BenchScore }
97
- const captured = new Map<string, Rec>()
98
- const judged = new Map<string, BenchScore>()
99
- const toolStats = new Map<string, { list: number; read: number; edit_ok: number; edit_fail: number; run: number; run_err: number }>()
100
- let activeTaskId = ''
101
- const recordTool = (name: string, args: unknown, result: unknown, error?: string) => {
102
- if (!artifactDir || !activeTaskId) return
103
- const taskDir = join(artifactDir, activeTaskId)
104
- mkdirSync(taskDir, { recursive: true })
105
- appendFileSync(join(taskDir, 'tools.jsonl'), JSON.stringify({
106
- at: new Date().toISOString(), name, args,
107
- ...(error ? { error } : { result }),
108
- }) + '\n')
109
- }
110
- const proxy: AgenticSurface = {
111
- ...environment,
112
- async call(handle, name, args) {
113
- let res: string
114
- try {
115
- res = await environment.call(handle, name, args)
116
- } catch (error) {
117
- recordTool(name, args, undefined, error instanceof Error ? error.message : String(error))
118
- throw error
119
- }
120
- recordTool(name, args, res)
121
- // Count tool usage per workspace so we can SEE whether the agent ever edited, and whether
122
- // edits succeeded or bounced off old_string matching. handle.id keys the workspace.
123
- const st = toolStats.get(handle.id) ?? { list: 0, read: 0, edit_ok: 0, edit_fail: 0, run: 0, run_err: 0 }
124
- const r = String(res)
125
- if (name === 'list_files') st.list += 1
126
- else if (name === 'read_file') st.read += 1
127
- else if (name === 'edit_file') {
128
- if (r.startsWith('edited ')) st.edit_ok += 1
129
- else st.edit_fail += 1
130
- } else if (name === 'run') {
131
- if (r.startsWith('ERROR:')) st.run_err += 1
132
- else st.run += 1
133
- }
134
- toolStats.set(handle.id, st)
135
- if (process.env.TRACE) {
136
- const a = JSON.stringify(args).slice(0, 200)
137
- console.error(`[TOOL] ${name} args=${a} -> ${r.slice(0, 200).replace(/\n/g, '⏎')}`)
138
- }
139
- return res
140
- },
141
- async score(task, handle: ArtifactHandle): Promise<SurfaceScore> {
142
- const dir = handle.id
143
- const diff = await exec('git', ['-C', dir, 'diff'], { maxBuffer: 40_000_000, timeout: 60_000 })
144
- const patch = diff.stdout
145
- // Mirror tool stats onto the task id (handle.id == dir).
146
- const st = toolStats.get(dir)
147
- if (st) toolStats.set(task.id, st)
148
- // Idempotent capture: keep the FIRST non-empty patch; never overwrite it with a later empty read.
149
- const prev = captured.get(task.id)
150
- let rec: Rec
151
- if (!prev) {
152
- rec = { patch, applied: false }
153
- captured.set(task.id, rec)
154
- } else {
155
- rec = prev
156
- if (!rec.patch.trim() && patch.trim()) rec.patch = patch
157
- }
158
- const effPatch = rec.patch
159
- if (!effPatch.trim()) return { passes: 0, total: 1, errored: 0 }
160
- // NON-DESTRUCTIVE apply-coherence check (once): the diff was produced from this tree vs HEAD,
161
- // so `git apply --check -R` proves it is a clean, self-consistent patch without touching the
162
- // working tree. The REAL forward-apply-to-clean-base proof is the swebench judge below, which
163
- // applies the patch in a fresh Docker checkout and reports apply failures.
164
- if (!rec.applyChecked) {
165
- rec.applyChecked = true
166
- const pf = join(mkdtempSync(join(tmpdir(), 'swe-apply-')), 'p.diff')
167
- writeFileSync(pf, effPatch)
168
- try {
169
- await exec('git', ['-C', dir, 'apply', '--check', '-R', pf], { timeout: 60_000 })
170
- rec.applied = true
171
- } catch (e) {
172
- rec.applied = false
173
- rec.applyErr = e instanceof Error ? e.message.slice(0, 200) : String(e)
174
- } finally {
175
- rmSync(pf, { force: true })
176
- }
177
- }
178
- // Cached judge: identical patch ⇒ identical verdict; don't pay for a second Docker run.
179
- let s = judged.get(effPatch)
180
- if (!s) {
181
- const benchTask = benchTaskById.get(task.id)
182
- if (!benchTask) throw new Error(`swe-local-proof: unknown benchmark task ${task.id}`)
183
- s = await adapter.judge(benchTask, effPatch)
184
- judged.set(effPatch, s)
185
- }
186
- rec.score = s
187
- return { passes: s.resolved ? 1 : 0, total: 1, errored: 0 }
188
- },
189
- }
190
-
191
- let anyResolved = 0
192
- for (const task of taskList) {
193
- activeTaskId = task.id
194
- const t0 = Date.now()
195
- const r = await runAgentic({
196
- surface: proxy,
197
- task,
198
- strategy: refine,
199
- routerBaseUrl,
200
- routerKey,
201
- workerProfile,
202
- analystProfile,
203
- budget,
204
- ...(artifactDir ? { hooks: { onEvent(event: unknown) {
205
- const taskDir = join(artifactDir, activeTaskId)
206
- mkdirSync(taskDir, { recursive: true })
207
- appendFileSync(join(taskDir, 'runtime-events.jsonl'), JSON.stringify(event, (_key, value) =>
208
- value instanceof Error ? { name: value.name, message: value.message, stack: value.stack } : value,
209
- ) + '\n')
210
- } } } : {}),
211
- })
212
- const rec = captured.get(task.id)
213
- const st = toolStats.get(task.id)
214
- const patchBytes = rec?.patch.length ?? 0
215
- const patchLines = rec?.patch ? rec.patch.split('\n').length : 0
216
- const files = rec?.patch ? [...rec.patch.matchAll(/^diff --git a\/(\S+)/gm)].map((m) => m[1]) : []
217
- const resolved = rec?.score?.resolved ?? false
218
- if (resolved) anyResolved += 1
219
- console.log(`\n──── ${task.id} ────`)
220
- console.log(` agent shots=${r.shots} completions=${r.completions} tokens=in:${r.tokens.input}/out:${r.tokens.output} usd=${r.usd} wall=${Math.round((Date.now() - t0) / 1000)}s`)
221
- console.log(` tools: list=${st?.list ?? 0} read=${st?.read ?? 0} edit_ok=${st?.edit_ok ?? 0} edit_fail=${st?.edit_fail ?? 0} run=${st?.run ?? 0} run_err=${st?.run_err ?? 0}`)
222
- console.log(` patch: ${patchBytes} bytes, ${patchLines} lines, files=[${files.join(', ') || '(none)'}]`)
223
- console.log(` patch APPLIED (git apply --check on clean base): ${rec?.applied ? 'YES' : 'NO'}${rec?.applyErr ? ` (${rec.applyErr})` : ''}`)
224
- console.log(` swebench judge RESOLVED: ${resolved ? '1' : '0'}`)
225
- if (rec?.score?.detail) console.log(` judge report: ${rec.score.detail.slice(0, 400)}`)
226
- if (artifactDir) {
227
- const taskDir = join(artifactDir, task.id)
228
- mkdirSync(taskDir, { recursive: true })
229
- writeFileSync(join(taskDir, 'patch.diff'), rec?.patch ?? '')
230
- writeFileSync(join(taskDir, 'summary.json'), JSON.stringify({
231
- benchmark: 'SWE-bench Verified',
232
- taskId: task.id,
233
- modelRequested: model,
234
- prompt: task.userPrompt,
235
- turnsLimit: innerTurns,
236
- maxTokens,
237
- budget,
238
- enableRun,
239
- shots: r.shots,
240
- completions: r.completions,
241
- tokens: r.tokens,
242
- tokensKnown: r.tokensKnown,
243
- billedCostUsd: null,
244
- reportedUsd: r.usd,
245
- reportedUsdKnown: r.usdKnown,
246
- progression: r.progression,
247
- runScore: r.score,
248
- runResolved: r.resolved,
249
- wallMs: Date.now() - t0,
250
- toolStats: st ?? null,
251
- patchBytes,
252
- patchLines,
253
- files,
254
- patchApplies: rec?.applied ?? false,
255
- score: rec?.score ?? null,
256
- }, null, 2) + '\n')
257
- }
258
- }
259
- console.log(`\n>>> resolved ${anyResolved}/${taskList.length}`)
260
- }
261
-
262
- main().catch((e) => {
263
- console.error(e instanceof Error ? (e.stack ?? e.message) : String(e))
264
- process.exit(1)
265
- })