@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,130 +0,0 @@
1
- // Step A (increment 1) of the trajectory-capture pipeline: turn a Claude Code session
2
- // transcript (you driving the top-level agent) into the human-driving signal — the
3
- // (intent, steer-move, fan-out) half — and emit FeedbackTrajectory-SHAPED records plus a
4
- // driving-policy summary. This is the imitation corpus: "what Drew steers toward."
5
- //
6
- // Increment 1 = the MAIN transcript's human signal (intent turns, short steers, the
7
- // explicit AskUserQuestion forks, and per-turn subagent/workflow fan-out). Increment 2
8
- // joins the subagent/workflow subtrees + attaches outcomes, and wires agent-eval's real
9
- // FeedbackTrajectory type + summarizePreferenceMemory. Plain Node ESM (streams big files).
10
- //
11
- // node trajectory-assemble.mjs [transcript.jsonl] [outDir]
12
-
13
- import { createReadStream, mkdirSync, writeFileSync } from 'node:fs'
14
- import { createInterface } from 'node:readline'
15
-
16
- const TRANSCRIPT =
17
- process.argv[2] ??
18
- '/home/drew/.claude/projects/-home-drew-code-agent-runtime/52d557cf-89a5-45b8-b590-8c598fb378ab.jsonl'
19
- const OUT_DIR = process.argv[3] ?? '/tmp/trajectory'
20
-
21
- // A short imperative/approval turn is a STEER (a course-correction on the prior move);
22
- // a longer turn is a fresh INTENT. Crude but matches how driving reads on the wire.
23
- const STEER_MAX = 160
24
- const STEER_HINT = /^(yes|yep|yeah|yalla|ok|okay|do it|go|sure|nah|no|stop|push|merge|continue|keep going|build it|ship it|lgtm|sounds good|great|perfect|exactly|right)/i
25
-
26
- const intents = [] // { uuid, promptId, ts, text, kind: 'intent'|'steer' }
27
- const asks = [] // { ts, promptId, toolUseId, questions:[{q,header,options[]}], chosen }
28
- const spawnsByPrompt = new Map() // promptId -> { agents, workflows }
29
- const toolCounts = new Map()
30
- let assistantTurns = 0
31
-
32
- const bump = (m, k) => m.set(k, (m.get(k) ?? 0) + 1)
33
-
34
- const rl = createInterface({ input: createReadStream(TRANSCRIPT), crlfDelay: Infinity })
35
- for await (const line of rl) {
36
- if (!line.trim()) continue
37
- let r
38
- try {
39
- r = JSON.parse(line)
40
- } catch {
41
- continue
42
- }
43
- const c = r?.message?.content
44
- if (r.type === 'user' && typeof c === 'string' && r.isSidechain !== true) {
45
- const text = c.trim()
46
- if (!text) continue
47
- const kind = text.length <= STEER_MAX && STEER_HINT.test(text) ? 'steer' : 'intent'
48
- intents.push({ uuid: r.uuid, promptId: r.promptId, ts: r.timestamp, text, kind })
49
- } else if (r.type === 'assistant' && Array.isArray(c)) {
50
- assistantTurns += 1
51
- for (const b of c) {
52
- if (b?.type !== 'tool_use') continue
53
- bump(toolCounts, b.name)
54
- if (b.name === 'Agent' || b.name === 'Workflow') {
55
- const pid = r.promptId ?? 'unknown'
56
- const cur = spawnsByPrompt.get(pid) ?? { agents: 0, workflows: 0 }
57
- if (b.name === 'Agent') cur.agents += 1
58
- else cur.workflows += 1
59
- spawnsByPrompt.set(pid, cur)
60
- }
61
- if (b.name === 'AskUserQuestion') {
62
- const questions = (b.input?.questions ?? []).map((q) => ({
63
- q: q.question,
64
- header: q.header,
65
- options: (q.options ?? []).map((o) => o.label),
66
- }))
67
- asks.push({ ts: r.timestamp, promptId: r.promptId, toolUseId: b.id, questions, chosen: null })
68
- }
69
- }
70
- } else if (r.type === 'user' && Array.isArray(c)) {
71
- for (const b of c) {
72
- if (b?.type !== 'tool_result') continue
73
- const tur = r.toolUseResult
74
- const a = asks.find((x) => x.toolUseId === b.tool_use_id && x.chosen === null)
75
- if (a && tur && (tur.answers || tur.metadata)) a.chosen = tur.answers ?? null
76
- }
77
- }
78
- }
79
-
80
- const steers = intents.filter((i) => i.kind === 'steer')
81
- const realIntents = intents.filter((i) => i.kind === 'intent')
82
- const fanouts = [...spawnsByPrompt.entries()]
83
- .map(([pid, v]) => ({ pid, ...v, total: v.agents + v.workflows }))
84
- .filter((x) => x.total >= 2)
85
- .sort((a, b) => b.total - a.total)
86
-
87
- // FeedbackTrajectory-SHAPED records (one per human turn) — the imitation corpus root nodes.
88
- const trajectory = intents.map((i) => ({
89
- id: i.uuid,
90
- createdAt: i.ts,
91
- task: { intent: i.text },
92
- labels: [{ source: 'user', kind: i.kind, value: i.text }],
93
- tags: { promptId: i.promptId, fanout: spawnsByPrompt.get(i.promptId) ?? null },
94
- attempts: [], // increment 2: join the assistant actions + subagent subtrees here
95
- outcome: null, // increment 2: label success (verifiable reward / later approval)
96
- }))
97
-
98
- mkdirSync(OUT_DIR, { recursive: true })
99
- writeFileSync(`${OUT_DIR}/trajectory.jsonl`, `${trajectory.map((t) => JSON.stringify(t)).join('\n')}\n`)
100
-
101
- const top = (m, n) =>
102
- [...m.entries()].sort((a, b) => b[1] - a[1]).slice(0, n).map(([k, v]) => `${k}:${v}`).join(' ')
103
-
104
- console.log(`\n=== DRIVING-POLICY EXTRACT (${TRANSCRIPT.split('/').pop()}) ===`)
105
- console.log(`human turns: ${intents.length} (intents ${realIntents.length} · steers ${steers.length})`)
106
- console.log(`assistant turns: ${assistantTurns} tool calls: ${top(toolCounts, 12)}`)
107
- console.log(`explicit forks (AskUserQuestion): ${asks.length} parallel fan-out turns (>=2 spawns): ${fanouts.length}`)
108
-
109
- console.log(`\n--- the explicit decisions you made at forks (your steering policy, labeled) ---`)
110
- for (const a of asks.slice(0, 30)) {
111
- for (const q of a.questions) {
112
- const chosenLabel = a.chosen ? Object.values(a.chosen).map((v) => (typeof v === 'string' ? v : JSON.stringify(v))).join(' / ') : '(unmatched)'
113
- console.log(` [${q.header ?? '?'}] ${String(q.q).slice(0, 80)}`)
114
- console.log(` options: ${q.options.join(' | ')}`)
115
- console.log(` CHOSE: ${chosenLabel}`)
116
- }
117
- }
118
-
119
- console.log(`\n--- your recurring short steers (the corrections you repeat) ---`)
120
- const steerCounts = new Map()
121
- for (const s of steers) bump(steerCounts, s.text.toLowerCase().slice(0, 40))
122
- for (const [phrase, n] of [...steerCounts.entries()].sort((a, b) => b[1] - a[1]).slice(0, 15)) {
123
- console.log(` ${n}x ${phrase}`)
124
- }
125
-
126
- console.log(`\n--- biggest parallel fan-outs (one intent → N concurrent agents/workflows) ---`)
127
- for (const f of fanouts.slice(0, 8)) console.log(` ${f.total} spawns (agents ${f.agents}, workflows ${f.workflows}) promptId ${String(f.pid).slice(0, 12)}`)
128
-
129
- console.log(`\nwrote ${trajectory.length} FeedbackTrajectory-shaped records → ${OUT_DIR}/trajectory.jsonl`)
130
- console.log(`(increment 2: join subagent/workflow subtrees + outcome labels + agent-eval FeedbackTrajectory/summarizePreferenceMemory)`)
@@ -1,381 +0,0 @@
1
- /**
2
- * Official GEPA prompt optimization for Trata hedge-bench.
3
- *
4
- * The optimization surface is the system prompt given to the financial analyst
5
- * worker. GEPA reflects on which rubric themes were missed across training tasks
6
- * and proposes improved system prompts, learning to instruct the model to
7
- * extract specific quantitative claims, cover multiple analytical themes, and
8
- * cite named evidence. Candidate selection and final testing use disjoint data.
9
- *
10
- * The surface evolves beyond a bare system instruction: GEPA naturally discovers
11
- * that it can add few-shot analytical patterns, calculation templates, and
12
- * structured coverage checklists, effectively skill-creating without
13
- * hand-engineering. Set K_ROUNDS=2 to add a self-critique refine pass.
14
- *
15
- * Usage:
16
- * TRATA_BENCH_ROOT=/tmp/trata-hedge-bench \
17
- * JUDGE_MODEL=gemini-2.5-flash WORKER_MODEL=deepseek-v4-flash \
18
- * REFLECT_MODEL=gemini-2.5-pro \
19
- * TRAIN_N=70 SELECTION_N=16 TEST_N=16 MAX_EVALUATIONS=12 CONCURRENCY=8 \
20
- * dotenvx run -f ~/company/devops/secrets/agent-state.env -- \
21
- * pnpm exec tsx bench/src/trata-gepa.mts
22
- *
23
- * Key env vars:
24
- * TRATA_BENCH_ROOT cloned trata-hedge-bench (default /tmp/trata-hedge-bench)
25
- * WORKER_MODEL analyst model (default deepseek-v4-flash)
26
- * JUDGE_MODEL judge model in trata adapter (default gemini-2.5-flash)
27
- * REFLECT_MODEL GEPA reflection model (default gemini-2.5-pro)
28
- * TRAIN_N training tasks (default 70)
29
- * SELECTION_N optimizer selection tasks (default 16)
30
- * TEST_N untouched final comparison tasks (default 16)
31
- * MAX_EVALUATIONS GEPA callback evaluations (default 12)
32
- * MAX_PROPOSER_COST_USD GEPA proposal budget (default 5)
33
- * REPS reps per scenario (default 1)
34
- * CONCURRENCY parallel worker slots (default 8)
35
- * K_ROUNDS 1=single-shot, 2=analysis+self-critique (default 1)
36
- * BASELINE_DIRECTIVE override the starting system prompt
37
- * CORPUS path to write JSONL run records (optional)
38
- */
39
-
40
- import {
41
- canonicalCandidateDigest,
42
- type AgentProfile,
43
- } from '@tangle-network/agent-interface'
44
- import type {
45
- DispatchContext,
46
- JudgeConfig,
47
- JudgeScore,
48
- Scenario,
49
- } from '@tangle-network/agent-eval/campaign'
50
- import {
51
- improve,
52
- officialGepa,
53
- type ReadonlyAgentProfile,
54
- } from '@tangle-network/agent-runtime'
55
- import { appendFileSync, writeFileSync } from 'node:fs'
56
- import { createTrataHedgeAdapter } from './benchmarks/trata-hedge'
57
- import type { BenchTask } from './benchmarks/types'
58
- import {
59
- assertCompleteCost,
60
- officialOptimizerModel,
61
- requiredTokenPricing,
62
- } from './official-optimizer-config.mjs'
63
- import { runBenchRouterTurn } from './router-turn'
64
-
65
- interface TrataScenario extends Scenario {
66
- task: BenchTask
67
- }
68
-
69
- function must(name: string): string {
70
- const v = process.env[name]
71
- if (!v) throw new Error(`env ${name} is required`)
72
- return v
73
- }
74
-
75
- function positiveInteger(name: string, fallback: number): number {
76
- const value = Number(process.env[name] ?? fallback)
77
- if (!Number.isSafeInteger(value) || value <= 0) {
78
- throw new Error(`env ${name} must be a positive integer`)
79
- }
80
- return value
81
- }
82
-
83
- function positiveNumber(name: string, fallback: number): number {
84
- const value = Number(process.env[name] ?? fallback)
85
- if (!Number.isFinite(value) || value <= 0) {
86
- throw new Error(`env ${name} must be a positive number`)
87
- }
88
- return value
89
- }
90
-
91
- // GEPA-optimised baseline — the best surface found across 9 runs (+8.6pp on holdout, 2 independent
92
- // confirmations). Future GEPA runs start from here; BASELINE_DIRECTIVE overrides if you want to
93
- // experiment from a different starting point.
94
- const DEFAULT_TRATA_SYSTEM = [
95
- 'You are a senior financial analyst producing a structured investment memo.',
96
- 'Begin your response with exactly "ANALYSIS:" on its own line (nothing before it), then write your full analysis.',
97
- 'Structure your analysis with clearly labeled sections for each distinct analytical theme',
98
- '(e.g., valuation, capital allocation, competitive dynamics, risk factors)',
99
- 'so that no major investment consideration is merged or omitted.',
100
- 'Benchmark the company explicitly against named sector peers, citing specific metrics such as',
101
- 'EV/EBITDA, P/E ratios, margin differentials, and growth premiums from the peer financial files.',
102
- 'Every factual claim must cite the filename (e.g., "per earnings_call/apo_q4_2025_earnings_call.txt").',
103
- 'Identify and verbatim-cite specific numerical targets from management guidance such as',
104
- 'earnings per share targets, margin percentages, growth rates, or AUM figures rather than paraphrasing approximately.',
105
- 'When evaluating capital allocation options, explicitly compute implied returns or internal rates of return (IRRs),',
106
- 'showing the arithmetic using price levels and targets from the source data.',
107
- 'Take a clear, decisive position — do not hedge with "it depends". Reconcile conflicting data points explicitly.',
108
- ].join(' ')
109
-
110
- // Refine round instruction — used only when K_ROUNDS >= 2.
111
- const REFINE_INSTRUCTION = [
112
- 'Review your analysis above. For each distinct analytical theme in the investment brief,',
113
- 'verify you have a dedicated section with at least one specific quantitative claim (a named figure,',
114
- 'percentage, ratio, or calculation) from the cited data files. Add any missing themes.',
115
- 'Rewrite any section that only gestures at a theme without a specific supporting data point.',
116
- ].join(' ')
117
-
118
- async function chatComplete(
119
- baseUrl: string,
120
- key: string,
121
- model: string,
122
- maxTokens: number,
123
- messages: Array<{ role: string; content: string }>,
124
- signal: AbortSignal,
125
- ): Promise<{ content: string; usage?: { input: number; output: number } }> {
126
- const system = messages.find((message) => message.role === 'system')?.content
127
- const result = await runBenchRouterTurn(
128
- {
129
- routerBaseUrl: baseUrl,
130
- routerKey: key,
131
- profile: {
132
- name: 'trata-gepa-worker',
133
- harness: 'cli-base',
134
- model: {
135
- provider: 'tangle-router',
136
- default: model,
137
- metadata: { temperature: 0 },
138
- maxVisibleOutputTokens: maxTokens,
139
- },
140
- ...(system ? { prompt: { systemPrompt: system } } : {}),
141
- },
142
- signal,
143
- },
144
- { messages: messages.filter((message) => message.role !== 'system') },
145
- )
146
- return {
147
- content: result.finalText,
148
- ...(result.usage.tokensKnown === false
149
- ? {}
150
- : { usage: { input: result.usage.input, output: result.usage.output } }),
151
- }
152
- }
153
-
154
- async function main(): Promise<void> {
155
- if (process.env.DRYRUN) {
156
- console.log(
157
- `DRYRUN: imports OK (improve=${typeof improve}, officialGepa=${typeof officialGepa})`,
158
- )
159
- return
160
- }
161
-
162
- const adapter = createTrataHedgeAdapter()
163
- await adapter.preflight()
164
-
165
- const model = process.env.WORKER_MODEL ?? 'deepseek-v4-flash'
166
- const reflectModel = process.env.REFLECT_MODEL ?? 'deepseek-v4-flash'
167
- const routerBaseUrl = process.env.ROUTER_BASE ?? 'https://router.tangle.tools/v1'
168
- const routerKey = must('TANGLE_API_KEY')
169
- const reflectBaseUrl = process.env.REFLECT_BASE ?? routerBaseUrl
170
- const reflectKey = process.env.REFLECT_KEY ?? routerKey
171
- const trainN = positiveInteger('TRAIN_N', 70)
172
- const selectionN = positiveInteger('SELECTION_N', 16)
173
- const testN = positiveInteger('TEST_N', 16)
174
- const kRounds = positiveInteger('K_ROUNDS', 1)
175
- const maxEvaluations = positiveInteger('MAX_EVALUATIONS', 12)
176
- const maxProposerCostUsd = positiveNumber('MAX_PROPOSER_COST_USD', 5)
177
- const maxConcurrency = positiveInteger('CONCURRENCY', 8)
178
- const reps = positiveInteger('REPS', 1)
179
- const workerMaxTokens = positiveInteger('MAX_TOKENS', 4096)
180
- const reflectMaxTokens = positiveInteger('REFLECT_MAX_TOKENS', 8192)
181
- const corpusPath = process.env.CORPUS
182
- const baselineSurface = process.env.BASELINE_DIRECTIVE ?? DEFAULT_TRATA_SYSTEM
183
- const runDir = process.env.RUN_DIR ?? '.runs/trata-official-gepa'
184
- const workerPricing = requiredTokenPricing(process.env, 'WORKER')
185
- const optimizer = officialOptimizerModel({
186
- env: process.env,
187
- model: reflectModel,
188
- baseUrl: reflectBaseUrl,
189
- apiKey: reflectKey,
190
- maxCostUsd: maxProposerCostUsd,
191
- maxOutputTokensPerRequest: reflectMaxTokens,
192
- })
193
-
194
- // Hash-shuffle by task id so all three partitions carry the same difficulty mix.
195
- const requestedTasks = trainN + selectionN + testN
196
- const tasks = await adapter.loadTasks({ limit: requestedTasks })
197
- if (tasks.length !== requestedTasks) {
198
- throw new Error(
199
- `Trata returned ${tasks.length} tasks; ${requestedTasks} are required for exact train/selection/test partitions`,
200
- )
201
- }
202
- const idHash = (s: string): number => {
203
- let h = 2166136261
204
- for (let i = 0; i < s.length; i += 1) {
205
- h ^= s.charCodeAt(i)
206
- h = Math.imul(h, 16777619)
207
- }
208
- return h >>> 0
209
- }
210
- tasks.sort((a, b) => idHash(a.id) - idHash(b.id) || a.id.localeCompare(b.id))
211
- const train = tasks.slice(0, trainN)
212
- const selection = tasks.slice(trainN, trainN + selectionN)
213
- const test = tasks.slice(trainN + selectionN)
214
- const toScenario = (t: BenchTask): TrataScenario => ({ id: t.id, kind: 'trata-hedge', task: t })
215
-
216
- console.log(
217
- `[trata-gepa] worker=${model} reflect=${reflectModel} rounds=${kRounds} train=${train.length} selection=${selection.length} test=${test.length}`,
218
- )
219
-
220
- // Run the financial analyst worker under the candidate surface.
221
- // For K_ROUNDS=2, a second round asks the model to review its own coverage.
222
- // Every provider call reports its returned usage through the campaign ledger.
223
- const runPaidCompletion = async (
224
- ctx: DispatchContext,
225
- actor: string,
226
- messages: Array<{ role: string; content: string }>,
227
- ): Promise<{ content: string; usage?: { input: number; output: number } }> => {
228
- const paid = await ctx.cost.runPaidCall({
229
- actor,
230
- model,
231
- execute: (signal) =>
232
- chatComplete(routerBaseUrl, routerKey, model, workerMaxTokens, messages, signal),
233
- receipt: (result) => ({
234
- model,
235
- inputTokens: result.usage?.input ?? 0,
236
- outputTokens: result.usage?.output ?? 0,
237
- customTokenPricing: workerPricing,
238
- ...(result.usage ? {} : { usageUnknown: true }),
239
- }),
240
- })
241
- if (!paid.succeeded) throw paid.error
242
- return paid.value
243
- }
244
-
245
- const runWithSurface = async (
246
- candidate: ReadonlyAgentProfile,
247
- scenario: TrataScenario,
248
- ctx: DispatchContext,
249
- ): Promise<string> => {
250
- const systemPrompt = candidate.prompt?.systemPrompt
251
- if (systemPrompt === undefined) throw new Error('Trata candidate profile has no system prompt')
252
- // Round 1: initial analysis under the candidate system prompt.
253
- const r1 = await runPaidCompletion(ctx, 'trata-worker-round-1', [
254
- { role: 'system', content: systemPrompt },
255
- { role: 'user', content: scenario.task.prompt },
256
- ])
257
- let answer = r1.content
258
-
259
- // Round 2 (optional): self-critique for rubric coverage.
260
- if (kRounds >= 2 && answer.trim()) {
261
- const r2 = await runPaidCompletion(ctx, 'trata-worker-round-2', [
262
- { role: 'system', content: systemPrompt },
263
- { role: 'user', content: scenario.task.prompt },
264
- { role: 'assistant', content: answer },
265
- { role: 'user', content: REFINE_INSTRUCTION },
266
- ])
267
- if (r2.content.trim()) answer = r2.content
268
- }
269
-
270
- if (corpusPath) {
271
- appendFileSync(
272
- corpusPath,
273
- JSON.stringify({ benchmark: 'trata-gepa', instanceId: scenario.task.id, model, answer: answer.slice(0, 500) }) +
274
- '\n',
275
- )
276
- }
277
- return answer
278
- }
279
-
280
- // Judge: wraps the Trata 3-stage judge. Returns partial-credit score (0/0.25/0.5/0.75/1.0).
281
- const judge: JudgeConfig<string, TrataScenario> = {
282
- name: 'trata-hedge-judge',
283
- dimensions: [
284
- { key: 'score', description: 'rubric theme coverage fraction (rawScore/4)' },
285
- { key: 'resolved', description: 'all themes hit + synthesis (rawScore=4)' },
286
- ],
287
- async score({ artifact, scenario }): Promise<JudgeScore> {
288
- if (!artifact.trim()) {
289
- return { dimensions: { score: 0, resolved: 0 }, composite: 0, notes: 'empty artifact' }
290
- }
291
- const verdict = await adapter.judge(scenario.task, artifact)
292
- const sc = typeof verdict.score === 'number' ? verdict.score : verdict.resolved ? 1 : 0
293
- return {
294
- dimensions: { score: sc, resolved: verdict.resolved ? 1 : 0 },
295
- composite: sc,
296
- notes: verdict.detail ?? '',
297
- }
298
- },
299
- }
300
-
301
- const profile: AgentProfile = {
302
- name: 'trata-financial-analyst',
303
- prompt: { systemPrompt: baselineSurface },
304
- }
305
- const result = await improve(profile, {
306
- surface: 'prompt',
307
- executionRef: canonicalCandidateDigest({
308
- callback: 'bench/trata-gepa',
309
- model,
310
- endpoint: new URL(routerBaseUrl).origin,
311
- maxTokens: workerMaxTokens,
312
- rounds: kRounds,
313
- judgeModel: process.env.JUDGE_MODEL ?? 'adapter-default',
314
- }),
315
- method: officialGepa<TrataScenario, string>({
316
- objective:
317
- 'Improve the complete system instruction for a financial analyst that writes evidence-backed investment memos.',
318
- background:
319
- 'The judge awards partial credit for covering every requested analytical theme with specific quantitative claims, named peer comparisons, explicit calculations, source citations, and a decisive synthesis. Preserve the required ANALYSIS: prefix.',
320
- recipe: {
321
- kind: 'engine',
322
- run: {
323
- engine: 'gepa',
324
- maxEvaluations,
325
- maxProposerCostUsd,
326
- },
327
- },
328
- optimizer,
329
- resume: 'if-compatible',
330
- trustResumeState: true,
331
- describeScenario: (scenario) => ({
332
- id: scenario.id,
333
- prompt: scenario.task.prompt,
334
- }),
335
- describeArtifact: (artifact) => ({ answer: artifact.slice(-4000) }),
336
- }),
337
- trainScenarios: train.map(toScenario),
338
- selectionScenarios: selection.map(toScenario),
339
- testScenarios: test.map(toScenario),
340
- judges: [judge],
341
- agent: runWithSurface,
342
- expectUsage: 'warn',
343
- maxConcurrency,
344
- reps,
345
- runDir,
346
- optimizationRunOptions: {
347
- expectUsage: 'warn',
348
- maxConcurrency,
349
- reps,
350
- },
351
- })
352
-
353
- assertCompleteCost('Trata official GEPA run', result.cost)
354
- console.log('\n=== trata-gepa RESULT ===')
355
- const improved = result.decision === 'ship'
356
- console.log(` baseline test mean: ${(result.raw.best.baselineComposite * 100).toFixed(1)}%`)
357
- console.log(` winner test mean: ${(result.raw.best.winnerComposite * 100).toFixed(1)}%`)
358
- console.log(` test delta: ${(result.lift * 100).toFixed(1)} pp`)
359
- console.log(
360
- ` 95% interval: [${(result.liftInterval.low * 100).toFixed(1)}, ${(result.liftInterval.high * 100).toFixed(1)}] pp`,
361
- )
362
- console.log(` decision: ${result.decision}`)
363
- console.log(` cost: ${JSON.stringify(result.cost)}`)
364
-
365
- const winnerSurface = String(result.candidate.value)
366
- if (improved) {
367
- console.log(`\n PROMOTED SYSTEM PROMPT:\n${winnerSurface}`)
368
- } else {
369
- console.log(' kept baseline (the final-test interval did not clear zero)')
370
- console.log(`\n BEST CANDIDATE SURFACE (set as BASELINE_DIRECTIVE to seed next run):\n${winnerSurface}`)
371
- }
372
- try {
373
- writeFileSync('/tmp/trata-gepa-winner-surface.txt', winnerSurface)
374
- console.log('\n (winner surface written to /tmp/trata-gepa-winner-surface.txt)')
375
- } catch { /* non-fatal */ }
376
- }
377
-
378
- main().catch((err) => {
379
- console.error(err instanceof Error ? (err.stack ?? err.message) : String(err))
380
- process.exit(1)
381
- })
@@ -1,81 +0,0 @@
1
- /** Single-shot lower-bound solver for trata-hedge-bench. */
2
- import { readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
3
- import { join, relative, resolve } from 'node:path'
4
- import { runBenchRouterTurn } from './router-turn'
5
-
6
- const environment = process.argv[2]
7
- if (!environment) throw new Error('usage: solve.mts <env-dir> [out.txt]')
8
- const output = process.argv[3] ?? '/tmp/thb-answer.txt'
9
- const model = process.env.WORKER_MODEL
10
- if (!model) throw new Error('WORKER_MODEL is required')
11
- const dataBudget = Number(process.env.DATA_BUDGET ?? 160_000)
12
- const maxTokens = Number(process.env.MAX_TOKENS ?? 6_000)
13
- const temperature = Number(process.env.TEMPERATURE ?? 0.5)
14
- const routerKey = process.env.TANGLE_API_KEY
15
- if (!routerKey) throw new Error('TANGLE_API_KEY is required')
16
- const routerBaseUrl = process.env.ROUTER_BASE ?? 'https://router.tangle.tools/v1'
17
-
18
- for (const [name, value] of [
19
- ['DATA_BUDGET', dataBudget],
20
- ['MAX_TOKENS', maxTokens],
21
- ] as const) {
22
- if (!Number.isSafeInteger(value) || value <= 0) throw new Error(`${name} must be a positive integer`)
23
- }
24
- if (!Number.isFinite(temperature)) throw new Error('TEMPERATURE must be finite')
25
-
26
- const root = resolve(environment)
27
- const dataDir = join(root, 'environment', 'data')
28
- const instruction = readFileSync(join(root, 'instruction.md'), 'utf8')
29
-
30
- function filesUnder(dir: string): string[] {
31
- return readdirSync(dir)
32
- .flatMap((name) => {
33
- const path = join(dir, name)
34
- return statSync(path).isDirectory() ? filesUnder(path) : [path]
35
- })
36
- }
37
-
38
- function rank(path: string): number {
39
- if (path.includes('earnings_call')) return 0
40
- if (path.includes('financials')) return 1
41
- if (path.includes('company_profiles')) return 2
42
- if (path.includes('press_releases')) return 3
43
- return 4
44
- }
45
-
46
- let used = 0
47
- const blocks: string[] = []
48
- const files = filesUnder(dataDir).sort((a, b) => rank(a) - rank(b) || a.localeCompare(b))
49
- for (const path of files) {
50
- const content = readFileSync(path, 'utf8')
51
- if (used + content.length > dataBudget) continue
52
- used += content.length
53
- blocks.push(`\n=== FILE: data/${relative(dataDir, path)} ===\n${content}`)
54
- }
55
- process.stderr.write(`[solve] ${blocks.length}/${files.length} files in context (${used} chars)\n`)
56
-
57
- const prompt =
58
- '--- AVAILABLE DATA (cite files by their `data/<path>` name inline) ---\n' +
59
- blocks.join('') +
60
- '\n\n--- END DATA ---\nWrite ONLY the full analysis (no preamble). Inline-cite every claim with its `data/<path>`.'
61
-
62
- const result = await runBenchRouterTurn(
63
- {
64
- routerBaseUrl,
65
- routerKey,
66
- profile: {
67
- name: 'trata-hedge-solver',
68
- harness: 'cli-base',
69
- model: {
70
- provider: 'tangle-router',
71
- default: model,
72
- metadata: { temperature },
73
- maxVisibleOutputTokens: maxTokens,
74
- },
75
- prompt: { systemPrompt: instruction },
76
- },
77
- },
78
- prompt,
79
- )
80
- writeFileSync(output, result.finalText)
81
- process.stderr.write(`[solve] wrote ${result.finalText.length} chars -> ${output} (model=${model})\n`)