@tangle-network/agent-bench 0.14.1 → 0.14.4

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 (40) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/package.json +6 -6
  3. package/scripts/verify-packed-consumer.mjs +0 -1
  4. package/src/atom-mcp-e2e.mts +14 -2
  5. package/src/coordination-mcp-container-reach.mts +5 -5
  6. package/src/gate.ts +1 -1
  7. package/src/mcp-mount-probe.mts +7 -5
  8. package/src/run-benchmarks.test.mts +0 -4
  9. package/src/search-bench/profiles.ts +1 -1
  10. package/src/tb-supervisor-sidecar.mts +1 -1
  11. package/tb_agents/opencode_supervisor_agent.py +2 -2
  12. package/src/browser/adapters/bad-design-audit.ts +0 -153
  13. package/src/browser/adapters/bad-design-audit.verify.ts +0 -85
  14. package/src/browser/adapters/bad.ts +0 -165
  15. package/src/browser/agent-adapter.ts +0 -145
  16. package/src/browser/process-adapter.ts +0 -146
  17. package/src/browser/run-to-spans.ts +0 -105
  18. package/src/browser/run-to-spans.verify.ts +0 -89
  19. package/src/browser/ui-reviewer.ts +0 -200
  20. package/src/browser/ui-reviewer.verify.ts +0 -94
  21. package/src/browser/verify.ts +0 -96
  22. package/src/clbench-codebase-gate.mts +0 -314
  23. package/src/clbench-context-gate.mts +0 -341
  24. package/src/commit0-env-run.mts +0 -62
  25. package/src/commit0-env.ts +0 -172
  26. package/src/commit0-gate.mts +0 -558
  27. package/src/egress-probe.mts +0 -26
  28. package/src/humaneval-repair-gate.mts +0 -182
  29. package/src/profile-coordinates.ts +0 -134
  30. package/src/run-benchmarks-report.ts +0 -66
  31. package/src/skill-sandbox-smoke.mts +0 -101
  32. package/src/supervisor-arena.mts +0 -825
  33. package/src/swe-emit-patch.mts +0 -125
  34. package/src/swe-local-proof.mts +0 -265
  35. package/src/swe-repro-calibrate.mts +0 -451
  36. package/src/swe-stream.mts +0 -1561
  37. package/src/trajectory-assemble.mjs +0 -130
  38. package/src/worker-browser.ts +0 -115
  39. package/src/worker-cad.ts +0 -470
  40. package/src/workspace-loop.mts +0 -133
@@ -1,451 +0,0 @@
1
- /**
2
- * Stage 0 of the SWE-bench frontier push — the REPRODUCTION-ORACLE CALIBRATOR
3
- * (contract: supervisor-lab/docs/results/PREREG-swe-frontier.md, Stage 0 only).
4
- *
5
- * Question it answers: can glm-5.2, given ONLY the issue text (+ up to 3 requested file reads),
6
- * author a self-contained repro script that (a) FAILS on the unpatched tree — "validity" — and
7
- * (b) PASSES after the GOLD patch — "soundness"? GATE: ≥60% of instances valid+sound (1 retry).
8
- *
9
- * No cheating by construction: the GOLD patch is used strictly script-side (applied host-side to a
10
- * COPY of the tree, then run in the jail); a hard assert refuses to send any model message that
11
- * contains gold-patch content. The repro runs in the instance's cached swebench Docker image with
12
- * the tree mounted READ-ONLY — the byte-identical invocation pattern of swe-bench-env's `run` tool
13
- * (conda testbed, cwd=/testbed, --network none, dual timeout) — so calibration measures the same
14
- * substrate Stage 1/2 will select patches on.
15
- *
16
- * cd ~/company/devops/secrets && dotenvx run -f agent-state.env -f tangle-router.env -- bash -c \
17
- * 'cd ~/code/agent-runtime-swe && OUT=/path/swe-stage0.jsonl node_modules/.bin/tsx bench/src/swe-repro-calibrate.mts'
18
- *
19
- * Env: ZAI_API_KEY (required unless CANARY_ONLY), ZAI_BASE, MODEL=glm-5.2, MAX_TOKENS=12000, TEMP=0.2,
20
- * CONC=3, REPRO_TIMEOUT=120 (s), LLM_TIMEOUT_MS=480000, IDS=comma-list override, OUT=jsonl path,
21
- * REPRO_EXEC=mount|image (execution substrate; see the constant below),
22
- * CANARY_ONLY=1 (run ONLY the per-instance execution canary — no model calls, no grading —
23
- * to decide which substrate is trustworthy per instance before spending on authoring).
24
- */
25
- import { execFile } from 'node:child_process'
26
- import { appendFileSync, cpSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
27
- import { tmpdir } from 'node:os'
28
- import { join } from 'node:path'
29
- import { promisify } from 'node:util'
30
- import type { AgenticTask, ArtifactHandle } from '@tangle-network/agent-runtime/kernel'
31
- import type { BenchTask } from './benchmarks/types'
32
- import { createSweBenchEnvironment, resolveImageForMetadata } from './swe-bench-env'
33
- import {
34
- APPLY_SENTINEL,
35
- cachedInstanceIds,
36
- extractReadRequests as extractReads,
37
- extractReproScript as extractScript,
38
- IMPORT_NAME,
39
- importCanaryScript,
40
- type JailRun,
41
- reproAuthorSystem,
42
- runPyInJail,
43
- tail,
44
- zaiChatRaw,
45
- } from './swe-jail'
46
-
47
- const exec = promisify(execFile)
48
-
49
- // ---------- config ----------
50
-
51
- const ZAI_BASE = process.env.ZAI_BASE ?? 'https://api.z.ai/api/coding/paas/v4'
52
- const ZAI_KEY = process.env.ZAI_API_KEY ?? ''
53
- const MODEL = process.env.MODEL ?? 'glm-5.2'
54
- // glm-5.2 is a reasoning model: hidden reasoning consumes max_tokens, so <8000 starves content.
55
- const MAX_TOKENS = Number(process.env.MAX_TOKENS ?? 12_000)
56
- const TEMP = Number(process.env.TEMP ?? 0.2)
57
- const CONC = Math.max(1, Math.min(3, Number(process.env.CONC ?? 3)))
58
- const REPRO_TIMEOUT_S = Number(process.env.REPRO_TIMEOUT ?? 120)
59
- const LLM_TIMEOUT_MS = Number(process.env.LLM_TIMEOUT_MS ?? 480_000)
60
- const OUT = process.env.OUT ?? 'swe-stage0.jsonl'
61
- /** Repro EXECUTION substrate. `mount` (the prereg default) mounts the fresh host clone :ro over
62
- * /testbed — the run tool's exact pattern. `image` executes against the image's OWN /testbed
63
- * (base_commit, BUILT — compiled extensions and generated version files present), applying the
64
- * gold patch in-container instead of host-side. Measured on the 23 cached instances: `mount`
65
- * kills 6 (astropy×2/matplotlib/sklearn×2/pytest) with import errors a fresh un-built clone
66
- * cannot avoid; the SAME scripts were all valid+sound under `image`. */
67
- const EXEC = process.env.REPRO_EXEC ?? 'mount'
68
- if (EXEC !== 'mount' && EXEC !== 'image') throw new Error(`REPRO_EXEC must be mount|image, got ${EXEC}`)
69
- /** Canary-only sweep: measure per-instance substrate trustworthiness (gold applied, import resolves
70
- * into the patched tree) across all instances with ZERO model calls. */
71
- const CANARY_ONLY = process.env.CANARY_ONLY === '1'
72
-
73
- // ---------- model client (swe-jail's zaiChatRaw: patient 429 ladder + empty-content retry —
74
- // the glm reasoning path starves `content` when reasoning eats max_tokens) ----------
75
-
76
- interface ChatMsg {
77
- role: 'system' | 'user' | 'assistant'
78
- content: string
79
- }
80
-
81
- interface Completion {
82
- content: string
83
- attempts: number
84
- tokensIn: number
85
- tokensOut: number
86
- }
87
-
88
- async function complete(messages: ChatMsg[]): Promise<Completion> {
89
- const { json, attempts } = await zaiChatRaw(
90
- { base: ZAI_BASE, key: ZAI_KEY, timeoutMs: LLM_TIMEOUT_MS },
91
- { model: MODEL, max_tokens: MAX_TOKENS, temperature: TEMP, messages },
92
- {
93
- name: 'swe-reproduction-calibrator',
94
- model: { provider: 'zai', default: MODEL, reasoningEffort: 'high' },
95
- prompt: { systemPrompt: AUTHOR_SYSTEM },
96
- },
97
- )
98
- const d = json as {
99
- choices?: Array<{ message?: { content?: string } }>
100
- usage?: { prompt_tokens?: number; completion_tokens?: number }
101
- }
102
- return {
103
- content: d.choices?.[0]?.message?.content ?? '',
104
- attempts,
105
- tokensIn: d.usage?.prompt_tokens ?? 0,
106
- tokensOut: d.usage?.completion_tokens ?? 0,
107
- }
108
- }
109
-
110
- // ---------- authoring protocol (one optional read round, plain-text READ: lines) ----------
111
- // The protocol constants/parsers now live in swe-jail.ts (shared with the stream driver);
112
- // behavior here is byte-identical to the in-file originals.
113
-
114
- const AUTHOR_SYSTEM = reproAuthorSystem(REPRO_TIMEOUT_S)
115
-
116
- // ---------- per-instance row ----------
117
-
118
- interface Row {
119
- instanceId: string
120
- repo: string
121
- execMode: string
122
- image: string | null
123
- imagePresent: boolean
124
- canaryExit: number | null
125
- canaryOut: string
126
- /** true = gold applied AND import resolved into the patched tree; false = this substrate cannot
127
- * grade this instance; null = repo not in IMPORT_NAME (canary not applicable). */
128
- canaryPass: boolean | null
129
- readsRequested: string[]
130
- authorCalls: number
131
- retryUsed: boolean
132
- preExitFirst: number | null
133
- preExitFinal: number | null
134
- preOut: string
135
- valid: boolean
136
- goldApplyOk: boolean | null
137
- postExit: number | null
138
- postOut: string
139
- sound: boolean
140
- validAndSound: boolean
141
- autoClass: string
142
- script: string | null
143
- scriptFirst: string | null
144
- tokensIn: number
145
- tokensOut: number
146
- wallMs: number
147
- error?: string
148
- }
149
-
150
- async function calibrateInstance(
151
- env: Awaited<ReturnType<typeof createSweBenchEnvironment>>,
152
- bt: BenchTask,
153
- ): Promise<Row> {
154
- const t0 = Date.now()
155
- const id = bt.id
156
- const row: Row = {
157
- instanceId: id, repo: '', execMode: EXEC, image: null, imagePresent: false, canaryExit: null, canaryOut: '',
158
- canaryPass: null, readsRequested: [], authorCalls: 0, retryUsed: false, preExitFirst: null, preExitFinal: null,
159
- preOut: '', valid: false, goldApplyOk: null, postExit: null, postOut: '', sound: false,
160
- validAndSound: false, autoClass: 'infra-error', script: null, scriptFirst: null,
161
- tokensIn: 0, tokensOut: 0, wallMs: 0,
162
- }
163
- let handle: ArtifactHandle | null = null
164
- let patchedDir: string | null = null
165
- try {
166
- // Metadata (issue + gold) comes from the adapter's task row, never the model path.
167
- const md = bt.metadata as Record<string, string>
168
- row.repo = md.repo
169
- const gold = String(md.patch ?? '')
170
- if (!gold.trim()) throw new Error('gold patch missing from metadata')
171
-
172
- // 1. Hard-assert the cached docker image BEFORE paying for a clone or a model call.
173
- const img = await resolveImageForMetadata(bt.metadata ?? {})
174
- if (!img.ok) {
175
- row.autoClass = 'image-missing'
176
- row.error = img.reason
177
- return row
178
- }
179
- row.image = img.tag
180
- row.imagePresent = true
181
-
182
- // 2. Open the environment: host clone at base_commit. The `mount` substrate jails against this
183
- // tree :ro; the `image` substrate uses it only for list_files/read_file during authoring — so a
184
- // canary-only image sweep skips the clone (and its network cost) entirely.
185
- let treeDir: string | null = null
186
- if (EXEC === 'mount' || !CANARY_ONLY) {
187
- const h = await env.environment.open({ id, systemPrompt: '', userPrompt: '', meta: {} } as AgenticTask)
188
- handle = h
189
- treeDir = h.id
190
- }
191
- const execTree = EXEC === 'image' ? null : treeDir
192
-
193
- // Mount substrate: apply the gold patch host-side to a COPY of the tree UP FRONT — the canary
194
- // must observe the tree exactly as the soundness run will mount it. A failed apply is terminal
195
- // before any model call is spent.
196
- if (EXEC === 'mount') {
197
- patchedDir = mkdtempSync(join(tmpdir(), 'swe-gold-'))
198
- cpSync(treeDir as string, patchedDir, { recursive: true })
199
- const goldFile = join(patchedDir, '.swe-gold.patch')
200
- writeFileSync(goldFile, gold.endsWith('\n') ? gold : `${gold}\n`)
201
- try {
202
- await exec('git', ['-C', patchedDir, 'apply', '--whitespace=nowarn', goldFile], { timeout: 60_000 })
203
- row.goldApplyOk = true
204
- } catch {
205
- // Official-harness fallback: GNU patch with fuzz.
206
- try {
207
- await exec('patch', ['-p1', '--fuzz=5', '-i', goldFile], { cwd: patchedDir, timeout: 60_000 })
208
- row.goldApplyOk = true
209
- } catch (e2) {
210
- row.goldApplyOk = false
211
- row.autoClass = 'gold-apply-failed'
212
- row.error = `gold patch failed to apply: ${(e2 as Error).message.slice(0, 200)}`
213
- return row
214
- }
215
- }
216
- rmSync(goldFile, { force: true })
217
- }
218
-
219
- // EXECUTION CANARY (mode-deciding, zero model calls): with the gold patch applied to the tree
220
- // under test, `import <pkg>` must succeed AND resolve INTO that tree. PYTHONPATH=/testbed is
221
- // already pinned by runPyInJail, so a site-packages resolution here (exit 3) means this substrate
222
- // would grade code the patch never reaches — the instance is env-unresolvable in this mode.
223
- const pkg = IMPORT_NAME[md.repo]
224
- if (pkg) {
225
- const canaryScript = importCanaryScript(pkg)
226
- const c = EXEC === 'image'
227
- ? await runPyInJail(img.tag, null, canaryScript, gold, { timeoutS: REPRO_TIMEOUT_S })
228
- : await runPyInJail(img.tag, patchedDir, canaryScript, undefined, { timeoutS: REPRO_TIMEOUT_S })
229
- if (c.infraError) throw new Error(c.infraError)
230
- row.canaryExit = c.code
231
- row.canaryOut = tail(c.out, 200)
232
- if (EXEC === 'image') {
233
- row.goldApplyOk = c.out.includes(APPLY_SENTINEL)
234
- if (!row.goldApplyOk) {
235
- row.autoClass = 'gold-apply-failed'
236
- row.error = `gold patch failed to apply in-container: ${tail(c.out, 200)}`
237
- return row
238
- }
239
- }
240
- row.canaryPass = c.code === 0
241
- if (!row.canaryPass) {
242
- row.autoClass = 'env-unresolvable'
243
- row.error = `canary: import ${pkg} did not resolve into the patched tree (exit ${c.code})`
244
- return row
245
- }
246
- }
247
- if (CANARY_ONLY) {
248
- row.autoClass = row.canaryPass === true ? 'canary-pass' : 'canary-unknown'
249
- return row
250
- }
251
- const h = handle as ArtifactHandle
252
-
253
- // 3. Author the repro: issue text + top-level listing; ONE optional read round (≤3 files).
254
- const listing = String(await env.environment.call(h, 'list_files', { dir: '' })).slice(0, 5_000)
255
- const issue = String(md.problem_statement ?? '').slice(0, 20_000)
256
- const messages: ChatMsg[] = [
257
- { role: 'system', content: AUTHOR_SYSTEM },
258
- {
259
- role: 'user',
260
- content:
261
- `Repository: ${md.repo} (checked out at the commit where the bug is PRESENT).\n\n` +
262
- `Repository file listing (top levels):\n${listing}\n\n--- Issue ---\n${issue}\n\n--- Instructions ---\n` +
263
- 'If you need to see specific source files before writing the script, reply with ONLY read requests, ' +
264
- 'one per line, at most 3, in the form:\nREAD: path/relative/to/repo/root\n' +
265
- 'Otherwise reply now with the final script in a single ```python fenced block.',
266
- },
267
- ]
268
- // Leak guard: no model message may carry gold-patch content. A distinctive added line is the sentinel.
269
- const goldMark = gold.split('\n').find((l) => l.startsWith('+') && !l.startsWith('+++') && l.trim().length > 12)?.slice(0, 80)
270
- const guardedComplete = async (msgs: ChatMsg[]): Promise<Completion> => {
271
- if (goldMark && msgs.some((m) => m.content.includes(goldMark))) {
272
- throw new Error('REFUSED: gold patch content leaked into model messages')
273
- }
274
- const c = await complete(msgs)
275
- row.authorCalls += 1
276
- row.tokensIn += c.tokensIn
277
- row.tokensOut += c.tokensOut
278
- return c
279
- }
280
-
281
- let resp = await guardedComplete(messages)
282
- let script = extractScript(resp.content)
283
- if (!script) {
284
- const reads = extractReads(resp.content)
285
- row.readsRequested = reads
286
- messages.push({ role: 'assistant', content: resp.content })
287
- if (reads.length) {
288
- const bodies: string[] = []
289
- for (const p of reads) {
290
- const c = String(await env.environment.call(h, 'read_file', { path: p }))
291
- bodies.push(`----- ${p} -----\n${c.slice(0, 12_000)}${c.length > 12_000 ? '\n…[truncated]' : ''}`)
292
- }
293
- messages.push({
294
- role: 'user',
295
- content: `${bodies.join('\n\n')}\n\nNow reply with the final script in a single \`\`\`python fenced block.`,
296
- })
297
- } else {
298
- messages.push({ role: 'user', content: 'Reply with ONLY the final Python script in a single ```python fenced block.' })
299
- }
300
- resp = await guardedComplete(messages)
301
- script = extractScript(resp.content)
302
- }
303
- if (!script) {
304
- row.autoClass = 'authoring-failed'
305
- row.error = `no script in response: ${resp.content.slice(0, 200)}`
306
- return row
307
- }
308
- row.script = script
309
-
310
- // 4. VALIDITY: the script must indicate bug-present (nonzero, non-timeout) on the UNPATCHED tree.
311
- let pre = await runPyInJail(img.tag, execTree, script, undefined, { timeoutS: REPRO_TIMEOUT_S })
312
- if (pre.infraError) throw new Error(pre.infraError)
313
- row.preExitFirst = pre.code
314
- let detected = pre.code !== 0 && !pre.timedOut
315
- if (!detected) {
316
- // One retry with feedback, per the prereg.
317
- row.retryUsed = true
318
- row.scriptFirst = script
319
- const feedback = pre.timedOut
320
- ? `your script timed out after ${REPRO_TIMEOUT_S}s on the known-buggy code. Write a faster, simpler script that still detects the bug.`
321
- : 'your script did not detect the bug on the known-buggy code: it exited 0 on the UNPATCHED repository. ' +
322
- `Its output was:\n${tail(pre.out, 1_500)}\nWrite a corrected script that FAILS (nonzero exit) on the buggy code.`
323
- messages.push({ role: 'assistant', content: `\`\`\`python\n${script}\n\`\`\`` }, { role: 'user', content: feedback })
324
- const retry = await guardedComplete(messages)
325
- const script2 = extractScript(retry.content)
326
- if (script2) {
327
- script = script2
328
- row.script = script2
329
- pre = await runPyInJail(img.tag, execTree, script2, undefined, { timeoutS: REPRO_TIMEOUT_S })
330
- if (pre.infraError) throw new Error(pre.infraError)
331
- detected = pre.code !== 0 && !pre.timedOut
332
- }
333
- }
334
- row.preExitFinal = pre.code
335
- row.preOut = tail(pre.out, 1_500)
336
- row.valid = detected
337
- if (!row.valid) {
338
- row.autoClass = pre.timedOut ? 'invalid-timeout' : 'invalid-exit0'
339
- return row
340
- }
341
-
342
- // 5. SOUNDNESS (script-side only): gold patch applied, same jail, must exit 0.
343
- let post: JailRun
344
- if (EXEC === 'image') {
345
- // Gold applied in-container to the image's built /testbed; a failed apply surfaces as exit≠0
346
- // with git's message in the output.
347
- post = await runPyInJail(img.tag, null, script, gold, { timeoutS: REPRO_TIMEOUT_S })
348
- if (post.infraError) throw new Error(post.infraError)
349
- row.goldApplyOk = post.out.includes(APPLY_SENTINEL)
350
- if (!row.goldApplyOk) {
351
- row.autoClass = 'gold-apply-failed'
352
- row.error = `gold patch failed to apply in-container: ${tail(post.out, 200)}`
353
- return row
354
- }
355
- } else {
356
- // Mount substrate: gold was already applied host-side to the canary-verified copy up front.
357
- post = await runPyInJail(img.tag, patchedDir as string, script, undefined, { timeoutS: REPRO_TIMEOUT_S })
358
- if (post.infraError) throw new Error(post.infraError)
359
- }
360
- row.postExit = post.code
361
- row.postOut = tail(post.out, 1_500)
362
- row.sound = post.code === 0
363
- row.validAndSound = row.valid && row.sound
364
- if (row.validAndSound) row.autoClass = 'ok'
365
- else if (post.timedOut) row.autoClass = 'unsound-timeout'
366
- else if (/ModuleNotFoundError|ImportError/.test(post.out)) row.autoClass = 'unsound-import-error'
367
- else row.autoClass = 'unsound-still-failing'
368
- return row
369
- } catch (e) {
370
- row.autoClass = row.autoClass === 'ok' ? 'infra-error' : row.autoClass
371
- row.error = e instanceof Error ? e.message.slice(0, 400) : String(e).slice(0, 400)
372
- return row
373
- } finally {
374
- row.wallMs = Date.now() - t0
375
- if (patchedDir) rmSync(patchedDir, { recursive: true, force: true })
376
- if (handle) await env.environment.close(handle).catch(() => {})
377
- }
378
- }
379
-
380
- // ---------- driver ----------
381
-
382
- async function main(): Promise<void> {
383
- if (!ZAI_KEY && !CANARY_ONLY) throw new Error('ZAI_API_KEY required (run under dotenvx: agent-state.env)')
384
- const ids = process.env.IDS
385
- ? process.env.IDS.split(',').map((s) => s.trim()).filter(Boolean)
386
- : await cachedInstanceIds()
387
- if (!ids.length) throw new Error('no cached sweb.eval images found and no IDS given')
388
-
389
- console.log(`═══ SWE-bench Stage 0 — ${CANARY_ONLY ? 'execution-canary sweep (no model calls)' : 'reproduction-oracle calibration'} ═══`)
390
- console.log(`model=${MODEL} base=${ZAI_BASE} maxTokens=${MAX_TOKENS} temp=${TEMP} conc=${CONC} reproTimeout=${REPRO_TIMEOUT_S}s exec=${EXEC}`)
391
- console.log(`instances (${ids.length}): ${ids.join(', ')}`)
392
- console.log(`out=${OUT}`)
393
-
394
- const env = await createSweBenchEnvironment(ids.length, { ids })
395
- // One dataset scan for all instances; per-instance metadata (issue + gold) rides the BenchTask.
396
- const taskById = new Map((await env.adapter.loadTasks({ ids, split: 'test' })).map((t) => [t.id, t]))
397
- const missing = ids.filter((id) => !taskById.has(id))
398
- if (missing.length) throw new Error(`instances not found in SWE-bench_Verified: ${missing.join(', ')}`)
399
- const rows: Row[] = []
400
- let next = 0
401
- const worker = async (): Promise<void> => {
402
- while (next < ids.length) {
403
- const i = next++
404
- const id = ids[i]
405
- console.log(`[${i + 1}/${ids.length}] ${id} …`)
406
- const row = await calibrateInstance(env, taskById.get(id) as BenchTask)
407
- rows.push(row)
408
- appendFileSync(OUT, `${JSON.stringify(row)}\n`)
409
- console.log(
410
- `[${i + 1}/${ids.length}] ${id} → ${row.autoClass}` +
411
- ` (pre=${row.preExitFinal ?? '-'} post=${row.postExit ?? '-'} retry=${row.retryUsed ? 'y' : 'n'}` +
412
- ` calls=${row.authorCalls} tok=${row.tokensIn}/${row.tokensOut} wall=${Math.round(row.wallMs / 1000)}s)` +
413
- (row.error ? ` err=${row.error.slice(0, 120)}` : ''),
414
- )
415
- }
416
- }
417
- await Promise.all(Array.from({ length: CONC }, () => worker()))
418
-
419
- // ---------- summary ----------
420
- const n = rows.length
421
- const present = rows.filter((r) => r.imagePresent).length
422
- const valid = rows.filter((r) => r.valid).length
423
- const sound = rows.filter((r) => r.validAndSound).length
424
- const retried = rows.filter((r) => r.retryUsed).length
425
- const classes = new Map<string, number>()
426
- for (const r of rows) classes.set(r.autoClass, (classes.get(r.autoClass) ?? 0) + 1)
427
-
428
- console.log('\n══ per-instance ══')
429
- console.log('instance | class | canary | pre1 | preF | valid | goldApply | post | sound | retry | calls | tokIn/out | wall_s')
430
- for (const r of [...rows].sort((a, b) => a.instanceId.localeCompare(b.instanceId))) {
431
- const canary = r.canaryPass === null ? `?(${r.canaryExit ?? '-'})` : r.canaryPass ? 'pass' : `FAIL(${r.canaryExit})`
432
- console.log(
433
- `${r.instanceId} | ${r.autoClass} | ${canary} | ${r.preExitFirst ?? '-'} | ${r.preExitFinal ?? '-'} | ` +
434
- `${r.valid ? 1 : 0} | ${r.goldApplyOk === null ? '-' : r.goldApplyOk ? 1 : 0} | ${r.postExit ?? '-'} | ${r.sound ? 1 : 0} | ` +
435
- `${r.retryUsed ? 1 : 0} | ${r.authorCalls} | ${r.tokensIn}/${r.tokensOut} | ${Math.round(r.wallMs / 1000)}`,
436
- )
437
- }
438
- console.log('\n══ summary ══')
439
- console.log(`n=${n} imagePresent=${present} canaryPass=${rows.filter((r) => r.canaryPass === true).length} valid(bug detected pre-patch)=${valid} valid+sound=${sound} retryUsed=${retried}`)
440
- console.log(`failure modes: ${[...classes.entries()].map(([k, v]) => `${k}=${v}`).join(' ')}`)
441
- if (!CANARY_ONLY) {
442
- const rate = n ? sound / n : 0
443
- const pct = (100 * rate).toFixed(1)
444
- console.log(`\nSTAGE-0 GATE (>=60% valid+sound): ${rate >= 0.6 ? 'PASS' : 'FAIL'} — ${sound}/${n} = ${pct}%`)
445
- }
446
- }
447
-
448
- main().catch((e) => {
449
- console.error(e instanceof Error ? (e.stack ?? e.message) : String(e))
450
- process.exit(1)
451
- })