@tangle-network/agent-bench 0.14.4 → 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.
- package/CHANGELOG.md +38 -0
- package/README.md +2 -3
- package/dist/adapters.d.ts +2 -5
- package/dist/adapters.js +3 -4
- package/dist/benchmarks/_harness.d.ts +17 -20
- package/dist/benchmarks/_harness.js +4 -4
- package/dist/benchmarks/_harness.js.map +1 -1
- package/dist/benchmarks/aec-bench.d.ts +1 -4
- package/dist/benchmarks/aec-bench.js +1 -2
- package/dist/benchmarks/agentbench.d.ts +2 -5
- package/dist/benchmarks/agentbench.js +1 -2
- package/dist/benchmarks/appworld.d.ts +8 -10
- package/dist/benchmarks/appworld.js +23 -23
- package/dist/benchmarks/appworld.js.map +1 -1
- package/dist/benchmarks/bfcl.d.ts +2 -5
- package/dist/benchmarks/bfcl.js +1 -2
- package/dist/benchmarks/cad-design.d.ts +2 -5
- package/dist/benchmarks/cad-design.js +2 -3
- package/dist/benchmarks/cad-design.js.map +1 -1
- package/dist/benchmarks/cadbench.d.ts +1 -4
- package/dist/benchmarks/cadbench.js +1 -2
- package/dist/benchmarks/cadgenbench.d.ts +1 -4
- package/dist/benchmarks/cadgenbench.js +1 -2
- package/dist/benchmarks/commit0.d.ts +2 -5
- package/dist/benchmarks/commit0.js +1 -2
- package/dist/benchmarks/crag.d.ts +1 -4
- package/dist/benchmarks/crag.js +3 -3
- package/dist/benchmarks/crag.js.map +1 -1
- package/dist/benchmarks/dabstep.d.ts +2 -5
- package/dist/benchmarks/dabstep.js +2 -3
- package/dist/benchmarks/dabstep.js.map +1 -1
- package/dist/benchmarks/enterpriseops-gym.d.ts +2 -5
- package/dist/benchmarks/enterpriseops-gym.js +1 -2
- package/dist/benchmarks/finresearchbench.d.ts +2 -5
- package/dist/benchmarks/finresearchbench.js +2 -3
- package/dist/benchmarks/finsearchcomp.d.ts +2 -5
- package/dist/benchmarks/finsearchcomp.js +4 -4
- package/dist/benchmarks/finsearchcomp.js.map +1 -1
- package/dist/benchmarks/frames.d.ts +3 -19
- package/dist/benchmarks/frames.js +13 -39
- package/dist/benchmarks/frames.js.map +1 -1
- package/dist/benchmarks/hotpotqa.d.ts +4 -14
- package/dist/benchmarks/hotpotqa.js +12 -32
- package/dist/benchmarks/hotpotqa.js.map +1 -1
- package/dist/benchmarks/humaneval.d.ts +9 -12
- package/dist/benchmarks/humaneval.js +2 -3
- package/dist/benchmarks/humaneval.js.map +1 -1
- package/dist/benchmarks/mcad-bench.d.ts +13 -16
- package/dist/benchmarks/mcad-bench.js +2 -3
- package/dist/benchmarks/mcad-bench.js.map +1 -1
- package/dist/benchmarks/mcad-cq-bench.d.ts +17 -20
- package/dist/benchmarks/mcad-cq-bench.js +2 -3
- package/dist/benchmarks/mcad-cq-bench.js.map +1 -1
- package/dist/benchmarks/mcad-cq-golds.d.ts +2 -5
- package/dist/benchmarks/mcad-cq-golds.js +1 -2
- package/dist/benchmarks/mcad-golds.d.ts +1 -4
- package/dist/benchmarks/mcad-golds.js +0 -1
- package/dist/benchmarks/mcad-tasks.d.ts +5 -8
- package/dist/benchmarks/mcad-tasks.js +7 -8
- package/dist/benchmarks/mcad-tasks.js.map +1 -1
- package/dist/benchmarks/mind2web.d.ts +3 -5
- package/dist/benchmarks/mind2web.js +2 -3
- package/dist/benchmarks/mind2web.js.map +1 -1
- package/dist/benchmarks/nomiracl.d.ts +1 -4
- package/dist/benchmarks/nomiracl.js +1 -2
- package/dist/benchmarks/open-rag-bench.d.ts +1 -4
- package/dist/benchmarks/open-rag-bench.js +3 -3
- package/dist/benchmarks/open-rag-bench.js.map +1 -1
- package/dist/benchmarks/programbench.d.ts +2 -5
- package/dist/benchmarks/programbench.js +1 -2
- package/dist/benchmarks/rag-shared.d.ts +30 -22
- package/dist/benchmarks/rag-shared.js +8 -2
- package/dist/benchmarks/rag-shared.js.map +1 -1
- package/dist/benchmarks/ragbench.d.ts +1 -4
- package/dist/benchmarks/ragbench.js +3 -3
- package/dist/benchmarks/ragbench.js.map +1 -1
- package/dist/benchmarks/simpleqa.d.ts +2 -18
- package/dist/benchmarks/simpleqa.js +5 -31
- package/dist/benchmarks/simpleqa.js.map +1 -1
- package/dist/benchmarks/swe-bench.d.ts +7 -10
- package/dist/benchmarks/swe-bench.js +4 -4
- package/dist/benchmarks/swe-bench.js.map +1 -1
- package/dist/benchmarks/t2-ragbench.d.ts +1 -4
- package/dist/benchmarks/t2-ragbench.js +3 -3
- package/dist/benchmarks/t2-ragbench.js.map +1 -1
- package/dist/benchmarks/tau-bench-shared.d.ts +5 -8
- package/dist/benchmarks/tau-bench-shared.js +4 -4
- package/dist/benchmarks/tau-bench-shared.js.map +1 -1
- package/dist/benchmarks/tau2-bench.d.ts +2 -5
- package/dist/benchmarks/tau2-bench.js +1 -2
- package/dist/benchmarks/tau3-banking.d.ts +1 -4
- package/dist/benchmarks/tau3-banking.js +1 -2
- package/dist/benchmarks/terminal-bench.d.ts +1 -4
- package/dist/benchmarks/terminal-bench.js +4 -4
- package/dist/benchmarks/terminal-bench.js.map +1 -1
- package/dist/benchmarks/toollm.d.ts +2 -5
- package/dist/benchmarks/toollm.js +1 -2
- package/dist/benchmarks/trata-hedge.d.ts +1 -4
- package/dist/benchmarks/trata-hedge.js +2 -3
- package/dist/benchmarks/types.d.ts +6 -9
- package/dist/benchmarks/webarena-verified.d.ts +2 -5
- package/dist/benchmarks/webarena-verified.js +1 -2
- package/dist/{cadbench-BRF-59Mt.js → cadbench-DhAndllg.js} +4 -6
- package/dist/cadbench-DhAndllg.js.map +1 -0
- package/dist/{cadgenbench-DXtGkuW3.js → cadgenbench-Tvk16YKT.js} +15 -5
- package/dist/cadgenbench-Tvk16YKT.js.map +1 -0
- package/dist/index.d.ts +8 -18
- package/dist/index.js +16 -24
- package/dist/index.js.map +1 -1
- package/dist/{router-turn-uTYO6KQ1.js → router-turn-DNbQ_GjQ.js} +2 -3
- package/dist/router-turn-DNbQ_GjQ.js.map +1 -0
- package/fixtures/pier-agent/no-model-task/pre_artifacts.sh +0 -0
- package/fixtures/pier-agent/no-model-task/tests/test.sh +0 -0
- package/package.json +10 -10
- package/pier_agents/tangle_candidate.py +15 -23
- package/scripts/run-package-tests.mjs +8 -15
- package/src/atom-mcp-e2e.mts +2 -2
- package/src/benchmarks/frames.ts +10 -44
- package/src/benchmarks/hotpotqa.ts +9 -29
- package/src/benchmarks/rag-shared.ts +12 -0
- package/src/benchmarks/simpleqa.ts +2 -36
- package/src/commit0-prereqs.sh +0 -0
- package/src/corpus-replay.mts +8 -8
- package/src/corpus-report.mts +21 -21
- package/src/corpus.test.mts +5 -5
- package/src/corpus.ts +16 -16
- package/src/directives.ts +0 -38
- package/src/examples/lean-verify.ts +1 -1
- package/src/gate.ts +7 -7
- package/src/generate-eval/certify.ts +2 -2
- package/src/index.ts +1 -0
- package/src/refine-loop.ts +5 -5
- package/src/resolve-client.ts +1 -1
- package/src/router-turn.ts +3 -11
- package/src/run-pool.ts +1 -1
- package/src/runtime-hook-recorder.ts +2 -2
- package/src/search-bench/tasks.ts +1 -1
- package/src/selector.test.mts +13 -13
- package/src/selector.ts +19 -19
- package/src/swe-bench-env.ts +4 -12
- package/src/swe-jail.ts +5 -156
- package/src/swe-structural-judge-policy.ts +3 -3
- package/src/swe-structural-policy.ts +3 -3
- package/src/swe-structural-provenance.ts +4 -4
- package/src/terminal-compare.ts +10 -10
- package/src/worker-blender.ts +2 -106
- package/src/worker-build123d.ts +2 -81
- package/tb_agents/opencode_router_agent.py +1 -1
- package/dist/cadbench-BRF-59Mt.js.map +0 -1
- package/dist/cadgenbench-DXtGkuW3.js.map +0 -1
- package/dist/router-turn-uTYO6KQ1.js.map +0 -1
- package/scripts/cadbench_prepare.py +0 -22
- package/scripts/cadgenbench_hard_parts.py +0 -48
- package/scripts/clbench_codebase_judge.py +0 -73
- package/scripts/render-gate-chart.mjs +0 -176
- package/scripts/trata-hedge/README.md +0 -57
- package/scripts/trata-hedge/run.sh +0 -64
- package/src/cloud-loop.mts +0 -156
- package/src/coordination-mcp-container-reach.mts +0 -182
- package/src/fleet.mts +0 -143
- package/src/hev-structural.mts +0 -697
- package/src/humaneval-gate.mts +0 -220
- package/src/mbpp-structural.mts +0 -676
- package/src/mcp-mount-probe.mts +0 -141
- package/src/profiles.ts +0 -128
- package/src/research-gate.mts +0 -132
- package/src/research-shot.ts +0 -144
- package/src/router-executor.ts +0 -51
- package/src/sandbox-run.ts +0 -108
- package/src/search-bench/bridge.ts +0 -182
- package/src/search-bench/export.mts +0 -0
- package/src/search-bench/parametric-check.mts +0 -78
- package/src/search-bench/profiles.ts +0 -113
- package/src/search-bench/run.mts +0 -286
- package/src/search-bench/tasks-fresh.ts +0 -688
- package/src/smoke-structural-rollout.mts +0 -415
- package/src/stats.mts +0 -90
- package/src/swe-code-improve.mts +0 -306
- package/src/swe-improve.mts +0 -284
- package/src/swe-structural.mts +0 -707
- package/src/tb-container-executor.mts +0 -266
- package/src/tb-container-executor.test.mts +0 -134
- package/src/tb-supervisor-sidecar.mts +0 -208
- package/src/trata-gepa.mts +0 -381
- package/src/trata-hedge-solve.mts +0 -81
- package/tb_agents/opencode_refine_agent.py +0 -117
- package/tb_agents/opencode_supervisor_agent.py +0 -239
package/src/swe-structural.mts
DELETED
|
@@ -1,707 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Stage 1 of the SWE-bench frontier push — the STRUCTURAL-SYSTEM mechanics pilot
|
|
3
|
-
* (contract: supervisor-lab/docs/results/PREREG-swe-frontier.md, Stage 1; execution design per the
|
|
4
|
-
* AMENDMENT + CLOSURE: image substrate everywhere, per-instance execution canary asserted at open).
|
|
5
|
-
*
|
|
6
|
-
* ARM=system, per instance:
|
|
7
|
-
* 1. canary — the Stage-0 execution canary on the image substrate (gold applied in-container,
|
|
8
|
-
* `import <pkg>` must resolve into /testbed). Gold is used strictly script-side, never near a
|
|
9
|
-
* model message (transport-level leak guard, below).
|
|
10
|
-
* 2. repro — the instance's Stage-0 valid+sound repro script is REUSED (REPRO_MANIFEST; source
|
|
11
|
-
* recorded per row) and re-verified on THIS substrate with zero model calls: validity (nonzero
|
|
12
|
-
* exit on the unpatched /testbed) + soundness (exit 0 under gold, in-container). A script that
|
|
13
|
-
* fails re-verification degrades to repro=none — recorded, never silent. Instances with no
|
|
14
|
-
* Stage-0 repro run repro=none and measure the no-signal path (selection = blind-first).
|
|
15
|
-
* 3. k=4 independent patch attempts — each the swe-emit-patch protocol verbatim (SWE_SEED_PROMPT,
|
|
16
|
-
* list/read/edit tools on a fresh host clone, runAgentic refine budget=1, glm-5.2 temp 0.8;
|
|
17
|
-
* the candidate is the workspace `git diff`, captured from inside score()).
|
|
18
|
-
* 4. selection — each candidate is scored in-image: `git apply` the candidate to the container's
|
|
19
|
-
* /testbed (writable layer, --rm discards), run the repro. Argmax: repro-pass first, then
|
|
20
|
-
* crash-lowest (fail < timeout < apply-fail < empty), first index breaks ties. With repro=none
|
|
21
|
-
* the selection degrades to blind-first (first non-empty candidate).
|
|
22
|
-
* 5. ≤2 guarded repair rounds on the best — the repro failure output (+ the current diff, both
|
|
23
|
-
* model-visible by construction) steers a fresh emit-patch attempt on a workspace with the
|
|
24
|
-
* best diff pre-applied; the combined diff must STRICTLY improve the repro outcome to displace
|
|
25
|
-
* (a repro-pass can never be displaced by a repro-fail — repair only runs while failing).
|
|
26
|
-
* 6. final diff locked → Phase B.
|
|
27
|
-
* ARM=solo: one emit-patch attempt (temp 0.7 — runShot's July-protocol default), same environment,
|
|
28
|
-
* same 23 instances. The honest single-attempt reference.
|
|
29
|
-
*
|
|
30
|
-
* Phase B (hidden judge): adapter.judge — the OFFICIAL swebench harness — runs serialized
|
|
31
|
-
* (max_workers 1) over the locked final diffs only, strictly AFTER every arm decision. Judge
|
|
32
|
-
* separation is asserted at the transport chokepoint: every outbound request's system/user messages
|
|
33
|
-
* (the strings WE author) are checked against gold-patch + test_patch content marks and refused on
|
|
34
|
-
* contact. Assistant/tool messages are exempt by construction (the model's own text and reads of
|
|
35
|
-
* the base tree — a model that independently authors the gold line is a success, not a leak).
|
|
36
|
-
*
|
|
37
|
-
* cd ~/company/devops/secrets && dotenvx run -f agent-state.env -- bash -c \
|
|
38
|
-
* 'cd ~/code/agent-runtime-swe && ARM=system REPRO_MANIFEST=/path/manifest.json \
|
|
39
|
-
* OUT=/path/swe-stage1-system.jsonl node_modules/.bin/tsx bench/src/swe-structural.mts'
|
|
40
|
-
*
|
|
41
|
-
* Env: ARM=system|solo (required), ZAI_API_KEY (required), ZAI_BASE, MODEL=glm-5.2,
|
|
42
|
-
* MAX_TOKENS=12000, K=4, REPAIRS=2, TEMP=0.8 (system attempts+repairs), SOLO_TEMP=0.7,
|
|
43
|
-
* INNER_TURNS=40, CONC=2, REPRO_TIMEOUT=120 (s), LLM_TIMEOUT_MS=480000, IDS=comma-list,
|
|
44
|
-
* OUT=jsonl path, REPRO_MANIFEST=json path (system), SKIP_JUDGE=1 (Phase A only),
|
|
45
|
-
* PRICE_IN/PRICE_OUT (USD per Mtok for the cost table; defaults are the assumed zai list rate).
|
|
46
|
-
* Rows are incremental (OUT.phaseA then OUT) and both phases resume by instance id.
|
|
47
|
-
*/
|
|
48
|
-
import { execFile } from 'node:child_process'
|
|
49
|
-
import { appendFileSync, existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
|
50
|
-
import { join } from 'node:path'
|
|
51
|
-
import { promisify } from 'node:util'
|
|
52
|
-
import type { AgenticSurface, AgenticTask, ArtifactHandle, SurfaceScore } from '@tangle-network/agent-runtime/kernel'
|
|
53
|
-
import { defaultAnalystInstruction, refine, runAgentic } from '@tangle-network/agent-runtime/kernel'
|
|
54
|
-
import type { BenchTask } from './benchmarks/types'
|
|
55
|
-
import { createSweBenchEnvironment, resolveImageForMetadata, SWE_SEED_PROMPT } from './swe-bench-env'
|
|
56
|
-
import {
|
|
57
|
-
APPLY_SENTINEL,
|
|
58
|
-
assertNoHiddenLeak,
|
|
59
|
-
cachedInstanceIds,
|
|
60
|
-
IMPORT_NAME,
|
|
61
|
-
importCanaryScript,
|
|
62
|
-
runPyInJail,
|
|
63
|
-
tail,
|
|
64
|
-
zaiChatRaw,
|
|
65
|
-
} from './swe-jail'
|
|
66
|
-
import { withBenchProfile } from './router-turn'
|
|
67
|
-
|
|
68
|
-
const exec = promisify(execFile)
|
|
69
|
-
|
|
70
|
-
// ---------- config ----------
|
|
71
|
-
|
|
72
|
-
const ARM = process.env.ARM ?? ''
|
|
73
|
-
if (ARM !== 'system' && ARM !== 'solo') throw new Error(`ARM must be system|solo, got "${ARM}"`)
|
|
74
|
-
const ZAI_BASE = process.env.ZAI_BASE ?? 'https://api.z.ai/api/coding/paas/v4'
|
|
75
|
-
const ZAI_KEY = process.env.ZAI_API_KEY ?? ''
|
|
76
|
-
if (!ZAI_KEY) throw new Error('ZAI_API_KEY required (run under dotenvx: agent-state.env)')
|
|
77
|
-
const MODEL = process.env.MODEL ?? 'glm-5.2'
|
|
78
|
-
// glm-5.2 is a reasoning model: hidden reasoning consumes max_tokens, so <8000 starves content.
|
|
79
|
-
const MAX_TOKENS = Number(process.env.MAX_TOKENS ?? 12_000)
|
|
80
|
-
const K = Number(process.env.K ?? 4)
|
|
81
|
-
const REPAIRS = Number(process.env.REPAIRS ?? 2)
|
|
82
|
-
const TEMP = Number(process.env.TEMP ?? 0.8)
|
|
83
|
-
const SOLO_TEMP = Number(process.env.SOLO_TEMP ?? 0.7)
|
|
84
|
-
const INNER_TURNS = Number(process.env.INNER_TURNS ?? 40)
|
|
85
|
-
const CONC = Math.max(1, Math.min(4, Number(process.env.CONC ?? 2)))
|
|
86
|
-
const REPRO_TIMEOUT_S = Number(process.env.REPRO_TIMEOUT ?? 120)
|
|
87
|
-
const LLM_TIMEOUT_MS = Number(process.env.LLM_TIMEOUT_MS ?? 480_000)
|
|
88
|
-
const OUT = process.env.OUT ?? `swe-stage1-${ARM}.jsonl`
|
|
89
|
-
const PHASE_A_OUT = `${OUT}.phaseA`
|
|
90
|
-
const SKIP_JUDGE = process.env.SKIP_JUDGE === '1'
|
|
91
|
-
// Cost-table rates, USD per Mtok. ASSUMED (zai coding-plan tokens have no per-call list price);
|
|
92
|
-
// override with PRICE_IN/PRICE_OUT. The summary labels them as assumed.
|
|
93
|
-
const PRICE_IN = Number(process.env.PRICE_IN ?? 0.6)
|
|
94
|
-
const PRICE_OUT = Number(process.env.PRICE_OUT ?? 2.2)
|
|
95
|
-
|
|
96
|
-
interface ReproManifestEntry {
|
|
97
|
-
script: string
|
|
98
|
-
source: string
|
|
99
|
-
stage0Class: string
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
const MANIFEST: Record<string, ReproManifestEntry> = (() => {
|
|
103
|
-
if (ARM !== 'system') return {}
|
|
104
|
-
const p = process.env.REPRO_MANIFEST
|
|
105
|
-
if (!p) throw new Error('REPRO_MANIFEST required for ARM=system (Stage-0 valid+sound repro scripts)')
|
|
106
|
-
return JSON.parse(readFileSync(p, 'utf8')) as Record<string, ReproManifestEntry>
|
|
107
|
-
})()
|
|
108
|
-
|
|
109
|
-
// ---------- transport: zai direct, patient ladder, leak guard at the chokepoint ----------
|
|
110
|
-
|
|
111
|
-
interface Counter {
|
|
112
|
-
calls: number
|
|
113
|
-
httpAttempts: number
|
|
114
|
-
tokensIn: number
|
|
115
|
-
tokensOut: number
|
|
116
|
-
guardedMsgs: number
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
const newCounter = (): Counter => ({ calls: 0, httpAttempts: 0, tokensIn: 0, tokensOut: 0, guardedMsgs: 0 })
|
|
120
|
-
|
|
121
|
-
/** Distinctive content marks for the leak guard: the first substantive ADDED line of the gold patch
|
|
122
|
-
* and of the hidden test patch. Never shown to any model; used only to refuse outbound messages. */
|
|
123
|
-
function leakMarks(md: Record<string, string>): string[] {
|
|
124
|
-
const marks: string[] = []
|
|
125
|
-
for (const src of [md.patch, md.test_patch]) {
|
|
126
|
-
const m = String(src ?? '')
|
|
127
|
-
.split('\n')
|
|
128
|
-
.find((l) => l.startsWith('+') && !l.startsWith('+++') && l.trim().length > 12)
|
|
129
|
-
?.slice(0, 80)
|
|
130
|
-
if (m) marks.push(m)
|
|
131
|
-
}
|
|
132
|
-
return marks
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
/** Every model call in this driver flows through here (runAgentic's `complete` seam), so the judge
|
|
136
|
-
* separation is asserted once, at the single chokepoint, for every arm and every round. */
|
|
137
|
-
const makeTransport =
|
|
138
|
-
(marks: string[], counter: Counter) =>
|
|
139
|
-
async (body: Record<string, unknown>): Promise<unknown> => {
|
|
140
|
-
const msgs = (body.messages ?? []) as Array<{ role?: string; content?: unknown }>
|
|
141
|
-
counter.guardedMsgs += assertNoHiddenLeak(marks, msgs)
|
|
142
|
-
const model = String(body.model ?? '')
|
|
143
|
-
const systemPrompt = msgs.find((message) => message.role === 'system')?.content
|
|
144
|
-
const toolNames = Array.isArray(body.tools)
|
|
145
|
-
? (body.tools as Array<{ function?: { name?: unknown } }>).flatMap((tool) =>
|
|
146
|
-
typeof tool.function?.name === 'string' ? [tool.function.name] : [],
|
|
147
|
-
)
|
|
148
|
-
: []
|
|
149
|
-
const { json, attempts } = await zaiChatRaw(
|
|
150
|
-
{ base: ZAI_BASE, key: ZAI_KEY, timeoutMs: LLM_TIMEOUT_MS },
|
|
151
|
-
body,
|
|
152
|
-
{
|
|
153
|
-
name: 'swe-structural-worker',
|
|
154
|
-
harness: 'cli-base',
|
|
155
|
-
model: { provider: 'zai', default: model, reasoningEffort: 'high' },
|
|
156
|
-
...(typeof systemPrompt === 'string' ? { prompt: { systemPrompt } } : {}),
|
|
157
|
-
...(toolNames.length > 0
|
|
158
|
-
? { tools: Object.fromEntries(toolNames.map((name) => [name, true])) }
|
|
159
|
-
: {}),
|
|
160
|
-
},
|
|
161
|
-
)
|
|
162
|
-
counter.calls += 1
|
|
163
|
-
counter.httpAttempts += attempts
|
|
164
|
-
const u = (json as { usage?: { prompt_tokens?: number; completion_tokens?: number } }).usage
|
|
165
|
-
counter.tokensIn += u?.prompt_tokens ?? 0
|
|
166
|
-
counter.tokensOut += u?.completion_tokens ?? 0
|
|
167
|
-
return json
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
// ---------- one emit-patch attempt (the swe-emit-patch protocol, with an optional pre-applied
|
|
171
|
-
// base diff for repair rounds) ----------
|
|
172
|
-
|
|
173
|
-
interface AttemptOut {
|
|
174
|
-
diff: string
|
|
175
|
-
completions: number
|
|
176
|
-
tokensIn: number
|
|
177
|
-
tokensOut: number
|
|
178
|
-
calls: number
|
|
179
|
-
wallMs: number
|
|
180
|
-
error?: string
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
async function emitAttempt(
|
|
184
|
-
environment: AgenticSurface,
|
|
185
|
-
bt: BenchTask,
|
|
186
|
-
cfg: {
|
|
187
|
-
temperature: number
|
|
188
|
-
marks: string[]
|
|
189
|
-
instanceCounter: Counter
|
|
190
|
-
preApply?: string
|
|
191
|
-
promptAppendix?: string
|
|
192
|
-
},
|
|
193
|
-
): Promise<AttemptOut> {
|
|
194
|
-
const t0 = Date.now()
|
|
195
|
-
const counter = newCounter()
|
|
196
|
-
// Capture the patch from inside score() (called during the refine loop, BEFORE the surface closes
|
|
197
|
-
// and rms the checkout). Keep the LATEST non-empty diff — the emit-patch pattern.
|
|
198
|
-
const capture = { patch: '' }
|
|
199
|
-
const proxy: AgenticSurface = {
|
|
200
|
-
...environment,
|
|
201
|
-
async open(t: AgenticTask): Promise<ArtifactHandle> {
|
|
202
|
-
const h = await environment.open(t)
|
|
203
|
-
const pre = cfg.preApply
|
|
204
|
-
if (pre?.trim()) {
|
|
205
|
-
const f = join(h.id, '.swe-preapply.diff')
|
|
206
|
-
writeFileSync(f, pre.endsWith('\n') ? pre : `${pre}\n`)
|
|
207
|
-
try {
|
|
208
|
-
await exec('git', ['-C', h.id, 'apply', '--whitespace=nowarn', f], { timeout: 60_000 })
|
|
209
|
-
} finally {
|
|
210
|
-
rmSync(f, { force: true })
|
|
211
|
-
}
|
|
212
|
-
}
|
|
213
|
-
return h
|
|
214
|
-
},
|
|
215
|
-
async score(_t: AgenticTask, handle: ArtifactHandle): Promise<SurfaceScore> {
|
|
216
|
-
try {
|
|
217
|
-
const d = await exec('git', ['-C', handle.id, 'diff'], { maxBuffer: 40_000_000, timeout: 60_000 })
|
|
218
|
-
if (d.stdout.trim()) capture.patch = d.stdout
|
|
219
|
-
} catch {
|
|
220
|
-
/* workspace gone or git error → keep whatever we already captured */
|
|
221
|
-
}
|
|
222
|
-
return { passes: capture.patch.trim() ? 1 : 0, total: 1, errored: 0 }
|
|
223
|
-
},
|
|
224
|
-
}
|
|
225
|
-
const task: AgenticTask = {
|
|
226
|
-
id: bt.id,
|
|
227
|
-
userPrompt: cfg.promptAppendix ? `${bt.prompt}\n\n${cfg.promptAppendix}` : bt.prompt,
|
|
228
|
-
meta: { instanceId: bt.id },
|
|
229
|
-
}
|
|
230
|
-
const workerProfile = withBenchProfile(
|
|
231
|
-
{
|
|
232
|
-
name: 'swe-structural-worker',
|
|
233
|
-
harness: 'cli-base',
|
|
234
|
-
model: { provider: 'zai', default: MODEL, reasoningEffort: 'high' },
|
|
235
|
-
tools: { list_files: true, read_file: true, edit_file: true },
|
|
236
|
-
},
|
|
237
|
-
{
|
|
238
|
-
systemPrompt: SWE_SEED_PROMPT,
|
|
239
|
-
maxTokens: MAX_TOKENS,
|
|
240
|
-
maxTurns: INNER_TURNS,
|
|
241
|
-
temperature: cfg.temperature,
|
|
242
|
-
},
|
|
243
|
-
)
|
|
244
|
-
const analystProfile = withBenchProfile(
|
|
245
|
-
{
|
|
246
|
-
name: 'swe-structural-analyst',
|
|
247
|
-
harness: 'cli-base',
|
|
248
|
-
model: { provider: 'zai', default: MODEL, reasoningEffort: 'high' },
|
|
249
|
-
},
|
|
250
|
-
{ systemPrompt: defaultAnalystInstruction, maxTokens: MAX_TOKENS },
|
|
251
|
-
)
|
|
252
|
-
let error: string | undefined
|
|
253
|
-
try {
|
|
254
|
-
const r = await runAgentic({
|
|
255
|
-
surface: proxy,
|
|
256
|
-
task,
|
|
257
|
-
strategy: refine,
|
|
258
|
-
routerBaseUrl: 'zai-direct', // unused: the `complete` transport short-circuits the router
|
|
259
|
-
routerKey: 'zai-direct',
|
|
260
|
-
workerProfile,
|
|
261
|
-
analystProfile,
|
|
262
|
-
budget: 1,
|
|
263
|
-
complete: makeTransport(cfg.marks, counter),
|
|
264
|
-
})
|
|
265
|
-
cfg.instanceCounter.calls += counter.calls
|
|
266
|
-
cfg.instanceCounter.httpAttempts += counter.httpAttempts
|
|
267
|
-
cfg.instanceCounter.tokensIn += counter.tokensIn
|
|
268
|
-
cfg.instanceCounter.tokensOut += counter.tokensOut
|
|
269
|
-
cfg.instanceCounter.guardedMsgs += counter.guardedMsgs
|
|
270
|
-
return {
|
|
271
|
-
diff: capture.patch,
|
|
272
|
-
completions: r.completions,
|
|
273
|
-
tokensIn: counter.tokensIn,
|
|
274
|
-
tokensOut: counter.tokensOut,
|
|
275
|
-
calls: counter.calls,
|
|
276
|
-
wallMs: Date.now() - t0,
|
|
277
|
-
}
|
|
278
|
-
} catch (e) {
|
|
279
|
-
error = e instanceof Error ? e.message.slice(0, 300) : String(e).slice(0, 300)
|
|
280
|
-
cfg.instanceCounter.calls += counter.calls
|
|
281
|
-
cfg.instanceCounter.httpAttempts += counter.httpAttempts
|
|
282
|
-
cfg.instanceCounter.tokensIn += counter.tokensIn
|
|
283
|
-
cfg.instanceCounter.tokensOut += counter.tokensOut
|
|
284
|
-
cfg.instanceCounter.guardedMsgs += counter.guardedMsgs
|
|
285
|
-
return {
|
|
286
|
-
diff: capture.patch,
|
|
287
|
-
completions: 0,
|
|
288
|
-
tokensIn: counter.tokensIn,
|
|
289
|
-
tokensOut: counter.tokensOut,
|
|
290
|
-
calls: counter.calls,
|
|
291
|
-
wallMs: Date.now() - t0,
|
|
292
|
-
error,
|
|
293
|
-
}
|
|
294
|
-
}
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
// ---------- in-image candidate scoring ----------
|
|
298
|
-
|
|
299
|
-
/** Severity ordering for argmax (lower is better): 0 repro-pass, 1 repro-fail (clean nonzero exit),
|
|
300
|
-
* 2 repro-timeout, 3 candidate failed to apply, 4 empty candidate. "Crash-lowest" is realized as
|
|
301
|
-
* this exit-class ordering; ties break on first index (deterministic). */
|
|
302
|
-
interface CandScore {
|
|
303
|
-
applyOk: boolean | null
|
|
304
|
-
exit: number | null
|
|
305
|
-
timedOut: boolean
|
|
306
|
-
severity: number
|
|
307
|
-
out: string
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
const EMPTY_SCORE: CandScore = { applyOk: null, exit: null, timedOut: false, severity: 4, out: '' }
|
|
311
|
-
const UNSCORED: CandScore = { applyOk: null, exit: null, timedOut: false, severity: 1, out: '(no repro signal)' }
|
|
312
|
-
|
|
313
|
-
async function scoreCandidate(imageTag: string, repro: string | null, diff: string): Promise<CandScore> {
|
|
314
|
-
if (!diff.trim()) return EMPTY_SCORE
|
|
315
|
-
if (!repro) return UNSCORED
|
|
316
|
-
const r = await runPyInJail(imageTag, null, repro, diff, { timeoutS: REPRO_TIMEOUT_S })
|
|
317
|
-
if (r.infraError) throw new Error(r.infraError)
|
|
318
|
-
const applyOk = r.out.includes(APPLY_SENTINEL)
|
|
319
|
-
if (!applyOk) return { applyOk, exit: r.code, timedOut: r.timedOut, severity: 3, out: tail(r.out, 800) }
|
|
320
|
-
if (r.timedOut) return { applyOk, exit: r.code, timedOut: true, severity: 2, out: tail(r.out, 800) }
|
|
321
|
-
return { applyOk, exit: r.code, timedOut: false, severity: r.code === 0 ? 0 : 1, out: tail(r.out, 1_500) }
|
|
322
|
-
}
|
|
323
|
-
|
|
324
|
-
// ---------- rows ----------
|
|
325
|
-
|
|
326
|
-
interface CandidateRow {
|
|
327
|
-
idx: number
|
|
328
|
-
diff: string
|
|
329
|
-
diffBytes: number
|
|
330
|
-
completions: number
|
|
331
|
-
calls: number
|
|
332
|
-
tokensIn: number
|
|
333
|
-
tokensOut: number
|
|
334
|
-
wallMs: number
|
|
335
|
-
attemptError: string | null
|
|
336
|
-
applyOk: boolean | null
|
|
337
|
-
reproExit: number | null
|
|
338
|
-
reproTimedOut: boolean
|
|
339
|
-
severity: number
|
|
340
|
-
reproOutTail: string
|
|
341
|
-
}
|
|
342
|
-
|
|
343
|
-
interface RepairRow {
|
|
344
|
-
round: number
|
|
345
|
-
baseFrom: string
|
|
346
|
-
baseSeverity: number
|
|
347
|
-
diff: string
|
|
348
|
-
diffBytes: number
|
|
349
|
-
completions: number
|
|
350
|
-
calls: number
|
|
351
|
-
tokensIn: number
|
|
352
|
-
tokensOut: number
|
|
353
|
-
wallMs: number
|
|
354
|
-
attemptError: string | null
|
|
355
|
-
applyOk: boolean | null
|
|
356
|
-
reproExit: number | null
|
|
357
|
-
severity: number
|
|
358
|
-
accepted: boolean
|
|
359
|
-
}
|
|
360
|
-
|
|
361
|
-
interface Row {
|
|
362
|
-
instanceId: string
|
|
363
|
-
arm: string
|
|
364
|
-
repo: string
|
|
365
|
-
model: string
|
|
366
|
-
image: string | null
|
|
367
|
-
execMode: 'image'
|
|
368
|
-
temperature: number
|
|
369
|
-
innerTurns: number
|
|
370
|
-
k: number
|
|
371
|
-
// canary + repro provenance (system arm)
|
|
372
|
-
canaryExit: number | null
|
|
373
|
-
canaryPass: boolean | null
|
|
374
|
-
reproSource: string
|
|
375
|
-
reproStatus: string
|
|
376
|
-
reproScript: string | null
|
|
377
|
-
reproPreExit: number | null
|
|
378
|
-
reproGoldExit: number | null
|
|
379
|
-
// candidates + selection + repair receipts (system arm)
|
|
380
|
-
candidates: CandidateRow[]
|
|
381
|
-
selection: { mode: string; selectedIdx: number; movedOffFirst: boolean } | null
|
|
382
|
-
repairs: RepairRow[]
|
|
383
|
-
repairStop: string | null
|
|
384
|
-
finalFrom: string
|
|
385
|
-
finalDiff: string
|
|
386
|
-
// hidden judge (Phase B; locked-after-decisions)
|
|
387
|
-
hiddenResolved: boolean | null
|
|
388
|
-
judgeDetail: string | null
|
|
389
|
-
judgeMs: number | null
|
|
390
|
-
judgeSkipped: string | null
|
|
391
|
-
// cost + guard receipts
|
|
392
|
-
llmCalls: number
|
|
393
|
-
httpAttempts: number
|
|
394
|
-
tokensIn: number
|
|
395
|
-
tokensOut: number
|
|
396
|
-
guardedMsgs: number
|
|
397
|
-
wallMs: number
|
|
398
|
-
error?: string
|
|
399
|
-
}
|
|
400
|
-
|
|
401
|
-
// ---------- phase A: all arm decisions (no judge anywhere) ----------
|
|
402
|
-
|
|
403
|
-
type Env = Awaited<ReturnType<typeof createSweBenchEnvironment>>
|
|
404
|
-
|
|
405
|
-
async function phaseA(env: Env, bt: BenchTask): Promise<Row> {
|
|
406
|
-
const t0 = Date.now()
|
|
407
|
-
const md = bt.metadata as Record<string, string>
|
|
408
|
-
const counter = newCounter()
|
|
409
|
-
const row: Row = {
|
|
410
|
-
instanceId: bt.id, arm: ARM, repo: md.repo, model: MODEL, image: null, execMode: 'image',
|
|
411
|
-
temperature: ARM === 'system' ? TEMP : SOLO_TEMP, innerTurns: INNER_TURNS, k: ARM === 'system' ? K : 1,
|
|
412
|
-
canaryExit: null, canaryPass: null, reproSource: 'none', reproStatus: 'none', reproScript: null,
|
|
413
|
-
reproPreExit: null, reproGoldExit: null, candidates: [], selection: null, repairs: [],
|
|
414
|
-
repairStop: null, finalFrom: 'none', finalDiff: '', hiddenResolved: null, judgeDetail: null,
|
|
415
|
-
judgeMs: null, judgeSkipped: null, llmCalls: 0, httpAttempts: 0, tokensIn: 0, tokensOut: 0,
|
|
416
|
-
guardedMsgs: 0, wallMs: 0,
|
|
417
|
-
}
|
|
418
|
-
const marks = leakMarks(md)
|
|
419
|
-
try {
|
|
420
|
-
const img = await resolveImageForMetadata(bt.metadata ?? {})
|
|
421
|
-
if (!img.ok) throw new Error(`image missing: ${img.reason}`)
|
|
422
|
-
row.image = img.tag
|
|
423
|
-
|
|
424
|
-
if (ARM === 'solo') {
|
|
425
|
-
const a = await emitAttempt(env.environment, bt, { temperature: SOLO_TEMP, marks, instanceCounter: counter })
|
|
426
|
-
row.candidates.push({
|
|
427
|
-
idx: 0, diff: a.diff, diffBytes: a.diff.length, completions: a.completions, calls: a.calls,
|
|
428
|
-
tokensIn: a.tokensIn, tokensOut: a.tokensOut, wallMs: a.wallMs, attemptError: a.error ?? null,
|
|
429
|
-
applyOk: null, reproExit: null, reproTimedOut: false, severity: a.diff.trim() ? 1 : 4, reproOutTail: '',
|
|
430
|
-
})
|
|
431
|
-
row.finalDiff = a.diff
|
|
432
|
-
row.finalFrom = 'candidate:0'
|
|
433
|
-
return row
|
|
434
|
-
}
|
|
435
|
-
|
|
436
|
-
// 1. EXECUTION CANARY (image substrate, gold in-container — script-side only, zero model calls).
|
|
437
|
-
const pkg = IMPORT_NAME[md.repo]
|
|
438
|
-
if (!pkg) throw new Error(`no IMPORT_NAME for ${md.repo} — canary not expressible`)
|
|
439
|
-
const gold = String(md.patch ?? '')
|
|
440
|
-
if (!gold.trim()) throw new Error('gold patch missing from metadata')
|
|
441
|
-
const c = await runPyInJail(img.tag, null, importCanaryScript(pkg), gold, { timeoutS: REPRO_TIMEOUT_S })
|
|
442
|
-
if (c.infraError) throw new Error(c.infraError)
|
|
443
|
-
row.canaryExit = c.code
|
|
444
|
-
row.canaryPass = c.code === 0 && c.out.includes(APPLY_SENTINEL)
|
|
445
|
-
if (!row.canaryPass) throw new Error(`canary failed (exit ${c.code}): this substrate cannot grade this instance`)
|
|
446
|
-
|
|
447
|
-
// 2. Repro reuse + re-verification on THIS substrate (validity without gold, soundness with).
|
|
448
|
-
const manifest = MANIFEST[bt.id]
|
|
449
|
-
let repro: string | null = null
|
|
450
|
-
if (manifest) {
|
|
451
|
-
row.reproSource = manifest.source
|
|
452
|
-
row.reproScript = manifest.script
|
|
453
|
-
const pre = await runPyInJail(img.tag, null, manifest.script, undefined, { timeoutS: REPRO_TIMEOUT_S })
|
|
454
|
-
if (pre.infraError) throw new Error(pre.infraError)
|
|
455
|
-
row.reproPreExit = pre.code
|
|
456
|
-
if (pre.timedOut) row.reproStatus = 'degraded-timeout'
|
|
457
|
-
else if (pre.code === 0) row.reproStatus = 'degraded-invalid'
|
|
458
|
-
else {
|
|
459
|
-
const post = await runPyInJail(img.tag, null, manifest.script, gold, { timeoutS: REPRO_TIMEOUT_S })
|
|
460
|
-
if (post.infraError) throw new Error(post.infraError)
|
|
461
|
-
row.reproGoldExit = post.code
|
|
462
|
-
if (post.code === 0 && post.out.includes(APPLY_SENTINEL)) {
|
|
463
|
-
row.reproStatus = 'ok'
|
|
464
|
-
repro = manifest.script
|
|
465
|
-
} else {
|
|
466
|
-
row.reproStatus = 'degraded-unsound'
|
|
467
|
-
}
|
|
468
|
-
}
|
|
469
|
-
}
|
|
470
|
-
|
|
471
|
-
// 3. k independent candidates (serial within the instance — CONC instances bound zai concurrency).
|
|
472
|
-
const diffs: string[] = []
|
|
473
|
-
for (let i = 0; i < K; i += 1) {
|
|
474
|
-
const a = await emitAttempt(env.environment, bt, { temperature: TEMP, marks, instanceCounter: counter })
|
|
475
|
-
diffs.push(a.diff)
|
|
476
|
-
row.candidates.push({
|
|
477
|
-
idx: i, diff: a.diff, diffBytes: a.diff.length, completions: a.completions, calls: a.calls,
|
|
478
|
-
tokensIn: a.tokensIn, tokensOut: a.tokensOut, wallMs: a.wallMs, attemptError: a.error ?? null,
|
|
479
|
-
applyOk: null, reproExit: null, reproTimedOut: false, severity: -1, reproOutTail: '',
|
|
480
|
-
})
|
|
481
|
-
}
|
|
482
|
-
|
|
483
|
-
// 4. In-image scoring + argmax.
|
|
484
|
-
const scores: CandScore[] = []
|
|
485
|
-
for (let i = 0; i < K; i += 1) {
|
|
486
|
-
const s = await scoreCandidate(img.tag, repro, diffs[i] as string)
|
|
487
|
-
scores.push(s)
|
|
488
|
-
const cand = row.candidates[i] as CandidateRow
|
|
489
|
-
cand.applyOk = s.applyOk
|
|
490
|
-
cand.reproExit = s.exit
|
|
491
|
-
cand.reproTimedOut = s.timedOut
|
|
492
|
-
cand.severity = s.severity
|
|
493
|
-
cand.reproOutTail = s.out
|
|
494
|
-
}
|
|
495
|
-
let selectedIdx: number
|
|
496
|
-
let mode: string
|
|
497
|
-
if (repro) {
|
|
498
|
-
mode = 'repro-argmax'
|
|
499
|
-
selectedIdx = 0
|
|
500
|
-
for (let i = 1; i < K; i += 1) {
|
|
501
|
-
if ((scores[i] as CandScore).severity < (scores[selectedIdx] as CandScore).severity) selectedIdx = i
|
|
502
|
-
}
|
|
503
|
-
} else {
|
|
504
|
-
mode = 'blind-first'
|
|
505
|
-
const firstNonEmpty = diffs.findIndex((d) => d.trim().length > 0)
|
|
506
|
-
selectedIdx = firstNonEmpty === -1 ? 0 : firstNonEmpty
|
|
507
|
-
}
|
|
508
|
-
row.selection = { mode, selectedIdx, movedOffFirst: mode === 'repro-argmax' && selectedIdx !== 0 }
|
|
509
|
-
|
|
510
|
-
// 5. Guarded repair (repro-armed instances only — no signal, no repair).
|
|
511
|
-
let best = { diff: diffs[selectedIdx] as string, score: scores[selectedIdx] as CandScore, from: `candidate:${selectedIdx}` }
|
|
512
|
-
if (!repro) {
|
|
513
|
-
row.repairStop = 'no-signal'
|
|
514
|
-
} else if (best.score.severity === 0) {
|
|
515
|
-
row.repairStop = 'already-passing'
|
|
516
|
-
} else {
|
|
517
|
-
for (let round = 1; round <= REPAIRS && best.score.severity > 0; round += 1) {
|
|
518
|
-
const appendix =
|
|
519
|
-
(best.diff.trim()
|
|
520
|
-
? `--- PREVIOUS FIX (already applied to this checkout) ---\n${tail(best.diff, 8_000)}\n\n`
|
|
521
|
-
: '--- NO FIX APPLIED YET (every prior attempt produced no change) ---\n\n') +
|
|
522
|
-
`--- REPRODUCTION SCRIPT (written from the issue; exit 0 = fixed) ---\n${tail(repro, 6_000)}\n\n` +
|
|
523
|
-
`--- REPRODUCTION OUTPUT on the current state (exit ${best.score.exit ?? 'n/a'}) ---\n${best.score.out}\n\n` +
|
|
524
|
-
'--- REPAIR INSTRUCTIONS ---\n' +
|
|
525
|
-
'The reproduction above STILL FAILS. Diagnose why the current state does not resolve the issue, ' +
|
|
526
|
-
'then correct the SOURCE with minimal edit_file changes (you may revise or revert parts of the ' +
|
|
527
|
-
'previous fix — it is already in the files). Do not modify tests.'
|
|
528
|
-
const a = await emitAttempt(env.environment, bt, {
|
|
529
|
-
temperature: TEMP, marks, instanceCounter: counter, preApply: best.diff, promptAppendix: appendix,
|
|
530
|
-
})
|
|
531
|
-
const ns = await scoreCandidate(img.tag, repro, a.diff)
|
|
532
|
-
const accepted = ns.severity < best.score.severity
|
|
533
|
-
row.repairs.push({
|
|
534
|
-
round, baseFrom: best.from, baseSeverity: best.score.severity, diff: a.diff, diffBytes: a.diff.length,
|
|
535
|
-
completions: a.completions, calls: a.calls, tokensIn: a.tokensIn, tokensOut: a.tokensOut,
|
|
536
|
-
wallMs: a.wallMs, attemptError: a.error ?? null, applyOk: ns.applyOk, reproExit: ns.exit,
|
|
537
|
-
severity: ns.severity, accepted,
|
|
538
|
-
})
|
|
539
|
-
if (accepted) best = { diff: a.diff, score: ns, from: `repair:${round}` }
|
|
540
|
-
}
|
|
541
|
-
row.repairStop = best.score.severity === 0 ? 'repaired-pass' : 'rounds-exhausted'
|
|
542
|
-
}
|
|
543
|
-
row.finalDiff = best.diff
|
|
544
|
-
row.finalFrom = best.from
|
|
545
|
-
return row
|
|
546
|
-
} catch (e) {
|
|
547
|
-
row.error = e instanceof Error ? e.message.slice(0, 400) : String(e).slice(0, 400)
|
|
548
|
-
return row
|
|
549
|
-
} finally {
|
|
550
|
-
row.llmCalls = counter.calls
|
|
551
|
-
row.httpAttempts = counter.httpAttempts
|
|
552
|
-
row.tokensIn = counter.tokensIn
|
|
553
|
-
row.tokensOut = counter.tokensOut
|
|
554
|
-
row.guardedMsgs = counter.guardedMsgs
|
|
555
|
-
row.wallMs = Date.now() - t0
|
|
556
|
-
}
|
|
557
|
-
}
|
|
558
|
-
|
|
559
|
-
// ---------- driver ----------
|
|
560
|
-
|
|
561
|
-
function loadRows(path: string): Map<string, Row> {
|
|
562
|
-
const m = new Map<string, Row>()
|
|
563
|
-
if (!existsSync(path)) return m
|
|
564
|
-
for (const line of readFileSync(path, 'utf8').split('\n')) {
|
|
565
|
-
if (!line.trim()) continue
|
|
566
|
-
const r = JSON.parse(line) as Row
|
|
567
|
-
m.set(r.instanceId, r)
|
|
568
|
-
}
|
|
569
|
-
return m
|
|
570
|
-
}
|
|
571
|
-
|
|
572
|
-
async function main(): Promise<void> {
|
|
573
|
-
const ids = process.env.IDS
|
|
574
|
-
? process.env.IDS.split(',').map((s) => s.trim()).filter(Boolean)
|
|
575
|
-
: await cachedInstanceIds()
|
|
576
|
-
if (!ids.length) throw new Error('no cached sweb.eval images found and no IDS given')
|
|
577
|
-
|
|
578
|
-
console.log(`═══ SWE-bench Stage 1 — structural pilot, ARM=${ARM} ═══`)
|
|
579
|
-
console.log(
|
|
580
|
-
`model=${MODEL} base=${ZAI_BASE} maxTokens=${MAX_TOKENS} innerTurns=${INNER_TURNS} ` +
|
|
581
|
-
(ARM === 'system' ? `k=${K} temp=${TEMP} repairs<=${REPAIRS} ` : `temp=${SOLO_TEMP} `) +
|
|
582
|
-
`conc=${CONC} reproTimeout=${REPRO_TIMEOUT_S}s exec=image judge=${SKIP_JUDGE ? 'SKIPPED' : 'phase-B serialized'}`,
|
|
583
|
-
)
|
|
584
|
-
console.log(`instances (${ids.length}): ${ids.join(', ')}`)
|
|
585
|
-
if (ARM === 'system') {
|
|
586
|
-
const withRepro = ids.filter((id) => MANIFEST[id]).length
|
|
587
|
-
console.log(`repro manifest: ${withRepro}/${ids.length} instances with a Stage-0 valid+sound repro (rest run repro=none)`)
|
|
588
|
-
}
|
|
589
|
-
console.log(`out=${OUT} (phase A receipts: ${PHASE_A_OUT})`)
|
|
590
|
-
|
|
591
|
-
const env = await createSweBenchEnvironment(ids.length, { ids, cloneCache: true })
|
|
592
|
-
await env.adapter.preflight?.()
|
|
593
|
-
const taskById = new Map((await env.adapter.loadTasks({ ids, split: 'test' })).map((t) => [t.id, t]))
|
|
594
|
-
const missing = ids.filter((id) => !taskById.has(id))
|
|
595
|
-
if (missing.length) throw new Error(`instances not found in SWE-bench_Verified: ${missing.join(', ')}`)
|
|
596
|
-
|
|
597
|
-
// ── Phase A (resumable): every arm decision, no judge anywhere ──
|
|
598
|
-
const done = loadRows(PHASE_A_OUT)
|
|
599
|
-
const todo = ids.filter((id) => !done.has(id))
|
|
600
|
-
if (done.size) console.log(`phase A resume: ${done.size} rows already present, ${todo.length} to run`)
|
|
601
|
-
let next = 0
|
|
602
|
-
const worker = async (): Promise<void> => {
|
|
603
|
-
while (next < todo.length) {
|
|
604
|
-
const i = next++
|
|
605
|
-
const id = todo[i] as string
|
|
606
|
-
console.log(`[A ${i + 1}/${todo.length}] ${id} …`)
|
|
607
|
-
const row = await phaseA(env, taskById.get(id) as BenchTask)
|
|
608
|
-
done.set(id, row)
|
|
609
|
-
appendFileSync(PHASE_A_OUT, `${JSON.stringify(row)}\n`)
|
|
610
|
-
const sel = row.selection ? `${row.selection.mode}@${row.selection.selectedIdx}${row.selection.movedOffFirst ? ' MOVED' : ''}` : '-'
|
|
611
|
-
console.log(
|
|
612
|
-
`[A ${i + 1}/${todo.length}] ${id} → repro=${row.reproStatus} sel=${sel} ` +
|
|
613
|
-
`sev=[${row.candidates.map((c) => c.severity).join(',')}] repairs=${row.repairs.length}(${row.repairStop ?? '-'}) ` +
|
|
614
|
-
`final=${row.finalFrom} diff=${row.finalDiff.length}b calls=${row.llmCalls} tok=${row.tokensIn}/${row.tokensOut} ` +
|
|
615
|
-
`wall=${Math.round(row.wallMs / 1000)}s${row.error ? ` ERR=${row.error.slice(0, 120)}` : ''}`,
|
|
616
|
-
)
|
|
617
|
-
}
|
|
618
|
-
}
|
|
619
|
-
await Promise.all(Array.from({ length: CONC }, () => worker()))
|
|
620
|
-
|
|
621
|
-
// ── Phase B: hidden judge, serialized, strictly after every arm decision locked ──
|
|
622
|
-
console.log(`\nphase A complete — all arm decisions locked (${new Date().toISOString()}).`)
|
|
623
|
-
const judged = loadRows(OUT)
|
|
624
|
-
if (SKIP_JUDGE) {
|
|
625
|
-
console.log('SKIP_JUDGE=1 — phase B not run; rows remain in the phase-A file only.')
|
|
626
|
-
} else {
|
|
627
|
-
console.log('phase B: official swebench judge, serialized (max_workers 1)…')
|
|
628
|
-
for (const id of ids) {
|
|
629
|
-
if (judged.has(id)) continue
|
|
630
|
-
const row = done.get(id) as Row
|
|
631
|
-
const t0 = Date.now()
|
|
632
|
-
if (!row.finalDiff.trim()) {
|
|
633
|
-
row.hiddenResolved = false
|
|
634
|
-
row.judgeSkipped = row.error ? 'error-no-patch' : 'empty-patch'
|
|
635
|
-
} else {
|
|
636
|
-
try {
|
|
637
|
-
const s = await env.adapter.judge(taskById.get(id) as BenchTask, row.finalDiff)
|
|
638
|
-
row.hiddenResolved = s.resolved ?? false
|
|
639
|
-
row.judgeDetail = String(s.detail ?? '').slice(0, 1_000)
|
|
640
|
-
} catch (e) {
|
|
641
|
-
row.hiddenResolved = false
|
|
642
|
-
row.judgeSkipped = `judge-error: ${e instanceof Error ? e.message.slice(0, 200) : String(e).slice(0, 200)}`
|
|
643
|
-
}
|
|
644
|
-
}
|
|
645
|
-
row.judgeMs = Date.now() - t0
|
|
646
|
-
judged.set(id, row)
|
|
647
|
-
appendFileSync(OUT, `${JSON.stringify(row)}\n`)
|
|
648
|
-
console.log(`[B] ${id} → resolved=${row.hiddenResolved} (${Math.round((row.judgeMs ?? 0) / 1000)}s)${row.judgeSkipped ? ` [${row.judgeSkipped}]` : ''}`)
|
|
649
|
-
}
|
|
650
|
-
}
|
|
651
|
-
|
|
652
|
-
// ── summary ──
|
|
653
|
-
const rows = [...(SKIP_JUDGE ? done : judged).values()].filter((r) => ids.includes(r.instanceId))
|
|
654
|
-
const n = rows.length
|
|
655
|
-
const resolved = rows.filter((r) => r.hiddenResolved === true).length
|
|
656
|
-
const errors = rows.filter((r) => r.error).length
|
|
657
|
-
const totIn = rows.reduce((s, r) => s + r.tokensIn, 0)
|
|
658
|
-
const totOut = rows.reduce((s, r) => s + r.tokensOut, 0)
|
|
659
|
-
const totCalls = rows.reduce((s, r) => s + r.llmCalls, 0)
|
|
660
|
-
const totHttp = rows.reduce((s, r) => s + r.httpAttempts, 0)
|
|
661
|
-
const totGuard = rows.reduce((s, r) => s + r.guardedMsgs, 0)
|
|
662
|
-
const walls = rows.map((r) => r.wallMs / 1000).sort((a, b) => a - b)
|
|
663
|
-
const q = (p: number): number => walls.length ? (walls[Math.min(walls.length - 1, Math.floor(p * (walls.length - 1)))] as number) : 0
|
|
664
|
-
const usd = (totIn / 1e6) * PRICE_IN + (totOut / 1e6) * PRICE_OUT
|
|
665
|
-
|
|
666
|
-
console.log(`\n══ per-instance (${ARM}) ══`)
|
|
667
|
-
console.log('instance | repro(src) | cand sev | sel | moved | repairs | stop | final | resolved | calls | tokIn/out | wall_s | err')
|
|
668
|
-
for (const r of [...rows].sort((a, b) => a.instanceId.localeCompare(b.instanceId))) {
|
|
669
|
-
const sel = r.selection ? `${r.selection.mode === 'repro-argmax' ? 'argmax' : 'blind'}@${r.selection.selectedIdx}` : '-'
|
|
670
|
-
console.log(
|
|
671
|
-
`${r.instanceId} | ${r.reproStatus}${r.reproSource !== 'none' ? `(${r.reproSource.replace('stage0-', '')})` : ''} | ` +
|
|
672
|
-
`[${r.candidates.map((c) => c.severity).join(',')}] | ${sel} | ${r.selection?.movedOffFirst ? 1 : 0} | ` +
|
|
673
|
-
`${r.repairs.length}${r.repairs.some((x) => x.accepted) ? '+acc' : ''} | ${r.repairStop ?? '-'} | ${r.finalFrom} | ` +
|
|
674
|
-
`${r.hiddenResolved === null ? '?' : r.hiddenResolved ? 1 : 0} | ${r.llmCalls} | ${r.tokensIn}/${r.tokensOut} | ` +
|
|
675
|
-
`${Math.round(r.wallMs / 1000)} | ${r.error ? r.error.slice(0, 60) : '-'}`,
|
|
676
|
-
)
|
|
677
|
-
}
|
|
678
|
-
|
|
679
|
-
console.log(`\n══ summary (${ARM}) ══`)
|
|
680
|
-
console.log(`n=${n} resolved(hidden)=${resolved}/${n} errorRows=${errors}`)
|
|
681
|
-
if (ARM === 'system') {
|
|
682
|
-
const armed = rows.filter((r) => r.reproStatus === 'ok')
|
|
683
|
-
const blind = rows.filter((r) => r.selection?.mode === 'blind-first')
|
|
684
|
-
const moved = rows.filter((r) => r.selection?.movedOffFirst)
|
|
685
|
-
const scored = armed.flatMap((r) => r.candidates)
|
|
686
|
-
const passCands = scored.filter((c) => c.severity === 0)
|
|
687
|
-
const fired = rows.filter((r) => r.repairs.length > 0)
|
|
688
|
-
const accepted = rows.filter((r) => r.repairs.some((x) => x.accepted))
|
|
689
|
-
const failToPass = rows.filter((r) => r.repairStop === 'repaired-pass')
|
|
690
|
-
console.log(`repro: ok=${armed.length} degraded=${rows.filter((r) => r.reproStatus.startsWith('degraded')).length} none=${rows.filter((r) => r.reproStatus === 'none').length}`)
|
|
691
|
-
console.log(`selection: repro-argmax=${armed.length} blind-first=${blind.length} | argmax moved off idx0 on ${moved.length} instance(s)`)
|
|
692
|
-
console.log(`candidates (repro-armed): ${scored.length} scored, ${passCands.length} repro-pass (${scored.length ? ((100 * passCands.length) / scored.length).toFixed(1) : 0}%)`)
|
|
693
|
-
console.log(`repair: fired on ${fired.length} instance(s), accepted(improved) on ${accepted.length}, repro fail→pass on ${failToPass.length}`)
|
|
694
|
-
const stops = new Map<string, number>()
|
|
695
|
-
for (const r of rows) if (r.repairStop) stops.set(r.repairStop, (stops.get(r.repairStop) ?? 0) + 1)
|
|
696
|
-
console.log(`repair stops: ${[...stops.entries()].map(([k, v]) => `${k}=${v}`).join(' ')}`)
|
|
697
|
-
}
|
|
698
|
-
console.log(`leak guard: ${totGuard} system/user messages checked across ${totCalls} completions — 0 trips (a trip throws)`)
|
|
699
|
-
console.log(`cost: tokens in=${totIn} out=${totOut} | llmCalls=${totCalls} httpAttempts=${totHttp} | ` +
|
|
700
|
-
`$${usd.toFixed(2)} @ $${PRICE_IN}/M in + $${PRICE_OUT}/M out (ASSUMED rate — override PRICE_IN/PRICE_OUT)`)
|
|
701
|
-
console.log(`wall per instance: min/med/p90/max = ${Math.round(q(0))}/${Math.round(q(0.5))}/${Math.round(q(0.9))}/${Math.round(q(1))}s sum=${Math.round(walls.reduce((a, b) => a + b, 0))}s`)
|
|
702
|
-
}
|
|
703
|
-
|
|
704
|
-
main().catch((e) => {
|
|
705
|
-
console.error(e instanceof Error ? (e.stack ?? e.message) : String(e))
|
|
706
|
-
process.exit(1)
|
|
707
|
-
})
|