@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,558 +0,0 @@
1
- /**
2
- * commit0 Layer-1 gate runner — the verifier-grounded selector AND the
3
- * observe→steer efficacy experiment on REAL stateful coding rollouts. Each shot is
4
- * a fresh sandbox where an opencode agent clones the stubbed repo at base_commit,
5
- * implements the source, and WRITES its diff to a file we read back over the
6
- * sandbox FS — NOT pasted in the final message (a large diff truncates there →
7
- * `git apply` "corrupt patch", the failure that made the generic stream-parse path
8
- * unusable). The official commit0 pytest harness then grades each diff to a
9
- * continuous (passed+xfail)/total reward — the within-task variance the
10
- * verifier-grounded selector needs (unlike aec's per-task-deterministic scores).
11
- *
12
- * ARMS (comma-separated, default `random`):
13
- * - random — K independent blind shots (the equal-compute control).
14
- * - refineAudit — shot 0 blind, then for each later shot a TRACE-ONLY analyst
15
- * (ANALYST_MODEL, default deepseek-v4-pro, off-box via the router) reads the
16
- * prior shot's diff + stream-trace tail and its findings are appended to a
17
- * FRESH sandbox's prompt. The analyst never sees a judge score — judging is
18
- * phase 2, after every rollout, so selector≠judge holds by construction.
19
- * Both arms run K shots per task: equal compute is the non-negotiable invariant
20
- * (the analyst call is the steering overhead, one cheap router completion).
21
- *
22
- * Two phases, deliberately split:
23
- * 1. ROLLOUTS run concurrently (sandbox-bound; CONCURRENCY units in flight; a
24
- * steered arm's shots chain sequentially inside one unit).
25
- * 2. JUDGES run SEQUENTIALLY (Docker-bound). commit0 keys its report dir on
26
- * hash(test_ids), shared across a repo's attempts, so concurrent judging of the
27
- * same repo races/overwrites report.json — the `None`-score bug.
28
- *
29
- * Judge prerequisite: the per-repo Docker image MUST exist before judging — the
30
- * local Docker backend ignores `rebuild_image` (only the Modal context honors it),
31
- * so run `./src/commit0-prereqs.sh <repo…>` (pulls wentingzhao/<repo>:v0, else
32
- * builds via commit0.harness.build) for every repo in the task list first.
33
- *
34
- * Fail loud: an attempt whose rollout errored, whose diff never materialized, or
35
- * whose judge harness failed is recorded as an INFRA attempt (error on the
36
- * AttemptRecord, no score) and its record is marked infraError — counted +
37
- * reported, excluded by corpus-report, never a silent 0.
38
- *
39
- * Writes one corpus RunRecord per (task, arm) (conditions `random@K`,
40
- * `refineAudit@K`) the existing `corpus-replay --selector=verifier` +
41
- * `corpus-report` consume unchanged.
42
- *
43
- * ./src/commit0-prereqs.sh wcwidth tinydb … # once per repo set
44
- * dotenvx run -f … -- env N=8 K=2 ARMS=random,refineAudit \
45
- * WORKER_MODEL=deepseek-v4-pro CONCURRENCY=3 CORPUS=/tmp/commit0.jsonl \
46
- * tsx src/commit0-gate.mts
47
- * tsx src/corpus-report.mts /tmp/commit0.jsonl # paired steering verdict
48
- * tsx src/corpus-replay.mts /tmp/commit0.jsonl --selector=verifier
49
- */
50
-
51
- import { spawn } from 'node:child_process'
52
- import { mkdtemp, rm } from 'node:fs/promises'
53
- import { tmpdir } from 'node:os'
54
- import { join } from 'node:path'
55
- import {
56
- collectAgentTurn,
57
- createExecutor,
58
- type AgentRunSpec,
59
- type Deliverable,
60
- openSandboxRun,
61
- type SandboxRun,
62
- streamAgentTurn,
63
- } from '@tangle-network/agent-runtime/kernel'
64
- import { Sandbox } from '@tangle-network/sandbox'
65
- import { createCommit0Adapter } from './benchmarks/commit0'
66
- import type { BenchTask } from './benchmarks/types'
67
- import { type AttemptRecord, appendRunRecord, buildRunRecordFromAttempts } from './corpus'
68
- import { type AnalystFn, llmAnalyst } from './sandbox-run'
69
- import {
70
- type BenchRuntimeDecisionPoint,
71
- type BenchRuntimeHookEvent,
72
- createRuntimeHookRecorder,
73
- } from './runtime-hook-recorder'
74
- import { pool } from './stats.mts'
75
-
76
- function must(name: string): string {
77
- const v = process.env[name]
78
- if (!v) throw new Error(`env ${name} is required`)
79
- return v
80
- }
81
-
82
- const PATCH_PATH = '/tmp/solution.patch'
83
- const randomSuffix = () => Math.random().toString(36).slice(2, 10)
84
-
85
- interface Commit0Meta {
86
- repo: string
87
- baseCommit: string
88
- srcDir: string
89
- testDir: string
90
- specification: string
91
- }
92
-
93
- interface Shot {
94
- task: BenchTask
95
- attempt: number
96
- diff: string
97
- ok: boolean
98
- detail?: string
99
- wallMs: number
100
- /** measured count of stream events from the rollout (0 if it errored before streaming) */
101
- events: number
102
- /** bounded tail of the raw stream events — the trace the analyst reads (trace-only). */
103
- traceEvents?: unknown[]
104
- /** the analyst findings appended to this shot's prompt (steered arm, round ≥ 1). */
105
- steer?: string
106
- runtimeEvents?: BenchRuntimeHookEvent[]
107
- runtimeDecisionPoints?: BenchRuntimeDecisionPoint[]
108
- }
109
-
110
- /** Last events of a rollout stream, kept for the trace-only analyst. */
111
- const TRACE_EVENTS_TAIL = 12
112
- /** Diff prefix shown to the analyst (it names files + hunks; the full diff can be 100KB+). */
113
- const ANALYST_DIFF_MAX = 6_000
114
- /** Findings ceiling appended to a steered prompt (the analyst is told 1-3 sentences). */
115
- const STEER_MAX = 1_500
116
-
117
- /** Append the analyst's findings to the base rollout prompt (fresh box — the
118
- * agent has no memory of the prior attempt, so the framing names it). */
119
- function steeredPrompt(base: string, steer: string): string {
120
- return `${base}\n\n--- Analysis of a previous attempt at this task ---\n${steer}\n\nApply this correction while you implement.`
121
- }
122
-
123
- /** Build the rollout prompt: clone the stub, implement the source, write the diff to
124
- * a FILE (the robust deliverable). Mirrors solveShot's file-read contract. */
125
- function rolloutPrompt(meta: Commit0Meta): string {
126
- return [
127
- `Clone https://github.com/${meta.repo} into /work, then \`cd /work && git checkout ${meta.baseCommit}\`.`,
128
- `The public functions/classes under \`${meta.srcDir}\` are stubbed (empty \`pass\`/\`...\` bodies). Your job is to`,
129
- `implement COMPLETE, CORRECT bodies under \`${meta.srcDir}\` so the existing test suite under \`${meta.testDir}\` passes.`,
130
- '',
131
- 'Work iteratively — do NOT stop at a first draft:',
132
- `1. Read the spec (${meta.specification}) and the tests under \`${meta.testDir}\` to learn the exact required behavior.`,
133
- `2. Install the package editable so imports resolve: \`pip install -e .\` (use the repo's setup if it differs).`,
134
- `3. Implement ALL stubbed bodies under \`${meta.srcDir}\` — every function/class, not just the easy ones.`,
135
- `4. RUN the suite: \`python -m pytest ${meta.testDir} -q\`. Read failures and FIX them. Repeat until as many tests`,
136
- ` pass as you can get — keep iterating; a partial implementation that fails most tests is not done.`,
137
- '5. Do NOT edit the tests — the evaluation re-runs them on a fresh clone.',
138
- '',
139
- `When the suite is green (or you have maximized passing tests), from /work run EXACTLY:`,
140
- ` git add -A && git diff --cached -- ${meta.srcDir} > ${PATCH_PATH}`,
141
- `Then stop. The patch file is the only deliverable — do NOT paste the diff in your reply.`,
142
- ].join('\n')
143
- }
144
-
145
- interface ShotCfg {
146
- sandboxBaseUrl: string
147
- sandboxKey: string
148
- routerBaseUrl: string
149
- /** Host-side opencode (`COMMIT0_BACKEND=local`) only — routes `openai/*` models
150
- * through the router from THIS machine. The sandbox path never sends it into
151
- * the box: in-box model auth is the box-provisioned `OPENCODE_MODEL_API_KEY`. */
152
- routerKey: string
153
- model: string
154
- /** in-box opencode provider. `openai-compat` (default) is the generic passthrough,
155
- * so router-served cheap models resolve in-box; `openai` only accepts its
156
- * registered model names (e.g. gpt-4.1). Override via WORKER_PROVIDER. */
157
- provider: string
158
- timeoutMs: number
159
- /** Local Runtime bridge transport. The profile, not this transport, selects the harness/model. */
160
- bridgeUrl?: string
161
- bridgeBearer?: string
162
- }
163
-
164
- function workerProfile(cfg: ShotCfg, name: string) {
165
- return {
166
- name,
167
- harness: 'opencode' as const,
168
- model: { provider: cfg.provider, default: cfg.model },
169
- }
170
- }
171
-
172
- /** The diff the in-box agent produces, read back off the box FS (+ any stream error). */
173
- interface RolloutDeliverable {
174
- diff: string
175
- lastErr?: string
176
- }
177
-
178
- /** Reads the patch FILE the agent wrote (the robust deliverable — a large diff
179
- * truncates in the chat stream → `git apply` "corrupt patch"), folding any in-box
180
- * error event into `lastErr` so a failed rollout still surfaces on an empty patch. */
181
- const commit0Deliverable: Deliverable<RolloutDeliverable> = {
182
- kind: 'artifact',
183
- path: PATCH_PATH,
184
- fromArtifact: (raw, events) => {
185
- let lastErr: string | undefined
186
- for (const ev of events) {
187
- if ((ev as { type?: string }).type === 'error') lastErr = JSON.stringify((ev as { data?: unknown }).data).slice(0, 300)
188
- }
189
- return { diff: raw, ...(lastErr ? { lastErr } : {}) }
190
- },
191
- }
192
-
193
- async function runShot(task: BenchTask, attempt: number, cfg: ShotCfg, steer?: string): Promise<Shot> {
194
- const meta = task.metadata as unknown as Commit0Meta
195
- const startedAt = Date.now()
196
- const client = new Sandbox({ baseUrl: cfg.sandboxBaseUrl, apiKey: cfg.sandboxKey })
197
- // A stream/transport ceiling for the flaky sandbox path (0 ⇒ untimed); the run
198
- // tears its own box down in `close()`. The whole rollout is fault-isolated: ANY
199
- // error (502 / stream drop / provision fail / abort) becomes a recorded NO-DIFF
200
- // attempt — it MUST NOT throw, or one flaky box aborts the pool and loses every
201
- // other rollout (the powered-run crash).
202
- const controller = new AbortController()
203
- const timer = cfg.timeoutMs > 0 ? setTimeout(() => controller.abort(), cfg.timeoutMs) : undefined
204
- // The exact profile owns harness/provider/model. Sandbox overrides contain only box
205
- // infrastructure; Runtime derives the backend from the profile and refuses conflicts.
206
- const agentRun: AgentRunSpec<string> = {
207
- profile: workerProfile(cfg, 'commit0-worker'),
208
- name: 'commit0-worker',
209
- taskToPrompt: () => '', // unused — the prompt is streamed directly by openSandboxRun
210
- sandboxOverrides: {
211
- name: `commit0-${task.id}-${attempt}-${randomSuffix()}`.replace(/[^a-zA-Z0-9_.-]/g, '_').slice(0, 60),
212
- environment: 'universal',
213
- },
214
- }
215
- let run: SandboxRun<RolloutDeliverable> | undefined
216
- const runtime = createRuntimeHookRecorder()
217
- try {
218
- run = await openSandboxRun(
219
- client,
220
- {
221
- agentRun,
222
- signal: controller.signal,
223
- hooks: runtime.hooks,
224
- runId: `commit0:${task.id}:${attempt}`,
225
- scenarioId: task.id,
226
- },
227
- commit0Deliverable,
228
- )
229
- const prompt = steer ? steeredPrompt(rolloutPrompt(meta), steer) : rolloutPrompt(meta)
230
- const turn = await run.start(prompt)
231
- const ok = turn.out.diff.trim().length > 0
232
- return {
233
- task,
234
- attempt,
235
- diff: turn.out.diff,
236
- ok,
237
- events: turn.events.length,
238
- traceEvents: turn.events.slice(-TRACE_EVENTS_TAIL),
239
- ...(steer ? { steer } : {}),
240
- runtimeEvents: runtime.events,
241
- runtimeDecisionPoints: runtime.decisionPoints,
242
- wallMs: Date.now() - startedAt,
243
- ...(ok ? {} : { detail: `empty patch${turn.readError ? ` (read failed: ${turn.readError.slice(0, 120)})` : ''}${turn.out.lastErr ? `; lastError=${turn.out.lastErr}` : ''}` }),
244
- }
245
- } catch (err) {
246
- const msg = err instanceof Error ? err.message : String(err)
247
- return {
248
- task,
249
- attempt,
250
- diff: '',
251
- ok: false,
252
- events: 0,
253
- ...(steer ? { steer } : {}),
254
- runtimeEvents: runtime.events,
255
- runtimeDecisionPoints: runtime.decisionPoints,
256
- wallMs: Date.now() - startedAt,
257
- detail: `rollout error: ${msg.slice(0, 200)}`,
258
- }
259
- } finally {
260
- if (timer) clearTimeout(timer)
261
- if (run) await run.close()
262
- }
263
- }
264
-
265
- /** Run a subprocess, capturing combined stdout+stderr; never throws (returns rc). */
266
- function sh(cmd: string, args: string[], opts: { cwd?: string; timeoutMs?: number; env?: NodeJS.ProcessEnv } = {}): Promise<{ code: number; out: string }> {
267
- return new Promise((resolve) => {
268
- const child = spawn(cmd, args, {
269
- ...(opts.cwd ? { cwd: opts.cwd } : {}),
270
- env: opts.env ?? process.env,
271
- ...(opts.timeoutMs ? { timeout: opts.timeoutMs } : {}),
272
- })
273
- let out = ''
274
- child.stdout?.on('data', (c: Buffer) => { out += c.toString() })
275
- child.stderr?.on('data', (c: Buffer) => { out += c.toString() })
276
- child.on('error', (e) => resolve({ code: -1, out: `${out}\n${e}` }))
277
- child.on('close', (code) => resolve({ code: code ?? -1, out }))
278
- })
279
- }
280
-
281
- /** Local-rollout prompt: the repo is ALREADY cloned + checked out into the cwd, so
282
- * (unlike the sandbox prompt) the agent implements + test-iterates in place; the diff
283
- * is read from git afterward (no chat-message truncation). */
284
- function localRolloutPrompt(meta: Commit0Meta): string {
285
- return [
286
- `The current directory is the stubbed Python library \`${meta.repo}\`, checked out at its base commit.`,
287
- `The public functions/classes under \`${meta.srcDir}\` are stubbed (empty \`pass\`/\`...\`). Implement COMPLETE, CORRECT bodies so the tests under \`${meta.testDir}\` pass.`,
288
- 'Work iteratively, do NOT stop at a first draft:',
289
- `1. Read the spec (${meta.specification}) and the tests under \`${meta.testDir}\`.`,
290
- '2. Set up an ISOLATED venv so imports + pytest resolve: `python3 -m venv .venv && .venv/bin/pip install -e .` (use the repo setup if it differs).',
291
- `3. Implement ALL stubbed bodies under \`${meta.srcDir}\`.`,
292
- `4. Run \`.venv/bin/python -m pytest ${meta.testDir} -q\`, read failures, FIX them, and repeat until as many tests pass as you can.`,
293
- '5. Do NOT edit the test files.',
294
- 'When done, just stop — do NOT print the diff; it is collected from git.',
295
- ].join('\n')
296
- }
297
-
298
- /**
299
- * LOCAL rollout backend (cli-bridge fallback for when the sandbox gateway is down):
300
- * clone + checkout the stub into a tmpdir, run local opencode (its own kimi/zai
301
- * coding-plan auth, or the router when model is `openai/*`) to implement + test-iterate
302
- * in place, then read the diff straight from git (complete — no message truncation).
303
- * Fault-isolated like runShot: any failure → a recorded NO-DIFF attempt, never a throw.
304
- */
305
- async function runShotLocal(task: BenchTask, attempt: number, cfg: ShotCfg, steer?: string): Promise<Shot> {
306
- const meta = task.metadata as unknown as Commit0Meta
307
- const startedAt = Date.now()
308
- let dir: string | undefined
309
- try {
310
- dir = await mkdtemp(join(tmpdir(), 'commit0-local-'))
311
- const clone = await sh('git', ['clone', '--quiet', `https://github.com/${meta.repo}`, dir], { timeoutMs: 180_000 })
312
- if (clone.code !== 0) {
313
- return { task, attempt, diff: '', ok: false, events: 0, wallMs: Date.now() - startedAt, detail: `git clone failed: ${clone.out.trim().slice(-180)}` }
314
- }
315
- const co = await sh('git', ['-C', dir, 'checkout', '--quiet', meta.baseCommit], { timeoutMs: 60_000 })
316
- if (co.code !== 0) {
317
- return { task, attempt, diff: '', ok: false, events: 0, wallMs: Date.now() - startedAt, detail: `git checkout ${meta.baseCommit} failed: ${co.out.trim().slice(-180)}` }
318
- }
319
- const prompt = steer ? steeredPrompt(localRolloutPrompt(meta), steer) : localRolloutPrompt(meta)
320
- if (!cfg.bridgeUrl || !cfg.bridgeBearer) {
321
- throw new Error('local rollout requires CLI_BRIDGE_URL/BRIDGE_URL and CLI_BRIDGE_BEARER/BRIDGE_BEARER')
322
- }
323
- const factory = createExecutor({
324
- backend: 'bridge',
325
- bridgeUrl: cfg.bridgeUrl,
326
- bridgeBearer: cfg.bridgeBearer,
327
- cwd: dir,
328
- ...(cfg.timeoutMs > 0 ? { timeoutMs: cfg.timeoutMs } : {}),
329
- })
330
- const turn = await collectAgentTurn(
331
- streamAgentTurn(
332
- { kind: 'executor', factory, profile: workerProfile(cfg, `commit0-local-${attempt}`) },
333
- { prompt },
334
- cfg.timeoutMs > 0 ? { timeoutMs: cfg.timeoutMs } : {},
335
- ),
336
- )
337
- if (turn.status !== 'completed') {
338
- throw new Error(turn.error?.message ?? `Runtime bridge ended with ${turn.status}`)
339
- }
340
- const traceEvents = turn.events.map((event) => JSON.stringify(event))
341
- const events = turn.events.length
342
- // Read the diff straight from git, scoped to src_dir (excludes the .venv the agent made).
343
- const diffRes = await sh('bash', ['-c', `cd ${JSON.stringify(dir)} && git add -- ${JSON.stringify(meta.srcDir)} && git diff --cached -- ${JSON.stringify(meta.srcDir)}`], { timeoutMs: 60_000 })
344
- const diff = diffRes.out
345
- const ok = diff.trim().length > 0
346
- return {
347
- task,
348
- attempt,
349
- diff,
350
- ok,
351
- events,
352
- traceEvents: traceEvents.slice(-TRACE_EVENTS_TAIL),
353
- ...(steer ? { steer } : {}),
354
- wallMs: Date.now() - startedAt,
355
- ...(ok ? {} : { detail: `no diff (Runtime bridge completed): ${turn.finalText.trim().slice(-160)}` }),
356
- }
357
- } catch (err) {
358
- return { task, attempt, diff: '', ok: false, events: 0, ...(steer ? { steer } : {}), wallMs: Date.now() - startedAt, detail: `local rollout error: ${(err instanceof Error ? err.message : String(err)).slice(0, 180)}` }
359
- } finally {
360
- if (dir) await rm(dir, { recursive: true, force: true }).catch(() => {})
361
- }
362
- }
363
-
364
- async function main(): Promise<void> {
365
- // BACKEND=local → cli-bridge fallback (local opencode, no remote sandbox); needs a
366
- // sandbox-down workaround. Default 'sandbox' (the remote gateway). Local uses opencode's
367
- // OWN auth (kimi-for-coding / zai coding-plan), so TANGLE_API_KEY is only required for
368
- // the sandbox backend or an `openai/*` local model (router).
369
- const backend = process.env.COMMIT0_BACKEND === 'local' ? 'local' : 'sandbox'
370
- const n = Number(process.env.N ?? 8)
371
- const k = Number(process.env.K ?? 4)
372
- const model = process.env.WORKER_MODEL ?? (backend === 'local' ? 'kimi-for-coding/kimi-k2-thinking' : 'deepseek-v4-flash')
373
- const routerBaseUrl = process.env.ROUTER_BASE ?? 'https://router.tangle.tools/v1'
374
- // The arms under test. `random` = K independent blind shots (the equal-compute
375
- // control); `refineAudit` = blind shot 0, then trace-only-analyst-steered shots.
376
- const armNames = (process.env.ARMS ?? 'random').split(',').map((s) => s.trim()).filter(Boolean)
377
- for (const a of armNames) {
378
- if (a !== 'random' && a !== 'refineAudit') throw new Error(`unknown arm ${a} (have: random, refineAudit)`)
379
- }
380
- // The analyst is an OFF-BOX router call (host-side), so it needs the router key
381
- // even when the worker runs on its own auth.
382
- const analystModel = process.env.ANALYST_MODEL ?? 'deepseek-v4-pro'
383
- const needsRouterKey = backend === 'sandbox' || model.startsWith('openai/') || armNames.includes('refineAudit')
384
- const routerKey = needsRouterKey ? must('TANGLE_API_KEY') : (process.env.TANGLE_API_KEY ?? '')
385
- const sandboxBaseUrl = process.env.SANDBOX_BASE_URL ?? 'https://sandbox.tangle.tools'
386
- // openai-compat = generic passthrough so cheap router models resolve in-box;
387
- // `openai` rejects non-registered model names. Override via WORKER_PROVIDER.
388
- const provider = process.env.WORKER_PROVIDER ?? 'openai-compat'
389
- const concurrency = Number(process.env.CONCURRENCY ?? 3)
390
- // No tight cap on the agentic rollout — it runs until the agent finishes (the clone→
391
- // implement→pytest-iterate loop genuinely takes a while). 0 = untimed. Only set
392
- // SHOT_TIMEOUT_MS to impose a deliberate ceiling. Sandbox keeps a stream cap (flaky transport).
393
- const timeoutMs = process.env.SHOT_TIMEOUT_MS ? Number(process.env.SHOT_TIMEOUT_MS) : backend === 'local' ? 0 : 900_000
394
- const corpusPath = process.env.CORPUS ?? '/tmp/commit0.jsonl'
395
- if (!Number.isInteger(n) || n < 1) throw new Error(`N must be a positive integer, got ${process.env.N}`)
396
- if (!Number.isInteger(k) || k < 1) throw new Error(`K must be a positive integer, got ${process.env.K}`)
397
-
398
- const adapter = createCommit0Adapter()
399
- console.log(`=== commit0 Layer-1 gate · backend=${backend} · N=${n} K=${k} arms=${armNames.join(',')} model=${model} analyst=${analystModel} rolloutConc=${concurrency} ===`)
400
- await adapter.preflight()
401
- const tasks = await adapter.loadTasks({ limit: n })
402
- console.log(`loaded ${tasks.length} task(s): ${tasks.map((t) => t.id).join(', ')}`)
403
-
404
- // Phase 1 — rollouts, concurrent. sandbox = remote box; local = cli-bridge (opencode
405
- // in a tmpdir, diff read from git). Both fault-isolated → a failure is a NO-DIFF, never a throw.
406
- const cfg: ShotCfg = {
407
- sandboxBaseUrl,
408
- sandboxKey: routerKey,
409
- routerBaseUrl,
410
- routerKey,
411
- model,
412
- provider,
413
- timeoutMs,
414
- bridgeUrl: process.env.CLI_BRIDGE_URL ?? process.env.BRIDGE_URL,
415
- bridgeBearer: process.env.CLI_BRIDGE_BEARER ?? process.env.BRIDGE_BEARER,
416
- }
417
- const runRollout = backend === 'local' ? runShotLocal : runShot
418
- const analyze: AnalystFn = llmAnalyst({ routerBaseUrl, routerKey, model: analystModel })
419
- const logShot = (armName: string, s: Shot) =>
420
- console.log(` rollout ${s.task.id}[${armName}]#${s.attempt}: ${s.ok ? `diff ${s.diff.length}B` : `NO DIFF (${s.detail})`}${s.steer ? ' [steered]' : ''} (${(s.wallMs / 1000) | 0}s)`)
421
-
422
- interface TaggedShot {
423
- arm: string
424
- shot: Shot
425
- }
426
- // A unit is the pool's schedulable atom: one blind shot for the control arm
427
- // (max packing), the WHOLE blind→analyst→steered chain for the steered arm
428
- // (shot i+1 depends on shot i's trace). Units never throw — every failure is a
429
- // recorded NO-DIFF/INFRA shot, so one flaky box cannot abort the pool.
430
- const units: Array<() => Promise<TaggedShot[]>> = []
431
- for (const task of tasks) {
432
- for (const armName of armNames) {
433
- if (armName === 'random') {
434
- for (let attempt = 0; attempt < k; attempt += 1) {
435
- units.push(async () => {
436
- const s = await runRollout(task, attempt, cfg)
437
- logShot(armName, s)
438
- return [{ arm: armName, shot: s }]
439
- })
440
- }
441
- continue
442
- }
443
- units.push(async () => {
444
- const out: TaggedShot[] = []
445
- let prev: Shot | undefined
446
- for (let attempt = 0; attempt < k; attempt += 1) {
447
- let steer: string | undefined
448
- if (prev) {
449
- // Trace-only: the analyst sees the prior shot's diff + stream tail,
450
- // never a judge score (judging is phase 2 — selector≠judge by
451
- // construction). "no change needed" is the policy's informed no-op.
452
- try {
453
- const events = prev.traceEvents?.length ? prev.traceEvents : prev.detail ? [prev.detail] : []
454
- const feedback = (await analyze([{ output: prev.diff.slice(0, ANALYST_DIFF_MAX), events }])).trim()
455
- if (feedback && !/^no change needed/i.test(feedback)) steer = feedback.slice(0, STEER_MAX)
456
- } catch (err) {
457
- // A steered arm whose analyst died is no longer a steered arm —
458
- // record the attempt as INFRA rather than degrading to blind.
459
- const msg = (err instanceof Error ? err.message : String(err)).slice(0, 200)
460
- const s: Shot = { task, attempt, diff: '', ok: false, events: 0, wallMs: 0, detail: `analyst error: ${msg}` }
461
- logShot(armName, s)
462
- out.push({ arm: armName, shot: s })
463
- break
464
- }
465
- }
466
- const s = await runRollout(task, attempt, cfg, steer)
467
- logShot(armName, s)
468
- out.push({ arm: armName, shot: s })
469
- prev = s
470
- }
471
- return out
472
- })
473
- }
474
- }
475
- const where = backend === 'local' ? 'local opencode (cli-bridge)' : `in-box (${PATCH_PATH})`
476
- console.log(`\n▶ phase 1: ${tasks.length * armNames.length * k} rollouts in ${units.length} units (conc=${concurrency}) via ${where}`)
477
- const tagged = (await pool(units, concurrency, (u) => u())).flat()
478
-
479
- // Phase 2 — judging, SEQUENTIAL (Docker-bound; commit0 keys its report dir on
480
- // hash(test_ids), shared across a repo's attempts → concurrent judging of one repo
481
- // races/overwrites report.json). Judged PER (TASK, ARM), writing each RunRecord
482
- // immediately so a mid-run crash keeps completed records. Fail loud: an attempt
483
- // with no diff or a failed judge becomes an INFRA attempt (error recorded, no
484
- // score) and the whole record is infra-excluded — never a silent 0.
485
- console.log(`\n▶ phase 2: judging sequentially per task (official commit0 pytest harness) → ${corpusPath}`)
486
- let scoredRecords = 0
487
- let infraRecords = 0
488
- let infraAttempts = 0
489
- for (const task of tasks) {
490
- let imageTouched = false
491
- for (const armName of armNames) {
492
- const armShots = tagged.filter((t) => t.arm === armName && t.shot.task.id === task.id).map((t) => t.shot)
493
- const attempts: AttemptRecord[] = []
494
- let recordInfra = false
495
- for (let i = 0; i < k; i += 1) {
496
- const s = armShots.find((x) => x.attempt === i)
497
- let sc: { score: number; resolved: boolean } | undefined
498
- let attemptError: string | undefined
499
- if (s?.ok) {
500
- // Local Docker backend: images must pre-exist (src/commit0-prereqs.sh);
501
- // rebuild_image is honored by the Modal backend only, where the first
502
- // judged attempt of a repo force-builds and the rest reuse.
503
- process.env.COMMIT0_REBUILD_IMAGE = imageTouched ? '0' : '1'
504
- imageTouched = true
505
- try {
506
- const v = await adapter.judge(s.task, s.diff)
507
- sc = { score: v.score, resolved: v.resolved }
508
- console.log(` judge ${task.id}[${armName}]#${i}: score=${(v.score * 100).toFixed(1)}% resolved=${v.resolved}`)
509
- } catch (err) {
510
- attemptError = `judge harness failed: ${(err instanceof Error ? err.message : String(err)).slice(0, 300)}`
511
- console.log(` judge ${task.id}[${armName}]#${i}: INFRA ${attemptError.slice(0, 200)}`)
512
- }
513
- } else {
514
- attemptError = s ? `no diff: ${s.detail ?? 'unknown'}` : 'missing shot'
515
- console.log(` judge ${task.id}[${armName}]#${i}: INFRA (${attemptError.slice(0, 160)})`)
516
- }
517
- if (attemptError) {
518
- recordInfra = true
519
- infraAttempts += 1
520
- }
521
- attempts.push({
522
- round: i,
523
- prompt: s?.steer ? `commit0-rollout + steer:\n${s.steer}` : 'commit0-rollout',
524
- output: s?.diff ?? '',
525
- ...(sc ? { valid: sc.resolved, score: sc.score } : {}),
526
- ...(attemptError ? { error: attemptError } : {}),
527
- wallMs: s?.wallMs ?? 0,
528
- eventCount: s?.events ?? 0,
529
- eventTypes: { 'sandbox.stream': s?.events ?? 0 },
530
- traceTail: (s?.diff ?? '').slice(-600),
531
- })
532
- }
533
- if (recordInfra) infraRecords += 1
534
- else if (attempts.some((a) => a.score !== undefined)) scoredRecords += 1
535
- const record = buildRunRecordFromAttempts(attempts, {
536
- benchmark: adapter.name,
537
- instanceId: task.id,
538
- condition: `${armName}@${k}`,
539
- model,
540
- infraError: recordInfra,
541
- runtimeEvents: armShots.flatMap((x) => x.runtimeEvents ?? []),
542
- runtimeDecisionPoints: armShots.flatMap((x) => x.runtimeDecisionPoints ?? []),
543
- })
544
- await appendRunRecord(corpusPath, record) // incremental: partial progress survives a crash
545
- }
546
- }
547
-
548
- console.log(
549
- `\n=== wrote ${tasks.length * armNames.length} record(s) (${scoredRecords} fully scored, ${infraRecords} infra-excluded; ${infraAttempts} infra attempts) → ${corpusPath} ===\n` +
550
- ` STEERING VERDICT: tsx src/corpus-report.mts ${corpusPath}\n` +
551
- ` SELECTOR GATE: tsx src/corpus-replay.mts ${corpusPath} --selector=verifier`,
552
- )
553
- }
554
-
555
- main().catch((err) => {
556
- console.error(`commit0-gate: ${err instanceof Error ? err.message : String(err)}`)
557
- process.exit(1)
558
- })