@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,1561 +0,0 @@
1
- /**
2
- * DAY 1 of the STREAM LOOP — the running two-arm stream over SWE-bench Verified
3
- * (contract: supervisor-lab/docs/design/stream-loop.md; base: swe-structural.mts @ 393ee50b).
4
- *
5
- * Two arms, interleaved per instance (same slot, F then L):
6
- * F (frozen-v0) — the swe-structural system config exactly: canary at open, Stage-0 repro reuse
7
- * (REPRO_MANIFEST) re-verified on this substrate — else authored fresh with the
8
- * calibrator's protocol — k=4 candidates, repro-argmax selection, ≤2 guarded
9
- * repairs. No memory.
10
- * L (learning) — byte-identical config PLUS (a) memory recall at open: searchKnowledge over a
11
- * stream-local store (starts EMPTY) with repo+issue tokens, top-3 provenance-
12
- * labeled notes injected via the promptAppendix seam; (b) after settle: a
13
- * templated outcome-anchored note (fields from the Row only — NEVER judge text,
14
- * NEVER FAIL_TO_PASS names) written via applyKnowledgeWriteBlocks; (c) a
15
- * failure-class tally persisted in the ledger.
16
- *
17
- * Phase separation per instance: both arms' decisions LOCK, then the official judge
18
- * (adapter.judge, serialized) grades that instance for both arms; judge outputs never reach any
19
- * model context (the L note carries the resolved BOOLEAN only — a tier-2 anchor).
20
- *
21
- * HARD DRIVER REQUIREMENTS (each traces to a measured failure):
22
- * 1. Per-instance wall-clock deadline (DEADLINE_MS, default 30min — Stage-1 hung 29h on one
23
- * instance): a promise race around the per-instance arm pipeline; breach → error rows with
24
- * partial receipts → next instance. The deadline reaches into the zai retry ladder
25
- * (zaiChatRaw deadlineAt) so a written-off instance stops spending within one call.
26
- * The judge runs OUTSIDE this race (first-judge env-image builds legitimately exceed 30min)
27
- * under its own JUDGE_TIMEOUT_MS race, so no instance holds the stream either way.
28
- * 2. Per-candidate turn cap (TURN_CAP, default 12 — Stage-1 spent 160 calls / 8.7M input tokens
29
- * on ONE instance): enforced at the transport chokepoint; on breach the loop is ended with a
30
- * synthetic no-tool-call completion and the candidate is scored AS-IS from whatever diff
31
- * exists (capBreached in receipts).
32
- * 3. zai discipline: conc ≤2 TOTAL (instance workers are the only callers; attempts are serial
33
- * within an instance), 429 ladder 60/120/240s, client timeout 480s (swe-jail's zaiChatRaw).
34
- * 4. Image pull→run→delete rotation: the fail-closed resolveImageForMetadata never pulls — this
35
- * driver pulls explicitly, hard-asserts presence, and deletes after both arms + judge finish,
36
- * EXCEPT images already cached at stream start (the keep-set). SWEBENCH_CACHE_LEVEL=instance
37
- * stops the judge from deleting images behind the rotation's back.
38
- *
39
- * Ledger: STREAM_DIR/ledger.jsonl — one row per (instance × arm): streamIndex, arm,
40
- * profileVersion, all swe-structural receipts, recall/write receipts, tally snapshot, cumulative
41
- * resolved counts + $ per arm. events.jsonl records stream events incl. the day-1 STUB batch
42
- * trigger: streamIndex % 25 === 0 → 'batch-look (stub)'. The divergence curve is a pure fold over
43
- * the ledger, printed at the end.
44
- *
45
- * cd ~/company/devops/secrets && dotenvx run -f agent-state.env -- bash -c \
46
- * 'cd ~/code/agent-runtime-swe && REPRO_MANIFEST=/path/manifest.json \
47
- * STREAM_DIR=~/.swe-stream/day1 bench/node_modules/.bin/tsx bench/src/swe-stream.mts'
48
- *
49
- * Env: ZAI_API_KEY (required), ZAI_BASE, WORKER_MODEL=glm-4.5-air (both arms, all solve+repair
50
- * calls), SUPERVISOR_MODEL=glm-5.2 (arm L repair advice ONLY — the stronger model),
51
- * REPRO_MODEL=glm-5.2 (shared repro instrument — strong author, default = SUPERVISOR_MODEL),
52
- * REASONING_EFFORT=enabled (SYMMETRIC thinking budget on the worker; 'off' disables),
53
- * SUPERVISOR_MAX_TOKENS=12000, MAX_TOKENS=12000, K=4, REPAIRS=2,
54
- * TEMP=0.8, INNER_TURNS=40, TURN_CAP=12, DEADLINE_MS=1800000, JUDGE_TIMEOUT_MS=2400000,
55
- * CONC=2 (hard max 2 — zai discipline), REPRO_TIMEOUT=120 (s), LLM_TIMEOUT_MS=480000,
56
- * SEED=0x5eed, IDS=comma-list (default: the 23-instance Stage-0 fingerprint set),
57
- * STREAM_N=max instances this run, STREAM_DIR=state dir (ledger/events/kb),
58
- * REPRO_MANIFEST=Stage-0 valid+sound repro scripts (optional — absent entries author fresh),
59
- * PRICE_IN/PRICE_OUT (USD per Mtok, assumed zai list rate). Resume: by instance id from the
60
- * ledger (an instance re-runs unless BOTH arm rows settled).
61
- */
62
- import { execFile } from 'node:child_process'
63
- import { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
64
- import { homedir } from 'node:os'
65
- import { join } from 'node:path'
66
- import { promisify } from 'node:util'
67
- import { applyKnowledgeWriteBlocks, buildKnowledgeIndex, initKnowledgeBase, searchKnowledge } from '@tangle-network/agent-knowledge'
68
- import type { AgenticSurface, AgenticTask, ArtifactHandle, SurfaceScore } from '@tangle-network/agent-runtime/kernel'
69
- import { defaultAnalystInstruction, refine, runAgentic } from '@tangle-network/agent-runtime/kernel'
70
- import type { BenchTask } from './benchmarks/types'
71
- import { createSweBenchEnvironment, resolveImageForMetadata, SWE_SEED_PROMPT } from './swe-bench-env'
72
- import {
73
- APPLY_SENTINEL,
74
- assertNoHiddenLeak,
75
- cachedInstanceIds,
76
- extractReadRequests,
77
- extractReproScript,
78
- IMPORT_NAME,
79
- importCanaryScript,
80
- reproAuthorSystem,
81
- runPyInJail,
82
- tail,
83
- zaiChatRaw,
84
- } from './swe-jail'
85
- import { withBenchProfile } from './router-turn'
86
-
87
- const exec = promisify(execFile)
88
-
89
- // The judge must not delete instance images behind the rotation's back (its default 'env' cache
90
- // level removes them after every run — measured: it pruned the 23-image fingerprint cache).
91
- process.env.SWEBENCH_CACHE_LEVEL ??= 'instance'
92
-
93
- // ---------- config ----------
94
-
95
- const ZAI_BASE = process.env.ZAI_BASE ?? 'https://api.z.ai/api/coding/paas/v4'
96
- const ZAI_KEY = process.env.ZAI_API_KEY ?? ''
97
- if (!ZAI_KEY) throw new Error('ZAI_API_KEY required (run under dotenvx: agent-state.env)')
98
- // WORKER runs every solve+repair call in BOTH arms — glm-4.5-air: cheap, with SWE headroom.
99
- // SUPERVISOR (Step 2) runs arm L's repair-advice call ONLY — a STRONGER model (glm-5.2). The
100
- // strength GAP over the worker is what recreates the arm-C win; a same-model pair is the arm-B null.
101
- // MODEL kept as a back-compat alias defaulting to the worker (older invocations set MODEL=…).
102
- const WORKER_MODEL = process.env.WORKER_MODEL ?? process.env.MODEL ?? 'glm-4.5-air'
103
- // Both glm-4.5-air and glm-5.2 are reasoning models: hidden reasoning consumes max_tokens, so a
104
- // small budget starves `content`. 12000 leaves ample headroom (probe: worker+thinking = 1905 out).
105
- const MAX_TOKENS = Number(process.env.MAX_TOKENS ?? 12_000)
106
- // Reasoning budget — SYMMETRIC across F and L (injected at the shared worker chokepoint, so both
107
- // arms send byte-identical bodies). The zai coding endpoint HONORS `thinking:{type:'enabled'}` on
108
- // TOOLLESS completions (probe 2026-07-12: glm-4.5-air reasoning 831→1820 tok, +119%) and SILENTLY
109
- // IGNORES `reasoning_effort` (200, zero lift), so this env toggles the thinking shape, not a level.
110
- // CAVEAT (probe): with a `tools` array present the endpoint ignores `thinking` too (289→275 compl_
111
- // tok), so this lever's real effect lands on the TOOLLESS calls — repro authoring + the supervisor
112
- // — not the worker's tool-loop solve/repair turns. Kept on (harmless, 200) and symmetric regardless.
113
- const REASONING_EFFORT = (process.env.REASONING_EFFORT ?? 'enabled').toLowerCase()
114
- const REASONING_ON = ['enabled', 'on', 'thinking', 'true', '1', 'high', 'medium'].includes(REASONING_EFFORT)
115
- const WORKER_REASONING: Record<string, unknown> = REASONING_ON ? { thinking: { type: 'enabled' } } : {}
116
- // The SUPERVISOR (arm L repair advice only): a STRONGER model than the worker. glm-5.2 reasons hard
117
- // at baseline (probe: 733 reasoning tok, and the thinking knob did NOT lift it), so no knob is
118
- // injected — the supervisor runs on its OWN token budget, wholly separate from the worker's, and
119
- // changing SUPERVISOR_MAX_TOKENS never touches the worker's MAX_TOKENS / thinking budget.
120
- const SUPERVISOR_MODEL = process.env.SUPERVISOR_MODEL ?? 'glm-5.2'
121
- const SUPERVISOR_MAX_TOKENS = Number(process.env.SUPERVISOR_MAX_TOKENS ?? 12_000)
122
- // The repro is a SHARED MEASUREMENT INSTRUMENT: it grades both arms' candidates AND defines the
123
- // supervisor-fire predicate (severity===1). Authoring it with the weaker worker leaks worker
124
- // weakness into the instrument (observed: a degraded-unsound matplotlib repro). So fresh authoring
125
- // runs on the STRONG model — default = SUPERVISOR_MODEL (glm-5.2), the same author as the Stage-0
126
- // manifest, so all 23 instances (reused + fresh) share one strong instrument. No thinking knob:
127
- // Stage-0 authored without one, and glm-5.2 reasons at baseline. Worker solving stays glm-4.5-air.
128
- const REPRO_MODEL = process.env.REPRO_MODEL ?? SUPERVISOR_MODEL
129
- const K = Number(process.env.K ?? 4)
130
- const REPAIRS = Number(process.env.REPAIRS ?? 2)
131
- // NOT `TEMP`: Node's os.tmpdir() honors the TEMP env var as the temp DIRECTORY, so setting
132
- // TEMP=0.8 made mkdtemp build a relative path "0.8/swe-repro-…" and every docker -v mount was
133
- // rejected as an invalid volume name. Sampling temperature reads SAMPLE_TEMP (TEMP still accepted
134
- // only if it parses as a number < 2, so a stray TEMP=/some/dir never leaks in as a temperature).
135
- const TEMP = (() => {
136
- const s = process.env.SAMPLE_TEMP ?? (process.env.TEMP && Number(process.env.TEMP) < 2 ? process.env.TEMP : undefined)
137
- return Number(s ?? 0.8)
138
- })()
139
- const INNER_TURNS = Number(process.env.INNER_TURNS ?? 40)
140
- const TURN_CAP = Number(process.env.TURN_CAP ?? 12)
141
- const DEADLINE_MS = Number(process.env.DEADLINE_MS ?? 1_800_000)
142
- const JUDGE_TIMEOUT_MS = Number(process.env.JUDGE_TIMEOUT_MS ?? 2_400_000)
143
- const CONC = Math.max(1, Math.min(2, Number(process.env.CONC ?? 2)))
144
- const REPRO_TIMEOUT_S = Number(process.env.REPRO_TIMEOUT ?? 120)
145
- const LLM_TIMEOUT_MS = Number(process.env.LLM_TIMEOUT_MS ?? 480_000)
146
- const SEED = Number(process.env.SEED ?? 0x5eed)
147
- const STREAM_N = Number(process.env.STREAM_N ?? Number.POSITIVE_INFINITY)
148
- const STREAM_DIR = process.env.STREAM_DIR ?? join(homedir(), '.swe-stream', 'day1')
149
- const LEDGER = join(STREAM_DIR, 'ledger.jsonl')
150
- const EVENTS = join(STREAM_DIR, 'events.jsonl')
151
- const STORE = join(STREAM_DIR, 'kb')
152
- const PROFILE_VERSION = 'v0'
153
- // Cost-table rates, USD per Mtok. ASSUMED (zai coding-plan tokens have no per-call list price).
154
- const PRICE_IN = Number(process.env.PRICE_IN ?? 0.6)
155
- const PRICE_OUT = Number(process.env.PRICE_OUT ?? 2.2)
156
-
157
- /**
158
- * The Stage-0 fingerprint set: the 23 instances whose swebench eval images were cached locally at
159
- * the PREREG-swe-frontier commit (enumerated then via `docker images`, recorded in the Stage-0
160
- * canary sweep). The cache has since been pruned by the judge's old 'env' cache level, so the list
161
- * is pinned HERE as the durable source — day-1 streams these first, re-pulling as needed.
162
- */
163
- const FINGERPRINT_23 = [
164
- 'astropy__astropy-12907', 'astropy__astropy-13033', 'django__django-12419', 'django__django-13406',
165
- 'django__django-14089', 'django__django-14534', 'django__django-16082', 'django__django-16429',
166
- 'matplotlib__matplotlib-23314', 'pallets__flask-5014', 'psf__requests-1142', 'psf__requests-1921',
167
- 'psf__requests-2931', 'pylint-dev__pylint-7080', 'pytest-dev__pytest-6202',
168
- 'scikit-learn__scikit-learn-14053', 'scikit-learn__scikit-learn-14141', 'sphinx-doc__sphinx-8595',
169
- 'sphinx-doc__sphinx-8721', 'sympy__sympy-13757', 'sympy__sympy-22914', 'sympy__sympy-23534',
170
- 'sympy__sympy-23950',
171
- ] as const
172
-
173
- interface ReproManifestEntry {
174
- script: string
175
- source: string
176
- stage0Class: string
177
- }
178
-
179
- const MANIFEST: Record<string, ReproManifestEntry> = (() => {
180
- const p = process.env.REPRO_MANIFEST
181
- if (!p) return {}
182
- return JSON.parse(readFileSync(p, 'utf8')) as Record<string, ReproManifestEntry>
183
- })()
184
-
185
- // ---------- seeded shuffle (mulberry32 — deterministic stream order) ----------
186
-
187
- function seededShuffle<T>(arr: readonly T[], seed: number): T[] {
188
- const a = [...arr]
189
- let s = seed >>> 0
190
- const rnd = (): number => {
191
- s = (s + 0x6d2b79f5) >>> 0
192
- let t = Math.imul(s ^ (s >>> 15), 1 | s)
193
- t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
194
- return ((t ^ (t >>> 14)) >>> 0) / 4294967296
195
- }
196
- for (let i = a.length - 1; i > 0; i -= 1) {
197
- const j = Math.floor(rnd() * (i + 1))
198
- ;[a[i], a[j]] = [a[j] as T, a[i] as T]
199
- }
200
- return a
201
- }
202
-
203
- // ---------- transport: leak guard + turn cap + deadline at the single chokepoint ----------
204
-
205
- interface Counter {
206
- calls: number
207
- httpAttempts: number
208
- tokensIn: number
209
- tokensOut: number
210
- guardedMsgs: number
211
- }
212
-
213
- const newCounter = (): Counter => ({ calls: 0, httpAttempts: 0, tokensIn: 0, tokensOut: 0, guardedMsgs: 0 })
214
-
215
- const addInto = (into: Counter, from: Counter): void => {
216
- into.calls += from.calls
217
- into.httpAttempts += from.httpAttempts
218
- into.tokensIn += from.tokensIn
219
- into.tokensOut += from.tokensOut
220
- into.guardedMsgs += from.guardedMsgs
221
- }
222
-
223
- /** Distinctive content marks for the leak guard: the first substantive ADDED line of the gold patch
224
- * and of the hidden test patch. Never shown to any model; used only to refuse outbound messages. */
225
- function leakMarks(md: Record<string, string>): string[] {
226
- const marks: string[] = []
227
- for (const src of [md.patch, md.test_patch]) {
228
- const m = String(src ?? '')
229
- .split('\n')
230
- .find((l) => l.startsWith('+') && !l.startsWith('+++') && l.trim().length > 12)
231
- ?.slice(0, 80)
232
- if (m) marks.push(m)
233
- }
234
- return marks
235
- }
236
-
237
- /** FAIL_TO_PASS test node ids for an instance — the hidden-grading vocabulary the L arm's memory
238
- * must never carry forward. Full pytest node ids (file::class::test) are distinctive enough to
239
- * serve as leak-guard marks without false positives. */
240
- function failToPassNames(md: Record<string, unknown>): string[] {
241
- const raw = md.FAIL_TO_PASS
242
- try {
243
- const list = Array.isArray(raw) ? raw : (JSON.parse(String(raw ?? '[]')) as unknown[])
244
- return list.map((x) => String(x)).filter((s) => s.length >= 8)
245
- } catch {
246
- return []
247
- }
248
- }
249
-
250
- /** Per-attempt enforcement state threaded into the transport. */
251
- interface AttemptGuard {
252
- deadlineAt: number
253
- turnCap: number
254
- capBreached: boolean
255
- }
256
-
257
- /** Synthetic no-tool-call completion: ends the tool loop cleanly on a turn-cap breach so the
258
- * candidate is scored AS-IS from whatever diff exists (requirement 2). Zero usage — no real call. */
259
- const CAP_COMPLETION = {
260
- choices: [{ message: { role: 'assistant', content: 'TURN CAP REACHED — finalize with the current state.' }, finish_reason: 'stop' }],
261
- usage: { prompt_tokens: 0, completion_tokens: 0 },
262
- }
263
-
264
- /** Every model call flows through here (runAgentic's `complete` seam): judge separation asserted,
265
- * turn cap + per-instance deadline enforced, usage counted — once, at the single chokepoint. */
266
- const makeTransport =
267
- (marks: readonly string[], counter: Counter, guard: AttemptGuard) =>
268
- async (body: Record<string, unknown>): Promise<unknown> => {
269
- if (Date.now() >= guard.deadlineAt) throw new Error('DEADLINE: per-instance wall clock exhausted')
270
- if (counter.calls >= guard.turnCap) {
271
- guard.capBreached = true
272
- return CAP_COMPLETION
273
- }
274
- const msgs = (body.messages ?? []) as Array<{ role?: string; content?: unknown }>
275
- counter.guardedMsgs += assertNoHiddenLeak(marks, msgs)
276
- // Inject the honored reasoning-budget knob (thinking) here at the single shared worker
277
- // chokepoint: makeTransport is byte-identical across arms F and L, so the budget is symmetric.
278
- const model = String(body.model ?? '')
279
- const systemPrompt = msgs.find((message) => message.role === 'system')?.content
280
- const toolNames = Array.isArray(body.tools)
281
- ? (body.tools as Array<{ function?: { name?: unknown } }>).flatMap((tool) =>
282
- typeof tool.function?.name === 'string' ? [tool.function.name] : [],
283
- )
284
- : []
285
- const { json, attempts } = await zaiChatRaw(
286
- { base: ZAI_BASE, key: ZAI_KEY, timeoutMs: LLM_TIMEOUT_MS, deadlineAt: guard.deadlineAt },
287
- { ...body, ...WORKER_REASONING },
288
- {
289
- name: 'swe-stream-worker',
290
- harness: 'cli-base',
291
- model: {
292
- provider: 'zai',
293
- default: model,
294
- reasoningEffort: REASONING_ON ? 'high' : 'none',
295
- },
296
- ...(typeof systemPrompt === 'string' ? { prompt: { systemPrompt } } : {}),
297
- ...(toolNames.length > 0
298
- ? { tools: Object.fromEntries(toolNames.map((name) => [name, true])) }
299
- : {}),
300
- },
301
- )
302
- counter.calls += 1
303
- counter.httpAttempts += attempts
304
- const u = (json as { usage?: { prompt_tokens?: number; completion_tokens?: number } }).usage
305
- counter.tokensIn += u?.prompt_tokens ?? 0
306
- counter.tokensOut += u?.completion_tokens ?? 0
307
- return json
308
- }
309
-
310
- // ---------- one emit-patch attempt (swe-structural's protocol + cap/deadline receipts) ----------
311
-
312
- interface AttemptOut {
313
- diff: string
314
- completions: number
315
- tokensIn: number
316
- tokensOut: number
317
- calls: number
318
- wallMs: number
319
- capBreached: boolean
320
- error?: string
321
- }
322
-
323
- async function emitAttempt(
324
- environment: AgenticSurface,
325
- bt: BenchTask,
326
- cfg: {
327
- temperature: number
328
- marks: readonly string[]
329
- instanceCounter: Counter
330
- deadlineAt: number
331
- preApply?: string
332
- promptAppendix?: string
333
- },
334
- ): Promise<AttemptOut> {
335
- const t0 = Date.now()
336
- const counter = newCounter()
337
- const guard: AttemptGuard = { deadlineAt: cfg.deadlineAt, turnCap: TURN_CAP, capBreached: false }
338
- // Capture the patch from inside score() (called during the refine loop, BEFORE the surface closes
339
- // and rms the checkout). Keep the LATEST non-empty diff — the emit-patch pattern.
340
- const capture = { patch: '' }
341
- const proxy: AgenticSurface = {
342
- ...environment,
343
- async open(t: AgenticTask): Promise<ArtifactHandle> {
344
- const h = await environment.open(t)
345
- const pre = cfg.preApply
346
- if (pre?.trim()) {
347
- const f = join(h.id, '.swe-preapply.diff')
348
- writeFileSync(f, pre.endsWith('\n') ? pre : `${pre}\n`)
349
- try {
350
- await exec('git', ['-C', h.id, 'apply', '--whitespace=nowarn', f], { timeout: 60_000 })
351
- } finally {
352
- rmSync(f, { force: true })
353
- }
354
- }
355
- return h
356
- },
357
- async score(_t: AgenticTask, handle: ArtifactHandle): Promise<SurfaceScore> {
358
- try {
359
- const d = await exec('git', ['-C', handle.id, 'diff'], { maxBuffer: 40_000_000, timeout: 60_000 })
360
- if (d.stdout.trim()) capture.patch = d.stdout
361
- } catch {
362
- /* workspace gone or git error → keep whatever we already captured */
363
- }
364
- return { passes: capture.patch.trim() ? 1 : 0, total: 1, errored: 0 }
365
- },
366
- }
367
- const task: AgenticTask = {
368
- id: bt.id,
369
- userPrompt: cfg.promptAppendix ? `${bt.prompt}\n\n${cfg.promptAppendix}` : bt.prompt,
370
- meta: { instanceId: bt.id },
371
- }
372
- const workerProfile = withBenchProfile(
373
- {
374
- name: 'swe-stream-worker',
375
- harness: 'cli-base',
376
- model: {
377
- provider: 'zai',
378
- default: WORKER_MODEL,
379
- reasoningEffort: REASONING_ON ? 'high' : 'none',
380
- },
381
- tools: { list_files: true, read_file: true, edit_file: true },
382
- },
383
- {
384
- systemPrompt: SWE_SEED_PROMPT,
385
- maxTokens: MAX_TOKENS,
386
- maxTurns: INNER_TURNS,
387
- temperature: cfg.temperature,
388
- extraBody: WORKER_REASONING,
389
- },
390
- )
391
- const analystProfile = withBenchProfile(
392
- {
393
- name: 'swe-stream-analyst',
394
- harness: 'cli-base',
395
- model: {
396
- provider: 'zai',
397
- default: WORKER_MODEL,
398
- reasoningEffort: REASONING_ON ? 'high' : 'none',
399
- },
400
- },
401
- {
402
- systemPrompt: defaultAnalystInstruction,
403
- maxTokens: MAX_TOKENS,
404
- extraBody: WORKER_REASONING,
405
- },
406
- )
407
- let error: string | undefined
408
- try {
409
- const r = await runAgentic({
410
- surface: proxy,
411
- task,
412
- strategy: refine,
413
- routerBaseUrl: 'zai-direct', // unused: the `complete` transport short-circuits the router
414
- routerKey: 'zai-direct',
415
- workerProfile,
416
- analystProfile,
417
- budget: 1,
418
- complete: makeTransport(cfg.marks, counter, guard),
419
- })
420
- addInto(cfg.instanceCounter, counter)
421
- return {
422
- diff: capture.patch, completions: r.completions, tokensIn: counter.tokensIn,
423
- tokensOut: counter.tokensOut, calls: counter.calls, wallMs: Date.now() - t0,
424
- capBreached: guard.capBreached,
425
- }
426
- } catch (e) {
427
- error = e instanceof Error ? e.message.slice(0, 300) : String(e).slice(0, 300)
428
- addInto(cfg.instanceCounter, counter)
429
- return {
430
- diff: capture.patch, completions: 0, tokensIn: counter.tokensIn, tokensOut: counter.tokensOut,
431
- calls: counter.calls, wallMs: Date.now() - t0, capBreached: guard.capBreached, error,
432
- }
433
- }
434
- }
435
-
436
- // ---------- in-image candidate scoring (swe-structural verbatim) ----------
437
-
438
- interface CandScore {
439
- applyOk: boolean | null
440
- exit: number | null
441
- timedOut: boolean
442
- severity: number
443
- out: string
444
- }
445
-
446
- const EMPTY_SCORE: CandScore = { applyOk: null, exit: null, timedOut: false, severity: 4, out: '' }
447
- const UNSCORED: CandScore = { applyOk: null, exit: null, timedOut: false, severity: 1, out: '(no repro signal)' }
448
-
449
- async function scoreCandidate(imageTag: string, repro: string | null, diff: string): Promise<CandScore> {
450
- if (!diff.trim()) return EMPTY_SCORE
451
- if (!repro) return UNSCORED
452
- const r = await runPyInJail(imageTag, null, repro, diff, { timeoutS: REPRO_TIMEOUT_S })
453
- if (r.infraError) throw new Error(r.infraError)
454
- const applyOk = r.out.includes(APPLY_SENTINEL)
455
- if (!applyOk) return { applyOk, exit: r.code, timedOut: r.timedOut, severity: 3, out: tail(r.out, 800) }
456
- if (r.timedOut) return { applyOk, exit: r.code, timedOut: true, severity: 2, out: tail(r.out, 800) }
457
- return { applyOk, exit: r.code, timedOut: false, severity: r.code === 0 ? 0 : 1, out: tail(r.out, 1_500) }
458
- }
459
-
460
- // ---------- rows ----------
461
-
462
- interface CandidateRow {
463
- idx: number
464
- diff: string
465
- diffBytes: number
466
- completions: number
467
- calls: number
468
- tokensIn: number
469
- tokensOut: number
470
- wallMs: number
471
- capBreached: boolean
472
- attemptError: string | null
473
- applyOk: boolean | null
474
- reproExit: number | null
475
- reproTimedOut: boolean
476
- severity: number
477
- reproOutTail: string
478
- }
479
-
480
- interface RepairRow {
481
- round: number
482
- baseFrom: string
483
- baseSeverity: number
484
- diff: string
485
- diffBytes: number
486
- completions: number
487
- calls: number
488
- tokensIn: number
489
- tokensOut: number
490
- wallMs: number
491
- capBreached: boolean
492
- attemptError: string | null
493
- applyOk: boolean | null
494
- reproExit: number | null
495
- severity: number
496
- accepted: boolean
497
- }
498
-
499
- interface RecallReceipt {
500
- query: string
501
- storePages: number
502
- hits: Array<{ path: string; rrfScore: number; streamIndex: number | null }>
503
- injectedChars: number
504
- }
505
-
506
- interface WriteReceipt {
507
- path: string
508
- bytes: number
509
- lintMarksChecked: number
510
- written: boolean
511
- error: string | null
512
- }
513
-
514
- /** Supervisor-steered-repair receipt (arm L only; null on F). `fired` is the VERIFIED-failure gate:
515
- * true iff the selected candidate's diff APPLIED and the gold-verified repro still reports the bug
516
- * (severity===1). `reason` records the gate decision either way. The evidence is built from
517
- * execution-verified / model-visible inputs ONLY (issue, the candidate diff, the repro-output tail)
518
- * — never FAIL_TO_PASS, never gold, never any worker self-report. */
519
- interface SupervisorPlanReceipt {
520
- fired: boolean
521
- reason: string
522
- model: string
523
- groundedOnReproTail: boolean
524
- evidenceChars: number
525
- planRaw: string
526
- plan: string
527
- leaked: boolean
528
- planCalls: number
529
- planAttempts: number
530
- planTokensIn: number
531
- planTokensOut: number
532
- }
533
-
534
- interface Row {
535
- streamIndex: number
536
- arm: 'F' | 'L'
537
- profileVersion: string
538
- instanceId: string
539
- repo: string
540
- model: string
541
- image: string | null
542
- imagePulled: boolean
543
- imagePullMs: number
544
- execMode: 'image'
545
- temperature: number
546
- innerTurns: number
547
- turnCap: number
548
- deadlineMs: number
549
- maxTokens: number
550
- reasoningEffort: string
551
- k: number
552
- issueTitle: string
553
- // canary + repro provenance (shared per instance, recorded on both arms)
554
- canaryExit: number | null
555
- canaryPass: boolean | null
556
- reproSource: string
557
- reproStatus: string
558
- reproScript: string | null
559
- reproPreExit: number | null
560
- reproGoldExit: number | null
561
- reproAuthorCalls: number
562
- reproAuthorTokensIn: number
563
- reproAuthorTokensOut: number
564
- // candidates + selection + repair receipts
565
- candidates: CandidateRow[]
566
- selection: { mode: string; selectedIdx: number; movedOffFirst: boolean } | null
567
- repairs: RepairRow[]
568
- repairStop: string | null
569
- finalFrom: string
570
- finalDiff: string
571
- capBreaches: number
572
- deadlineHit: boolean
573
- // memory receipts (L arm only; null on F)
574
- recall: RecallReceipt | null
575
- noteWrite: WriteReceipt | null
576
- // supervisor-steered repair (L arm only; null on F)
577
- supervisorPlan: SupervisorPlanReceipt | null
578
- failureClass: string | null
579
- tallySnapshot: Record<string, number> | null
580
- marksDroppedDatasetText: number
581
- // hidden judge (per-instance phase B; locked-after-decisions)
582
- hiddenResolved: boolean | null
583
- judgeDetail: string | null
584
- judgeMs: number | null
585
- judgeSkipped: string | null
586
- // cost + guard receipts
587
- llmCalls: number
588
- httpAttempts: number
589
- tokensIn: number
590
- tokensOut: number
591
- guardedMsgs: number
592
- usd: number
593
- wallMs: number
594
- // cumulative (this arm, at append time — completion order; the curve refolds in stream order)
595
- cumN: number
596
- cumResolved: number
597
- cumUsd: number
598
- error?: string
599
- }
600
-
601
- function newRow(streamIndex: number, arm: 'F' | 'L', bt: BenchTask): Row {
602
- const md = bt.metadata as Record<string, string>
603
- const issueTitle = String(md.problem_statement ?? '').split('\n').map((l) => l.trim()).find(Boolean) ?? ''
604
- return {
605
- streamIndex, arm, profileVersion: PROFILE_VERSION, instanceId: bt.id, repo: md.repo, model: WORKER_MODEL,
606
- image: null, imagePulled: false, imagePullMs: 0, execMode: 'image', temperature: TEMP,
607
- innerTurns: INNER_TURNS, turnCap: TURN_CAP, deadlineMs: DEADLINE_MS,
608
- maxTokens: MAX_TOKENS, reasoningEffort: REASONING_EFFORT, k: K,
609
- issueTitle: issueTitle.slice(0, 200),
610
- canaryExit: null, canaryPass: null, reproSource: 'none', reproStatus: 'none', reproScript: null,
611
- reproPreExit: null, reproGoldExit: null, reproAuthorCalls: 0, reproAuthorTokensIn: 0,
612
- reproAuthorTokensOut: 0, candidates: [], selection: null, repairs: [], repairStop: null,
613
- finalFrom: 'none', finalDiff: '', capBreaches: 0, deadlineHit: false, recall: null,
614
- noteWrite: null, supervisorPlan: null, failureClass: null, tallySnapshot: null, marksDroppedDatasetText: 0,
615
- hiddenResolved: null, judgeDetail: null, judgeMs: null, judgeSkipped: null,
616
- llmCalls: 0, httpAttempts: 0, tokensIn: 0, tokensOut: 0, guardedMsgs: 0, usd: 0, wallMs: 0,
617
- cumN: 0, cumResolved: 0, cumUsd: 0,
618
- }
619
- }
620
-
621
- const usdOf = (tokensIn: number, tokensOut: number): number =>
622
- (tokensIn / 1e6) * PRICE_IN + (tokensOut / 1e6) * PRICE_OUT
623
-
624
- // ---------- repro acquisition (manifest reuse re-verified — swe-structural verbatim — else fresh
625
- // authoring with the calibrator's protocol; ONCE per instance, shared by both arms so the pairing
626
- // stays tight; authoring usd is split 50/50 into each arm's cost track) ----------
627
-
628
- interface ReproOut {
629
- script: string | null
630
- source: string
631
- status: string
632
- preExit: number | null
633
- goldExit: number | null
634
- authorCalls: number
635
- authorTokensIn: number
636
- authorTokensOut: number
637
- }
638
-
639
- async function acquireRepro(
640
- env: Env,
641
- bt: BenchTask,
642
- imageTag: string,
643
- marks: readonly string[],
644
- deadlineAt: number,
645
- ): Promise<ReproOut> {
646
- const md = bt.metadata as Record<string, string>
647
- const gold = String(md.patch ?? '')
648
- const out: ReproOut = {
649
- script: null, source: 'none', status: 'none', preExit: null, goldExit: null,
650
- authorCalls: 0, authorTokensIn: 0, authorTokensOut: 0,
651
- }
652
-
653
- const verify = async (script: string): Promise<'ok' | 'degraded-timeout' | 'degraded-invalid' | 'degraded-unsound'> => {
654
- const pre = await runPyInJail(imageTag, null, script, undefined, { timeoutS: REPRO_TIMEOUT_S })
655
- if (pre.infraError) throw new Error(pre.infraError)
656
- out.preExit = pre.code
657
- if (pre.timedOut) return 'degraded-timeout'
658
- if (pre.code === 0) return 'degraded-invalid'
659
- const post = await runPyInJail(imageTag, null, script, gold, { timeoutS: REPRO_TIMEOUT_S })
660
- if (post.infraError) throw new Error(post.infraError)
661
- out.goldExit = post.code
662
- return post.code === 0 && post.out.includes(APPLY_SENTINEL) ? 'ok' : 'degraded-unsound'
663
- }
664
-
665
- const manifest = MANIFEST[bt.id]
666
- if (manifest) {
667
- out.source = manifest.source
668
- out.status = await verify(manifest.script)
669
- if (out.status === 'ok') out.script = manifest.script
670
- return out
671
- }
672
-
673
- // Fresh authoring — the calibrator's protocol (issue + listing, one optional read round, one
674
- // validity retry), guarded by the same marks and the instance deadline. Model-visible inputs
675
- // only; gold is used strictly script-side in verify().
676
- out.source = 'stream-authored'
677
- const handle = await env.environment.open({ id: bt.id, systemPrompt: '', userPrompt: '', meta: {} } as AgenticTask)
678
- try {
679
- const listing = String(await env.environment.call(handle, 'list_files', { dir: '' })).slice(0, 5_000)
680
- const issue = String(md.problem_statement ?? '').slice(0, 20_000)
681
- const messages: Array<{ role: 'system' | 'user' | 'assistant'; content: string }> = [
682
- { role: 'system', content: reproAuthorSystem(REPRO_TIMEOUT_S) },
683
- {
684
- role: 'user',
685
- content:
686
- `Repository: ${md.repo} (checked out at the commit where the bug is PRESENT).\n\n` +
687
- `Repository file listing (top levels):\n${listing}\n\n--- Issue ---\n${issue}\n\n--- Instructions ---\n` +
688
- 'If you need to see specific source files before writing the script, reply with ONLY read requests, ' +
689
- 'one per line, at most 3, in the form:\nREAD: path/relative/to/repo/root\n' +
690
- 'Otherwise reply now with the final script in a single ```python fenced block.',
691
- },
692
- ]
693
- const guardedComplete = async (): Promise<string> => {
694
- if (Date.now() >= deadlineAt) throw new Error('DEADLINE: repro authoring abandoned')
695
- assertNoHiddenLeak(marks, messages)
696
- const { json } = await zaiChatRaw(
697
- { base: ZAI_BASE, key: ZAI_KEY, timeoutMs: LLM_TIMEOUT_MS, deadlineAt },
698
- { model: REPRO_MODEL, max_tokens: MAX_TOKENS, temperature: 0.2, messages },
699
- {
700
- name: 'swe-reproduction-author',
701
- model: { provider: 'zai', default: REPRO_MODEL, reasoningEffort: 'high' },
702
- prompt: { systemPrompt: reproAuthorSystem(REPRO_TIMEOUT_S) },
703
- },
704
- )
705
- const d = json as { choices?: Array<{ message?: { content?: string } }>; usage?: { prompt_tokens?: number; completion_tokens?: number } }
706
- out.authorCalls += 1
707
- out.authorTokensIn += d.usage?.prompt_tokens ?? 0
708
- out.authorTokensOut += d.usage?.completion_tokens ?? 0
709
- return d.choices?.[0]?.message?.content ?? ''
710
- }
711
-
712
- let resp = await guardedComplete()
713
- let script = extractReproScript(resp)
714
- if (!script) {
715
- const reads = extractReadRequests(resp)
716
- messages.push({ role: 'assistant', content: resp })
717
- if (reads.length) {
718
- const bodies: string[] = []
719
- for (const p of reads) {
720
- const c = String(await env.environment.call(handle, 'read_file', { path: p }))
721
- bodies.push(`----- ${p} -----\n${c.slice(0, 12_000)}${c.length > 12_000 ? '\n…[truncated]' : ''}`)
722
- }
723
- messages.push({ role: 'user', content: `${bodies.join('\n\n')}\n\nNow reply with the final script in a single \`\`\`python fenced block.` })
724
- } else {
725
- messages.push({ role: 'user', content: 'Reply with ONLY the final Python script in a single ```python fenced block.' })
726
- }
727
- resp = await guardedComplete()
728
- script = extractReproScript(resp)
729
- }
730
- if (!script) {
731
- out.status = 'authoring-failed'
732
- return out
733
- }
734
- out.status = await verify(script)
735
- if (out.status === 'degraded-invalid' || out.status === 'degraded-timeout') {
736
- // One retry with feedback, per the Stage-0 protocol.
737
- const pre = await runPyInJail(imageTag, null, script, undefined, { timeoutS: REPRO_TIMEOUT_S })
738
- const feedback = out.status === 'degraded-timeout'
739
- ? `your script timed out after ${REPRO_TIMEOUT_S}s on the known-buggy code. Write a faster, simpler script that still detects the bug.`
740
- : 'your script did not detect the bug on the known-buggy code: it exited 0 on the UNPATCHED repository. ' +
741
- `Its output was:\n${tail(pre.out, 1_500)}\nWrite a corrected script that FAILS (nonzero exit) on the buggy code.`
742
- messages.push({ role: 'assistant', content: `\`\`\`python\n${script}\n\`\`\`` }, { role: 'user', content: feedback })
743
- const retry = await guardedComplete()
744
- const script2 = extractReproScript(retry)
745
- if (script2) {
746
- script = script2
747
- out.status = await verify(script2)
748
- }
749
- }
750
- if (out.status === 'ok') out.script = script
751
- return out
752
- } finally {
753
- await env.environment.close(handle).catch(() => {})
754
- }
755
- }
756
-
757
- // ---------- supervisor-steered repair (arm L): a STRONGER model diagnoses the verified failure and
758
- // hands the worker a no-code plan. Primitives replicated from supervisor-arena.mts (that file runs
759
- // main() on import, so it cannot be imported) — evidence from execution-verified inputs only. ----------
760
-
761
- type RepairFailureKind = 'wrong-fix' | 'apply-failed' | 'empty-diff'
762
-
763
- /** Evidence for the supervisor: the issue, the worker's own candidate diff, and the tail of the
764
- * gold-verified reproduction's output on that diff. Execution-verified / model-visible ONLY — never
765
- * FAIL_TO_PASS, never the gold patch, never any worker self-report. Bounded to maxChars. */
766
- function renderRepairEvidence(
767
- issue: string,
768
- candidateDiff: string,
769
- reproTail: string,
770
- reproExit: number | null,
771
- maxChars: number,
772
- failureKind: RepairFailureKind = 'wrong-fix',
773
- ): string {
774
- const header =
775
- failureKind === 'apply-failed'
776
- ? 'A bug was reported in an open-source Python repository. A programmer wrote a candidate patch, but the ' +
777
- 'patch FAILED TO APPLY to the repository — its diff context/line numbers do not match the current source. ' +
778
- 'The diff must be re-anchored to the real file contents. Only execution-verified evidence is shown.'
779
- : 'A bug was reported in an open-source Python repository. A programmer wrote a candidate patch, but a ' +
780
- 'REPRODUCTION SCRIPT (authored from the issue; verified to fail on the buggy code and pass on a correct ' +
781
- 'fix) STILL FAILS after the patch is applied. Only execution-verified evidence is shown.'
782
- const diffLabel =
783
- failureKind === 'apply-failed'
784
- ? "--- THE PROGRAMMER'S CANDIDATE PATCH (git diff — it did NOT apply; the context lines are stale/mismatched) ---"
785
- : "--- THE PROGRAMMER'S CANDIDATE PATCH (git diff — it applied cleanly but did NOT fix the bug) ---"
786
- const outLabel =
787
- failureKind === 'apply-failed'
788
- ? `--- git apply ERROR (exit ${reproExit ?? 'n/a'}) — which hunks failed and why ---`
789
- : `--- REPRODUCTION OUTPUT after applying the patch (exit ${reproExit ?? 'n/a'}; nonzero = bug still present) ---`
790
- const parts: string[] = [
791
- header,
792
- '',
793
- '--- ISSUE ---',
794
- issue.trim().slice(0, 12_000),
795
- '',
796
- diffLabel,
797
- tail(candidateDiff.trim(), 8_000) || '(empty diff — the attempt produced no change)',
798
- '',
799
- outLabel,
800
- tail(reproTail.trim(), 4_000) || '(no output captured)',
801
- ]
802
- let text = parts.join('\n')
803
- if (text.length > maxChars) text = `${text.slice(0, maxChars)}\n…[evidence truncated at ${maxChars} chars]`
804
- return text
805
- }
806
-
807
- /** The no-code contract (replicated from arena's planContract, adapted to a diff-shaped fix). */
808
- const planContract =
809
- 'Diagnose why the candidate patch failed to make the reproduction pass, then write a concise plan for the ' +
810
- 'programmer: the specific mistake in the current patch, the correct root-cause approach, and edge cases to ' +
811
- 'handle. You may name at most 3 short symbols or expressions. Do NOT write the fix: no fenced code blocks, no ' +
812
- "lines starting with 'def ', and no raw diff/patch hunks. Keep the plan under 400 tokens."
813
-
814
- const supervisorPrompt = (evidence: string): string =>
815
- ["You are a senior engineer reviewing a junior programmer's failed bug-fix attempt.", '', evidence, '', planContract].join('\n')
816
-
817
- /** Enforce the no-code contract: strip fenced blocks, `def ` lines (arena), and unambiguous patch
818
- * headers (SWE hardening — `diff --git`/`@@`/`+++ `/`--- a|b/` never occur in legitimate plan prose,
819
- * so this cannot eat bullets or narrative dashes). `leaked` is a measured signal, not a drop: the
820
- * stripped plan is still used (matching arena — leak RATE is a pre-registered measurement). */
821
- function stripPlanCode(raw: string): { plan: string; leaked: boolean } {
822
- let leaked = false
823
- let s = raw
824
- if (s.includes('```')) {
825
- const stripped = s.replace(/```[a-zA-Z]*[^\n]*\n?[\s\S]*?(?:```|$)/g, '')
826
- if (stripped !== s) leaked = true
827
- s = stripped
828
- }
829
- const lines = s.split('\n')
830
- const kept = lines.filter((l) => !/^\s*def\s/.test(l) && !/^\s*(?:diff --git |@@ |\+\+\+ |--- [ab]\/)/.test(l))
831
- if (kept.length !== lines.length) leaked = true
832
- return { plan: kept.join('\n').trim(), leaked }
833
- }
834
-
835
- /** A held (non-firing) supervisor receipt — the verified-failure gate was NOT met. */
836
- const heldSupervisorReceipt = (reason: string): SupervisorPlanReceipt => ({
837
- fired: false, reason, model: SUPERVISOR_MODEL, groundedOnReproTail: false, evidenceChars: 0,
838
- planRaw: '', plan: '', leaked: false, planCalls: 0, planAttempts: 0, planTokensIn: 0, planTokensOut: 0,
839
- })
840
-
841
- /** Fire ONCE per instance on the verified-failure gate: fetch the stronger model's no-code plan on
842
- * its OWN token budget. `fired` stays true (the gate fired) even if the plan comes back empty / the
843
- * guard trips / the call fails — those are recorded in `reason` and leave `plan` empty so the L
844
- * repair simply proceeds raw (like F). The leak guard HOLDS rather than crashes. */
845
- async function superviseRepair(
846
- bt: BenchTask,
847
- candidateDiff: string,
848
- reproTail: string,
849
- reproExit: number | null,
850
- marks: readonly string[],
851
- deadlineAt: number,
852
- failureKind: RepairFailureKind = 'wrong-fix',
853
- ): Promise<SupervisorPlanReceipt> {
854
- const md = bt.metadata as Record<string, string>
855
- const evidence = renderRepairEvidence(String(md.problem_statement ?? ''), candidateDiff, reproTail, reproExit, 14_000, failureKind)
856
- const messages = [{ role: 'user' as const, content: supervisorPrompt(evidence) }]
857
- const base: SupervisorPlanReceipt = {
858
- fired: true, reason: 'ok', model: SUPERVISOR_MODEL, groundedOnReproTail: true, evidenceChars: evidence.length,
859
- planRaw: '', plan: '', leaked: false, planCalls: 0, planAttempts: 0, planTokensIn: 0, planTokensOut: 0,
860
- }
861
- try {
862
- assertNoHiddenLeak(marks, messages)
863
- } catch {
864
- return { ...base, reason: 'leak-guard-tripped' }
865
- }
866
- if (Date.now() >= deadlineAt) return { ...base, reason: 'deadline' }
867
- try {
868
- const { json, attempts } = await zaiChatRaw(
869
- { base: ZAI_BASE, key: ZAI_KEY, timeoutMs: LLM_TIMEOUT_MS, deadlineAt },
870
- { model: SUPERVISOR_MODEL, max_tokens: SUPERVISOR_MAX_TOKENS, temperature: 0.2, messages },
871
- {
872
- name: 'swe-repair-supervisor',
873
- model: { provider: 'zai', default: SUPERVISOR_MODEL, reasoningEffort: 'high' },
874
- },
875
- )
876
- const d = json as { choices?: Array<{ message?: { content?: string } }>; usage?: { prompt_tokens?: number; completion_tokens?: number } }
877
- const planRaw = d.choices?.[0]?.message?.content ?? ''
878
- const { plan, leaked } = stripPlanCode(planRaw)
879
- return {
880
- ...base, reason: plan.trim() ? 'ok' : 'empty-plan', planRaw, plan, leaked, planCalls: 1, planAttempts: attempts,
881
- planTokensIn: d.usage?.prompt_tokens ?? 0, planTokensOut: d.usage?.completion_tokens ?? 0,
882
- }
883
- } catch (e) {
884
- return { ...base, reason: `supervisor-call-failed: ${(e instanceof Error ? e.message : String(e)).slice(0, 120)}` }
885
- }
886
- }
887
-
888
- // ---------- one arm: k candidates → argmax → guarded repair (swe-structural steps 3-5) ----------
889
-
890
- type Env = Awaited<ReturnType<typeof createSweBenchEnvironment>>
891
-
892
- async function runArm(
893
- env: Env,
894
- bt: BenchTask,
895
- row: Row,
896
- repro: string | null,
897
- marks: readonly string[],
898
- deadlineAt: number,
899
- promptAppendix: string | undefined,
900
- counter: Counter,
901
- supervise: boolean,
902
- ): Promise<void> {
903
- const imageTag = row.image as string
904
- const diffs: string[] = []
905
- for (let i = 0; i < K; i += 1) {
906
- const a = await emitAttempt(env.environment, bt, {
907
- temperature: TEMP, marks, instanceCounter: counter, deadlineAt,
908
- ...(promptAppendix ? { promptAppendix } : {}),
909
- })
910
- diffs.push(a.diff)
911
- if (a.capBreached) row.capBreaches += 1
912
- row.candidates.push({
913
- idx: i, diff: a.diff, diffBytes: a.diff.length, completions: a.completions, calls: a.calls,
914
- tokensIn: a.tokensIn, tokensOut: a.tokensOut, wallMs: a.wallMs, capBreached: a.capBreached,
915
- attemptError: a.error ?? null, applyOk: null, reproExit: null, reproTimedOut: false,
916
- severity: -1, reproOutTail: '',
917
- })
918
- }
919
-
920
- const scores: CandScore[] = []
921
- for (let i = 0; i < K; i += 1) {
922
- const s = await scoreCandidate(imageTag, repro, diffs[i] as string)
923
- scores.push(s)
924
- const cand = row.candidates[i] as CandidateRow
925
- cand.applyOk = s.applyOk
926
- cand.reproExit = s.exit
927
- cand.reproTimedOut = s.timedOut
928
- cand.severity = s.severity
929
- cand.reproOutTail = s.out
930
- }
931
- let selectedIdx: number
932
- let mode: string
933
- if (repro) {
934
- mode = 'repro-argmax'
935
- selectedIdx = 0
936
- for (let i = 1; i < K; i += 1) {
937
- if ((scores[i] as CandScore).severity < (scores[selectedIdx] as CandScore).severity) selectedIdx = i
938
- }
939
- } else {
940
- mode = 'blind-first'
941
- const firstNonEmpty = diffs.findIndex((d) => d.trim().length > 0)
942
- selectedIdx = firstNonEmpty === -1 ? 0 : firstNonEmpty
943
- }
944
- row.selection = { mode, selectedIdx, movedOffFirst: mode === 'repro-argmax' && selectedIdx !== 0 }
945
-
946
- let best = { diff: diffs[selectedIdx] as string, score: scores[selectedIdx] as CandScore, from: `candidate:${selectedIdx}` }
947
- if (!repro) {
948
- row.repairStop = 'no-signal'
949
- if (supervise) row.supervisorPlan = heldSupervisorReceipt('no-repro')
950
- } else if (best.score.severity === 0) {
951
- row.repairStop = 'already-passing'
952
- if (supervise) row.supervisorPlan = heldSupervisorReceipt('already-passing')
953
- } else {
954
- // ── Supervisor gate (arm L only): fire ONCE on a VERIFIED failure — the selected diff APPLIED
955
- // and the gold-verified repro STILL reports the bug (severity===1) — then reuse the stronger
956
- // model's no-code plan across every repair round. Arm F is never supervised (raw failure =
957
- // control); severity 2 (repro timeout) / 3 (apply failed) are HELD, not steered. ──
958
- let supPreamble = ''
959
- if (supervise) {
960
- // Fire on any EXECUTION-VERIFIED failure the supervisor can act on: severity 1 = patch applied
961
- // but the gold-verified repro still reports the bug (wrong fix); severity 3 = patch FAILED TO
962
- // APPLY (git apply objectively rejected it — the weak worker's DOMINANT failure, and stale-diff
963
- // re-anchoring is exactly where a stronger reviewer helps). Both are objective, non-credulous
964
- // signals. Held: severity 0 (already passing), 2 (repro timeout — ambiguous), 4 (empty diff —
965
- // nothing to advise on).
966
- const failureKind =
967
- best.score.severity === 3 ? ('apply-failed' as const) : best.score.severity === 4 ? ('empty-diff' as const) : ('wrong-fix' as const)
968
- // Fire on every OBJECTIVE, execution-verified failure a plan can act on: 1=applied-but-wrong,
969
- // 3=apply-failed (stale diff), 4=empty-diff (worker produced nothing — the case a plan helps
970
- // MOST). Hold only 0 (already passing) and 2 (repro-timeout — ambiguous, not a clean signal).
971
- const gateOk = best.score.severity === 1 || best.score.severity === 3 || best.score.severity === 4
972
- if (!gateOk) {
973
- const reason = best.score.severity === 2 ? 'repro-timeout' : `severity-${best.score.severity}`
974
- row.supervisorPlan = heldSupervisorReceipt(reason)
975
- logEvent('supervisor-held', { streamIndex: row.streamIndex, instanceId: row.instanceId, arm: row.arm, reason })
976
- } else {
977
- const sp = await superviseRepair(bt, best.diff, best.score.out, best.score.exit, marks, deadlineAt, failureKind)
978
- row.supervisorPlan = sp
979
- logEvent('supervisor-fired', {
980
- streamIndex: row.streamIndex, instanceId: row.instanceId, arm: row.arm,
981
- reason: sp.reason, leaked: sp.leaked, planTokensIn: sp.planTokensIn, planTokensOut: sp.planTokensOut,
982
- })
983
- if (sp.plan.trim()) {
984
- supPreamble =
985
- "--- SUPERVISOR DIAGNOSIS (a stronger reviewer's no-code plan for why the fix failed; weigh it " +
986
- 'against the code — it may be wrong) ---\n' +
987
- `${sp.plan}\n--- END SUPERVISOR DIAGNOSIS ---\n\n`
988
- }
989
- }
990
- }
991
- for (let round = 1; round <= REPAIRS && best.score.severity > 0; round += 1) {
992
- if (Date.now() >= deadlineAt) throw new Error('DEADLINE: per-instance wall clock exhausted (repair)')
993
- const appendix =
994
- supPreamble +
995
- (best.diff.trim()
996
- ? `--- PREVIOUS FIX (already applied to this checkout) ---\n${tail(best.diff, 8_000)}\n\n`
997
- : '--- NO FIX APPLIED YET (every prior attempt produced no change) ---\n\n') +
998
- `--- REPRODUCTION SCRIPT (written from the issue; exit 0 = fixed) ---\n${tail(repro, 6_000)}\n\n` +
999
- `--- REPRODUCTION OUTPUT on the current state (exit ${best.score.exit ?? 'n/a'}) ---\n${best.score.out}\n\n` +
1000
- '--- REPAIR INSTRUCTIONS ---\n' +
1001
- 'The reproduction above STILL FAILS. Diagnose why the current state does not resolve the issue, ' +
1002
- 'then correct the SOURCE with minimal edit_file changes (you may revise or revert parts of the ' +
1003
- 'previous fix — it is already in the files). Do not modify tests.'
1004
- const a = await emitAttempt(env.environment, bt, {
1005
- temperature: TEMP, marks, instanceCounter: counter, deadlineAt, preApply: best.diff, promptAppendix: appendix,
1006
- })
1007
- if (a.capBreached) row.capBreaches += 1
1008
- const ns = await scoreCandidate(imageTag, repro, a.diff)
1009
- const accepted = ns.severity < best.score.severity
1010
- row.repairs.push({
1011
- round, baseFrom: best.from, baseSeverity: best.score.severity, diff: a.diff, diffBytes: a.diff.length,
1012
- completions: a.completions, calls: a.calls, tokensIn: a.tokensIn, tokensOut: a.tokensOut,
1013
- wallMs: a.wallMs, capBreached: a.capBreached, attemptError: a.error ?? null, applyOk: ns.applyOk,
1014
- reproExit: ns.exit, severity: ns.severity, accepted,
1015
- })
1016
- if (accepted) best = { diff: a.diff, score: ns, from: `repair:${round}` }
1017
- }
1018
- row.repairStop = best.score.severity === 0 ? 'repaired-pass' : 'rounds-exhausted'
1019
- }
1020
- row.finalDiff = best.diff
1021
- row.finalFrom = best.from
1022
- }
1023
-
1024
- // ---------- memory: recall at open, templated note after settle (L arm only) ----------
1025
-
1026
- async function recallForInstance(bt: BenchTask): Promise<{ appendix?: string; receipt: RecallReceipt }> {
1027
- const md = bt.metadata as Record<string, string>
1028
- const issue = String(md.problem_statement ?? '')
1029
- const title = issue.split('\n').map((l) => l.trim()).find(Boolean) ?? ''
1030
- const query = `${md.repo} ${md.repo.split('/').join(' ')} ${title} ${issue.slice(0, 400)}`
1031
- const index = await buildKnowledgeIndex(STORE)
1032
- const receipt: RecallReceipt = { query: query.slice(0, 300), storePages: index.pages.length, hits: [], injectedChars: 0 }
1033
- if (index.pages.length === 0) return { receipt }
1034
- const hits = searchKnowledge(index, query, 3)
1035
- if (!hits.length) return { receipt }
1036
- const parts: string[] = [
1037
- '--- PRIOR EXPERIENCE (notes recalled from this stream\'s own earlier tasks; provenance-labeled; ' +
1038
- 'they may or may not apply — weigh them against the issue) ---',
1039
- ]
1040
- for (const h of hits) {
1041
- const si = Number((h.page.frontmatter as Record<string, unknown>).streamIndex ?? Number.NaN)
1042
- receipt.hits.push({ path: h.page.path, rrfScore: h.rrfScore, streamIndex: Number.isNaN(si) ? null : si })
1043
- parts.push(`\n[note ${h.rank}] source=${h.page.path} rrf=${h.rrfScore.toFixed(4)}\n${h.page.text.trim().slice(0, 1_200)}`)
1044
- }
1045
- parts.push('--- END PRIOR EXPERIENCE ---')
1046
- const appendix = parts.join('\n')
1047
- receipt.injectedChars = appendix.length
1048
- return { appendix, receipt }
1049
- }
1050
-
1051
- /** Fixed per-class lesson lines — templated (class → string), so the note stays "fields from the
1052
- * Row only": no judge text, no free-form model text, no hidden-test vocabulary. */
1053
- const CLASS_LESSON: Record<string, string> = {
1054
- 'repro-pass-resolved': 'repro-verified fix confirmed by the official grade — the repro was a faithful check here.',
1055
- 'repro-pass-but-unresolved': 'the repro passed but the official grade failed — the reproduction under-covered the hidden requirement; prefer root-cause edits and re-check adjacent behaviors, not just the literal symptom.',
1056
- 'resolved-despite-repro-fail': 'the official grade passed although the repro still failed — the repro was measuring something stricter or adjacent; treat repro failures as advisory, not fatal.',
1057
- 'repro-fail-unresolved': 'no candidate made the repro pass and the official grade failed — candidates likely missed the root cause; explore more files before editing.',
1058
- 'no-repro-resolved': 'resolved with no repro signal (blind-first selection) — the first non-empty candidate was good.',
1059
- 'no-repro-unresolved': 'no repro signal and the official grade failed — without a visible check, selection was blind; invest in a better reproduction next time.',
1060
- error: 'the instance errored before settling — receipts are partial.',
1061
- }
1062
-
1063
- function classifyOutcome(row: Row): string {
1064
- if (row.error) return 'error'
1065
- const reproArmed = row.reproStatus === 'ok'
1066
- const finalPass = row.repairStop === 'already-passing' || row.repairStop === 'repaired-pass'
1067
- if (row.hiddenResolved === true) {
1068
- if (!reproArmed) return 'no-repro-resolved'
1069
- return finalPass ? 'repro-pass-resolved' : 'resolved-despite-repro-fail'
1070
- }
1071
- if (!reproArmed) return 'no-repro-unresolved'
1072
- return finalPass ? 'repro-pass-but-unresolved' : 'repro-fail-unresolved'
1073
- }
1074
-
1075
- /** Files touched by the final diff — the model's OWN output (model-visible by construction). */
1076
- function filesTouched(diff: string): string[] {
1077
- return [...new Set([...diff.matchAll(/^\+\+\+ b\/(\S+)/gm)].map((m) => m[1] as string))].slice(0, 8)
1078
- }
1079
-
1080
- async function writeNote(row: Row, allFtpMarks: readonly string[], instanceMarks: readonly string[]): Promise<WriteReceipt> {
1081
- const cls = row.failureClass ?? 'error'
1082
- const notePath = `knowledge/notes/${String(row.streamIndex).padStart(4, '0')}-${row.instanceId}.md`
1083
- const repoSlug = row.repo.replace('/', '-')
1084
- const sev = row.candidates.map((c) => c.severity).join(',')
1085
- const sel = row.selection ? `${row.selection.mode}@${row.selection.selectedIdx}${row.selection.movedOffFirst ? ' (moved off first)' : ''}` : 'none'
1086
- const body = [
1087
- '---',
1088
- `title: 'stream note: ${row.instanceId}'`,
1089
- `tags: [swe-stream, ${repoSlug}, ${cls}]`,
1090
- `streamIndex: ${row.streamIndex}`,
1091
- `profileVersion: ${row.profileVersion}`,
1092
- '---',
1093
- `# ${row.instanceId} — ${row.repo}`,
1094
- '',
1095
- `- provenance: streamIndex ${row.streamIndex}, arm L, ${row.profileVersion} (this stream's own run receipts)`,
1096
- `- issue: ${row.issueTitle}`,
1097
- `- repro: ${row.reproStatus} (source ${row.reproSource}); candidate severities [${sev}]; selection ${sel}`,
1098
- `- repairs: ${row.repairs.length} round(s), accepted=${row.repairs.some((r) => r.accepted)}, stop=${row.repairStop ?? 'n/a'}`,
1099
- `- final: from ${row.finalFrom}, ${row.finalDiff.length} diff bytes, files: ${filesTouched(row.finalDiff).join(', ') || '(none)'}`,
1100
- `- outcome: resolved=${row.hiddenResolved === true} (official grade, boolean anchor only)`,
1101
- `- failureClass: ${cls}`,
1102
- `- lesson: ${CLASS_LESSON[cls] ?? CLASS_LESSON.error}`,
1103
- ].join('\n')
1104
-
1105
- // LEAK LINT (fails loud): the note must carry NO hidden-grading vocabulary — not this instance's
1106
- // FAIL_TO_PASS names, not any accumulated FTP name from the stream, not gold/test-patch marks,
1107
- // and no judge-report vocabulary. A violation throws: a leaking note is never written.
1108
- const lintMarks = [...new Set([...allFtpMarks, ...instanceMarks])]
1109
- for (const mark of lintMarks) {
1110
- if (mark && body.includes(mark)) {
1111
- throw new Error(`NOTE LINT REFUSED: hidden-grading mark would leak into the memory store (${mark.slice(0, 40)}…)`)
1112
- }
1113
- }
1114
- if (row.judgeDetail && row.judgeDetail.length > 20 && body.includes(row.judgeDetail.slice(0, 60))) {
1115
- throw new Error('NOTE LINT REFUSED: judge text would leak into the memory store')
1116
- }
1117
- const proposal = `--- FILE: ${notePath} ---\n${body}\n--- END FILE ---\n`
1118
- const applied = await applyKnowledgeWriteBlocks(STORE, proposal)
1119
- if (!applied.written.includes(notePath)) {
1120
- throw new Error(`note write failed: ${applied.warnings.join('; ') || 'no block written'}`)
1121
- }
1122
- return { path: notePath, bytes: body.length, lintMarksChecked: lintMarks.length, written: true, error: null }
1123
- }
1124
-
1125
- // ---------- image rotation ----------
1126
-
1127
- async function ensureImage(bt: BenchTask): Promise<{ tag: string; pulled: boolean; pullMs: number }> {
1128
- let r = await resolveImageForMetadata(bt.metadata ?? {})
1129
- if (r.ok) return { tag: r.tag, pulled: false, pullMs: 0 }
1130
- const remote = `swebench/sweb.eval.x86_64.${bt.id.replace('__', '_1776_')}:latest`
1131
- const t0 = Date.now()
1132
- await exec('docker', ['pull', remote], { timeout: 1_500_000, maxBuffer: 8_000_000 })
1133
- r = await resolveImageForMetadata(bt.metadata ?? {})
1134
- // Hard assert (requirement 4): a missing image after an explicit pull is an error row, never
1135
- // silent signal loss.
1136
- if (!r.ok) throw new Error(`image missing after explicit pull of ${remote}: ${r.reason}`)
1137
- return { tag: r.tag, pulled: true, pullMs: Date.now() - t0 }
1138
- }
1139
-
1140
- // ---------- ledger + events ----------
1141
-
1142
- function appendRow(row: Row): void {
1143
- appendFileSync(LEDGER, `${JSON.stringify(row)}\n`)
1144
- }
1145
-
1146
- function logEvent(type: string, data: Record<string, unknown>): void {
1147
- appendFileSync(EVENTS, `${JSON.stringify({ at: new Date().toISOString(), type, ...data })}\n`)
1148
- }
1149
-
1150
- function loadLedger(): Row[] {
1151
- if (!existsSync(LEDGER)) return []
1152
- const rows: Row[] = []
1153
- for (const line of readFileSync(LEDGER, 'utf8').split('\n')) {
1154
- if (!line.trim()) continue
1155
- rows.push(JSON.parse(line) as Row)
1156
- }
1157
- return rows
1158
- }
1159
-
1160
- // ---------- per-instance pipeline ----------
1161
-
1162
- interface StreamState {
1163
- keepImages: Set<string>
1164
- ftpMarks: Set<string>
1165
- tally: Record<string, number>
1166
- cum: { F: { n: number; resolved: number; usd: number }; L: { n: number; resolved: number; usd: number } }
1167
- judgeChain: Promise<void>
1168
- }
1169
-
1170
- /** Serialized official judge with its own timeout race — the chain never blocks past the timeout
1171
- * (a zombie evaluator can linger; max_workers=1 keeps it single). Judge output goes to the ROW
1172
- * only, never near a model message. */
1173
- function serializedJudge(
1174
- state: StreamState,
1175
- env: Env,
1176
- bt: BenchTask,
1177
- diff: string,
1178
- ): Promise<{ resolved: boolean; detail: string | null; skipped: string | null; ms: number }> {
1179
- const run = async (): Promise<{ resolved: boolean; detail: string | null; skipped: string | null; ms: number }> => {
1180
- const t0 = Date.now()
1181
- if (!diff.trim()) return { resolved: false, detail: null, skipped: 'empty-patch', ms: 0 }
1182
- let timer: NodeJS.Timeout | undefined
1183
- try {
1184
- const timeout = new Promise<never>((_, rej) => {
1185
- timer = setTimeout(() => rej(new Error('judge-timeout')), JUDGE_TIMEOUT_MS)
1186
- })
1187
- const s = await Promise.race([env.adapter.judge(bt, diff), timeout])
1188
- return { resolved: s.resolved ?? false, detail: String(s.detail ?? '').slice(0, 1_000), skipped: null, ms: Date.now() - t0 }
1189
- } catch (e) {
1190
- const msg = e instanceof Error ? e.message.slice(0, 200) : String(e).slice(0, 200)
1191
- return { resolved: false, detail: null, skipped: `judge-error: ${msg}`, ms: Date.now() - t0 }
1192
- } finally {
1193
- clearTimeout(timer)
1194
- }
1195
- }
1196
- const p = state.judgeChain.then(run)
1197
- state.judgeChain = p.then(
1198
- () => undefined,
1199
- () => undefined,
1200
- )
1201
- return p
1202
- }
1203
-
1204
- async function processInstance(state: StreamState, env: Env, bt: BenchTask, streamIndex: number): Promise<void> {
1205
- const t0 = Date.now()
1206
- const md = bt.metadata as Record<string, string>
1207
- const rowF = newRow(streamIndex, 'F', bt)
1208
- const rowL = newRow(streamIndex, 'L', bt)
1209
- const deadlineAt = t0 + DEADLINE_MS
1210
- const counterF = newCounter()
1211
- const counterL = newCounter()
1212
-
1213
- // Leak-guard marks: this instance's gold/test marks + EVERY FAIL_TO_PASS name accumulated over
1214
- // the stream so far (the memory channel is the only path that could carry one forward — a trip
1215
- // means the note lint failed and MUST fail loud). Marks that already occur in the dataset's own
1216
- // issue text are dropped (dataset-authored, not memory-authored) and receipted.
1217
- const ftpThis = failToPassNames(bt.metadata ?? {})
1218
- for (const m of ftpThis) state.ftpMarks.add(m)
1219
- const issueText = String(md.problem_statement ?? '')
1220
- const promptText = bt.prompt
1221
- const allMarks = [...leakMarks(md), ...state.ftpMarks]
1222
- const marks = allMarks.filter((m) => !issueText.includes(m) && !promptText.includes(m))
1223
- rowF.marksDroppedDatasetText = rowL.marksDroppedDatasetText = allMarks.length - marks.length
1224
-
1225
- let repro: ReproOut | null = null
1226
- const checkDeadline = (where: string): void => {
1227
- if (Date.now() >= deadlineAt) throw new Error(`DEADLINE: per-instance wall clock exhausted (${where})`)
1228
- }
1229
-
1230
- const pipeline = async (): Promise<void> => {
1231
- // Image: hard-asserted per instance; pulled explicitly when the cache lacks it (requirement 4).
1232
- const img = await ensureImage(bt)
1233
- rowF.image = rowL.image = img.tag
1234
- rowF.imagePulled = rowL.imagePulled = img.pulled
1235
- rowF.imagePullMs = rowL.imagePullMs = img.pullMs
1236
- if (img.pulled) logEvent('image-pulled', { streamIndex, instanceId: bt.id, tag: img.tag, pullMs: img.pullMs })
1237
-
1238
- // Execution canary (zero model calls) — this substrate must be able to grade this instance.
1239
- const pkg = IMPORT_NAME[md.repo]
1240
- if (!pkg) throw new Error(`no IMPORT_NAME for ${md.repo} — canary not expressible`)
1241
- const gold = String(md.patch ?? '')
1242
- if (!gold.trim()) throw new Error('gold patch missing from metadata')
1243
- const c = await runPyInJail(img.tag, null, importCanaryScript(pkg), gold, { timeoutS: REPRO_TIMEOUT_S })
1244
- if (c.infraError) throw new Error(c.infraError)
1245
- rowF.canaryExit = rowL.canaryExit = c.code
1246
- const canaryPass = c.code === 0 && c.out.includes(APPLY_SENTINEL)
1247
- rowF.canaryPass = rowL.canaryPass = canaryPass
1248
- if (!canaryPass) throw new Error(`canary failed (exit ${c.code}): this substrate cannot grade this instance`)
1249
-
1250
- // Repro: manifest reuse re-verified, else authored fresh — ONCE, shared by both arms.
1251
- repro = await acquireRepro(env, bt, img.tag, marks, deadlineAt)
1252
- for (const row of [rowF, rowL]) {
1253
- row.reproSource = repro.source
1254
- row.reproStatus = repro.status
1255
- row.reproScript = repro.script
1256
- row.reproPreExit = repro.preExit
1257
- row.reproGoldExit = repro.goldExit
1258
- row.reproAuthorCalls = repro.authorCalls
1259
- row.reproAuthorTokensIn = repro.authorTokensIn
1260
- row.reproAuthorTokensOut = repro.authorTokensOut
1261
- }
1262
-
1263
- // Arm F (frozen): no memory, no supervisor.
1264
- checkDeadline('before arm F')
1265
- await runArm(env, bt, rowF, repro.script, marks, deadlineAt, undefined, counterF, false)
1266
-
1267
- // Arm L (learning): recall at open via the promptAppendix seam + supervisor-steered repair;
1268
- // worker budget byte-identical to F otherwise.
1269
- checkDeadline('before arm L')
1270
- const recall = await recallForInstance(bt)
1271
- rowL.recall = recall.receipt
1272
- await runArm(env, bt, rowL, repro.script, marks, deadlineAt, recall.appendix, counterL, true)
1273
- }
1274
-
1275
- let deadlineErr: string | null = null
1276
- try {
1277
- let timer: NodeJS.Timeout | undefined
1278
- const breach = new Promise<never>((_, rej) => {
1279
- timer = setTimeout(
1280
- () => rej(new Error(`DEADLINE: instance exceeded ${DEADLINE_MS}ms — error row, stream continues`)),
1281
- DEADLINE_MS,
1282
- )
1283
- })
1284
- try {
1285
- await Promise.race([pipeline(), breach])
1286
- } finally {
1287
- clearTimeout(timer)
1288
- }
1289
- } catch (e) {
1290
- const msg = e instanceof Error ? e.message.slice(0, 400) : String(e).slice(0, 400)
1291
- deadlineErr = msg
1292
- const hit = msg.startsWith('DEADLINE')
1293
- for (const row of [rowF, rowL]) {
1294
- if (!row.error) row.error = msg
1295
- row.deadlineHit = row.deadlineHit || hit
1296
- }
1297
- if (hit) logEvent('deadline-breach', { streamIndex, instanceId: bt.id, afterMs: Date.now() - t0 })
1298
- }
1299
-
1300
- // ── Per-instance phase B: decisions are locked; the official judge grades both arms,
1301
- // serialized. Judge outputs live in rows only — never in any model context. ──
1302
- for (const row of [rowF, rowL]) {
1303
- if (row.error && !row.finalDiff.trim()) {
1304
- row.hiddenResolved = false
1305
- row.judgeSkipped = deadlineErr ? 'error-no-patch' : 'empty-patch'
1306
- continue
1307
- }
1308
- const j = await serializedJudge(state, env, bt, row.finalDiff)
1309
- row.hiddenResolved = j.resolved
1310
- row.judgeDetail = j.detail
1311
- row.judgeMs = j.ms
1312
- row.judgeSkipped = j.skipped
1313
- }
1314
-
1315
- // ── L settle: failure-class tally + templated outcome-anchored note (Row fields only). ──
1316
- rowL.failureClass = classifyOutcome(rowL)
1317
- rowF.failureClass = classifyOutcome(rowF)
1318
- state.tally[rowL.failureClass] = (state.tally[rowL.failureClass] ?? 0) + 1
1319
- rowL.tallySnapshot = { ...state.tally }
1320
- try {
1321
- rowL.noteWrite = await writeNote(rowL, [...state.ftpMarks], leakMarks(md))
1322
- logEvent('note-written', { streamIndex, instanceId: bt.id, path: rowL.noteWrite.path })
1323
- } catch (e) {
1324
- const msg = e instanceof Error ? e.message.slice(0, 300) : String(e).slice(0, 300)
1325
- rowL.noteWrite = { path: '', bytes: 0, lintMarksChecked: 0, written: false, error: msg }
1326
- logEvent('note-lint-violation', { streamIndex, instanceId: bt.id, error: msg })
1327
- }
1328
-
1329
- // ── Finalize receipts + cumulative tracks; append both rows. Authoring usd splits 50/50 so the
1330
- // arm-vs-arm $ comparison stays unbiased (the repro is a shared instrument). ──
1331
- const authorUsd = usdOf(rowF.reproAuthorTokensIn, rowF.reproAuthorTokensOut)
1332
- for (const [row, counter] of [
1333
- [rowF, counterF],
1334
- [rowL, counterL],
1335
- ] as Array<[Row, Counter]>) {
1336
- row.llmCalls = counter.calls
1337
- row.httpAttempts = counter.httpAttempts
1338
- // WORKER tokens only — kept clean so the "worker budget identical across F/L" audit reads the
1339
- // ledger directly. The supervisor's spend lives in row.supervisorPlan and is added to $ below.
1340
- row.tokensIn = counter.tokensIn
1341
- row.tokensOut = counter.tokensOut
1342
- row.guardedMsgs = counter.guardedMsgs
1343
- const supUsd = row.supervisorPlan ? usdOf(row.supervisorPlan.planTokensIn, row.supervisorPlan.planTokensOut) : 0
1344
- row.usd = usdOf(counter.tokensIn, counter.tokensOut) + authorUsd / 2 + supUsd
1345
- row.wallMs = Date.now() - t0
1346
- const cum = state.cum[row.arm]
1347
- cum.n += 1
1348
- if (row.hiddenResolved === true) cum.resolved += 1
1349
- cum.usd += row.usd
1350
- row.cumN = cum.n
1351
- row.cumResolved = cum.resolved
1352
- row.cumUsd = cum.usd
1353
- appendRow(row)
1354
- }
1355
-
1356
- // ── Rotation: delete the instance image AFTER both arms + judge, unless it was cached at
1357
- // stream start (the keep-set). ──
1358
- const tag = rowF.image
1359
- if (tag && !state.keepImages.has(tag)) {
1360
- try {
1361
- await exec('docker', ['rmi', tag], { timeout: 120_000 })
1362
- logEvent('image-deleted', { streamIndex, instanceId: bt.id, tag })
1363
- } catch (e) {
1364
- logEvent('image-delete-failed', { streamIndex, instanceId: bt.id, tag, error: String(e).slice(0, 200) })
1365
- }
1366
- }
1367
-
1368
- const sup = (r: Row): string =>
1369
- r.supervisorPlan ? ` sup=${r.supervisorPlan.fired ? `fired(${r.supervisorPlan.reason},${r.supervisorPlan.planTokensOut}out)` : `held(${r.supervisorPlan.reason})`}` : ''
1370
- const fmt = (r: Row): string =>
1371
- `${r.arm}: repro=${r.reproStatus} sel=${r.selection ? `${r.selection.mode}@${r.selection.selectedIdx}` : '-'} ` +
1372
- `sev=[${r.candidates.map((x) => x.severity).join(',')}] repairs=${r.repairs.length} caps=${r.capBreaches} ` +
1373
- `resolved=${r.hiddenResolved === null ? '?' : r.hiddenResolved ? 1 : 0} calls=${r.llmCalls} $${r.usd.toFixed(3)}${sup(r)}` +
1374
- `${r.error ? ` ERR=${r.error.slice(0, 80)}` : ''}`
1375
- console.log(`[#${streamIndex}] ${bt.id} settle (${Math.round((Date.now() - t0) / 1000)}s)\n ${fmt(rowF)}\n ${fmt(rowL)}`)
1376
- }
1377
-
1378
- // ---------- curve (a pure fold over the ledger, in stream order) ----------
1379
-
1380
- function printCurve(rows: Row[]): void {
1381
- const byKey = new Map<string, Row>()
1382
- for (const r of rows) byKey.set(`${r.streamIndex}:${r.arm}`, r) // last write wins (resume reruns)
1383
- const indices = [...new Set([...byKey.values()].map((r) => r.streamIndex))].sort((a, b) => a - b)
1384
- let fN = 0
1385
- let fRes = 0
1386
- let fUsd = 0
1387
- let lRes = 0
1388
- let lUsd = 0
1389
- console.log('\n══ cumulative divergence curve (fold over the ledger, stream order) ══')
1390
- console.log('idx | instance | F | L | F-cum% | L-cum% | delta(pp) | F-cum$ | L-cum$')
1391
- for (const i of indices) {
1392
- const f = byKey.get(`${i}:F`)
1393
- const l = byKey.get(`${i}:L`)
1394
- if (!f || !l) continue
1395
- fN += 1
1396
- if (f.hiddenResolved === true) fRes += 1
1397
- if (l.hiddenResolved === true) lRes += 1
1398
- fUsd += f.usd
1399
- lUsd += l.usd
1400
- const fPct = (100 * fRes) / fN
1401
- const lPct = (100 * lRes) / fN
1402
- console.log(
1403
- `${String(i).padStart(3)} | ${f.instanceId.padEnd(38)} | ${f.hiddenResolved ? 1 : 0} | ${l.hiddenResolved ? 1 : 0} | ` +
1404
- `${fPct.toFixed(1).padStart(5)} | ${lPct.toFixed(1).padStart(5)} | ${(lPct - fPct).toFixed(1).padStart(6)} | ` +
1405
- `${fUsd.toFixed(2).padStart(6)} | ${lUsd.toFixed(2).padStart(6)}`,
1406
- )
1407
- }
1408
- console.log(`n=${fN} paired | F resolved ${fRes}/${fN} | L resolved ${lRes}/${fN} | final delta ${((100 * (lRes - fRes)) / Math.max(1, fN)).toFixed(1)}pp`)
1409
- }
1410
-
1411
- // ---------- driver ----------
1412
-
1413
- async function main(): Promise<void> {
1414
- mkdirSync(STREAM_DIR, { recursive: true })
1415
- await initKnowledgeBase(STORE)
1416
-
1417
- const pool = process.env.IDS
1418
- ? process.env.IDS.split(',').map((s) => s.trim()).filter(Boolean)
1419
- : [...FINGERPRINT_23]
1420
- // Stream order is an APPEND-ONLY pre-registered plan persisted in STREAM_DIR/plan.json: the
1421
- // saved order is immutable (streamIndex must stay stable across continuations); ids new to the
1422
- // pool are seeded-shuffled, cached-images-first, and APPENDED. Day-1 starts the plan; later days
1423
- // extend it by passing a larger IDS pool to the same STREAM_DIR.
1424
- const planPath = join(STREAM_DIR, 'plan.json')
1425
- const prefix: string[] = existsSync(planPath) ? (JSON.parse(readFileSync(planPath, 'utf8')) as string[]) : []
1426
- const known = new Set(prefix)
1427
- const shuffled = seededShuffle(pool.filter((id) => !known.has(id)), SEED)
1428
- const cached = new Set(await cachedInstanceIds())
1429
- const fullPlan = [...prefix, ...shuffled.filter((id) => cached.has(id)), ...shuffled.filter((id) => !cached.has(id))]
1430
- writeFileSync(planPath, `${JSON.stringify(fullPlan, null, 1)}\n`)
1431
- const plan = fullPlan.slice(0, Math.min(fullPlan.length, STREAM_N))
1432
-
1433
- console.log('═══ SWE-bench STREAM — day 1 (two-arm, F=frozen-v0 vs L=learning) ═══')
1434
- console.log(
1435
- `worker=${WORKER_MODEL} supervisor=${SUPERVISOR_MODEL} (arm L repair only) repro-author=${REPRO_MODEL} ` +
1436
- `reasoning=${REASONING_ON ? 'thinking' : 'off'} base=${ZAI_BASE} ` +
1437
- `maxTokens=${MAX_TOKENS} supMaxTokens=${SUPERVISOR_MAX_TOKENS} k=${K} temp=${TEMP} repairs<=${REPAIRS} ` +
1438
- `innerTurns=${INNER_TURNS} TURN_CAP=${TURN_CAP} DEADLINE_MS=${DEADLINE_MS} conc=${CONC} seed=0x${SEED.toString(16)} ` +
1439
- `judge=serialized(cache_level=${process.env.SWEBENCH_CACHE_LEVEL}) profile=${PROFILE_VERSION}`,
1440
- )
1441
- console.log(`stream dir=${STREAM_DIR}\nplan (${plan.length}): ${plan.join(', ')}`)
1442
- const manifestN = plan.filter((id) => MANIFEST[id]).length
1443
- console.log(`repro manifest: ${manifestN}/${plan.length} reused (re-verified); the rest author fresh`)
1444
-
1445
- const env = await createSweBenchEnvironment(plan.length, { ids: plan, cloneCache: true })
1446
- await env.adapter.preflight?.()
1447
- const taskById = new Map((await env.adapter.loadTasks({ ids: plan, split: 'test' })).map((t) => [t.id, t]))
1448
- const missing = plan.filter((id) => !taskById.has(id))
1449
- if (missing.length) throw new Error(`instances not found in SWE-bench_Verified: ${missing.join(', ')}`)
1450
-
1451
- // Resume: an instance is DONE iff both arm rows settled. Cumulative tracks, the failure tally,
1452
- // and the FTP mark set refold from the ledger.
1453
- const prior = loadLedger()
1454
- const doneIds = new Set<string>()
1455
- const seen = new Map<string, Set<string>>()
1456
- for (const r of prior) {
1457
- const arms = seen.get(r.instanceId) ?? new Set<string>()
1458
- arms.add(r.arm)
1459
- seen.set(r.instanceId, arms)
1460
- if (arms.has('F') && arms.has('L')) doneIds.add(r.instanceId)
1461
- }
1462
- const state: StreamState = {
1463
- keepImages: new Set<string>(),
1464
- ftpMarks: new Set<string>(),
1465
- tally: {},
1466
- cum: { F: { n: 0, resolved: 0, usd: 0 }, L: { n: 0, resolved: 0, usd: 0 } },
1467
- judgeChain: Promise.resolve(),
1468
- }
1469
- for (const r of prior) {
1470
- const cum = state.cum[r.arm]
1471
- cum.n = Math.max(cum.n, r.cumN)
1472
- cum.resolved = Math.max(cum.resolved, r.cumResolved)
1473
- cum.usd = Math.max(cum.usd, r.cumUsd)
1474
- if (r.arm === 'L' && r.tallySnapshot) state.tally = { ...r.tallySnapshot }
1475
- }
1476
- for (const id of doneIds) {
1477
- const t = taskById.get(id)
1478
- if (t) for (const m of failToPassNames(t.metadata ?? {})) state.ftpMarks.add(m)
1479
- }
1480
- // The keep-set: every instance image cached at stream start survives rotation.
1481
- const { stdout } = await exec('docker', ['images', '--format', '{{.Repository}}:{{.Tag}}'], { timeout: 30_000 })
1482
- for (const line of stdout.split('\n')) {
1483
- if (/sweb\.eval\.x86_64\./.test(line.trim())) state.keepImages.add(line.trim())
1484
- }
1485
- // Fresh stream ⇒ the memory store must start EMPTY (the doc's divergence-only-from-learning
1486
- // invariant). A resumed stream carries its own notes forward.
1487
- if (prior.length === 0) {
1488
- const idx = await buildKnowledgeIndex(STORE)
1489
- if (idx.pages.length > 0) {
1490
- throw new Error(`stream is fresh (empty ledger) but the memory store has ${idx.pages.length} page(s) — stale STORE at ${STORE}`)
1491
- }
1492
- }
1493
- if (prior.length === 0) {
1494
- logEvent('stream-start', {
1495
- seed: SEED, plan, deadlineMs: DEADLINE_MS, turnCap: TURN_CAP, k: K, repairs: REPAIRS,
1496
- temp: TEMP, workerModel: WORKER_MODEL, supervisorModel: SUPERVISOR_MODEL, reproModel: REPRO_MODEL,
1497
- reasoningEffort: REASONING_EFFORT, profileVersion: PROFILE_VERSION, keepImages: [...state.keepImages],
1498
- })
1499
- } else {
1500
- logEvent('stream-resume', { done: doneIds.size, planned: plan.length })
1501
- }
1502
- if (doneIds.size) console.log(`resume: ${doneIds.size} instance(s) already settled; ${plan.filter((id) => !doneIds.has(id)).length} to run`)
1503
-
1504
- let next = 0
1505
- const worker = async (): Promise<void> => {
1506
- while (next < plan.length) {
1507
- const i = next++
1508
- const id = plan[i] as string
1509
- if (doneIds.has(id)) continue
1510
- // Day-1 STUB of the every-N batch trigger (N=25): the gate look is wired on later days.
1511
- if (i > 0 && i % 25 === 0) logEvent('batch-look (stub)', { streamIndex: i })
1512
- console.log(`[#${i}] ${id} …`)
1513
- try {
1514
- await processInstance(state, env, taskById.get(id) as BenchTask, i)
1515
- } catch (e) {
1516
- // processInstance settles its own rows; reaching here means settling itself failed.
1517
- console.error(`[#${i}] ${id} SETTLE FAILURE: ${e instanceof Error ? e.message : String(e)}`)
1518
- logEvent('settle-failure', { streamIndex: i, instanceId: id, error: String(e).slice(0, 300) })
1519
- }
1520
- }
1521
- }
1522
- await Promise.all(Array.from({ length: CONC }, () => worker()))
1523
-
1524
- const rows = loadLedger()
1525
- printCurve(rows)
1526
-
1527
- // Sound-repro rate — the instrument's health (per instance, shared across arms; read off F rows).
1528
- // A low rate means the supervisor-fire predicate (repro=ok + severity===1) rarely gets a chance.
1529
- const fRows = rows.filter((r) => r.arm === 'F')
1530
- const soundRepro = fRows.filter((r) => r.reproStatus === 'ok').length
1531
- const reproDist = fRows.reduce<Record<string, number>>((m, r) => ({ ...m, [r.reproStatus]: (m[r.reproStatus] ?? 0) + 1 }), {})
1532
- console.log(
1533
- `sound-repro rate: ${soundRepro}/${fRows.length} ok (author=${REPRO_MODEL}) — status dist ${JSON.stringify(reproDist)}`,
1534
- )
1535
-
1536
- const byArm = (arm: 'F' | 'L'): Row[] => rows.filter((r) => r.arm === arm)
1537
- for (const arm of ['F', 'L'] as const) {
1538
- const a = byArm(arm)
1539
- const caps = a.reduce((s, r) => s + r.capBreaches, 0)
1540
- const dl = a.filter((r) => r.deadlineHit).length
1541
- const usd = a.reduce((s, r) => s + r.usd, 0)
1542
- const tokIn = a.reduce((s, r) => s + r.tokensIn, 0)
1543
- const tokOut = a.reduce((s, r) => s + r.tokensOut, 0)
1544
- const guarded = a.reduce((s, r) => s + r.guardedMsgs, 0)
1545
- const supFired = a.filter((r) => r.supervisorPlan?.fired).length
1546
- const supLeaked = a.filter((r) => r.supervisorPlan?.leaked).length
1547
- const supTrips = a.filter((r) => r.supervisorPlan?.reason === 'leak-guard-tripped').length
1548
- console.log(
1549
- `arm ${arm}: rows=${a.length} resolved=${a.filter((r) => r.hiddenResolved === true).length} ` +
1550
- `errorRows=${a.filter((r) => r.error).length} deadlineHits=${dl} capBreaches=${caps} ` +
1551
- `supervisorFired=${supFired} planLeaked=${supLeaked} leakTrips=${supTrips} ` +
1552
- `tokens=${tokIn}/${tokOut} guardedMsgs=${guarded} $${usd.toFixed(2)} (assumed $${PRICE_IN}/M in, $${PRICE_OUT}/M out)`,
1553
- )
1554
- }
1555
- console.log(`ledger=${LEDGER}\nevents=${EVENTS}\nstore=${STORE}`)
1556
- }
1557
-
1558
- main().catch((e) => {
1559
- console.error(e instanceof Error ? (e.stack ?? e.message) : String(e))
1560
- process.exit(1)
1561
- })