@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,314 +0,0 @@
1
- /**
2
- * CL-Bench (Continual) Codebase Adaptation — verifier-grounded selector gate.
3
- *
4
- * Of CL-Bench's six domains, codebase_adaptation is the ONLY deployable checker:
5
- * its scorer applies the instance's provided `test_patch` and runs pytest in the
6
- * instance's Docker image, keying off the exit code (the rest grade against realized
7
- * outcomes the agent never has = oracles). That makes it the clean analogue of the
8
- * HumanEval gate — an INDEPENDENT deployable check (tests ≠ the answer), unlike the
9
- * CL-bench Context gate where the rubric judge IS the metric.
10
- *
11
- * Each instance is SWE-bench format (repo @ base_commit + a GitHub issue). The worker
12
- * is a real sandbox rollout (opencode clones the repo, fixes the source, writes a diff
13
- * to a file we read back — a large diff truncates in the chat stream). We score each
14
- * candidate patch with CL-Bench's OWN scorer via `clbench_codebase_judge.py` (run in
15
- * CL-Bench's venv) — verified to self-check (gold patch passes, empty fails). Two
16
- * paired arms over the same instances:
17
- * random@K — K identical-issue rollouts (the compute control)
18
- * diverse@K — K rollouts, the i-th with a strategy lens prepended (composeStrategies)
19
- * verifierGroundedSelect picks by pytest-pass; we report blind / random@k / diverse@k /
20
- * oracle@k with paired-bootstrap CIs, and write a corpus RunRecord/task the existing
21
- * `corpus-replay --selector=verifier` + `corpus-report` consume unchanged. Fail loud:
22
- * an infra-errored rollout is excluded (infraError), never scored 0.
23
- *
24
- * dotenvx run -f … -- env N=4 K=3 WORKER_MODEL=deepseek-chat CONCURRENCY=2 \
25
- * CLBENCH_DIR=/tmp/clbench-continual CORPUS=/tmp/clbench-codebase.jsonl \
26
- * tsx src/clbench-codebase-gate.mts
27
- */
28
-
29
- import { execFile } from 'node:child_process'
30
- import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
31
- import { tmpdir } from 'node:os'
32
- import { join } from 'node:path'
33
- import { promisify } from 'node:util'
34
- import { acquireSandbox } from '@tangle-network/agent-runtime/kernel'
35
- import { Sandbox } from '@tangle-network/sandbox'
36
- import { composeStrategies } from './directives'
37
- import { type AttemptRecord, appendRunRecord, buildRunRecordFromAttempts } from './corpus'
38
- import { verifierGroundedSelect } from './selector'
39
- import { type PairedLift, pairedLift, pool } from './stats.mts'
40
-
41
- const execFileAsync = promisify(execFile)
42
- const PATCH_PATH = '/tmp/solution.patch'
43
- const randomSuffix = () => Math.random().toString(36).slice(2, 10)
44
-
45
- function must(name: string): string {
46
- const v = process.env[name]
47
- if (!v) throw new Error(`env ${name} is required`)
48
- return v
49
- }
50
-
51
- interface Instance {
52
- instanceId: string
53
- repo: string
54
- baseCommit: string
55
- problemStatement: string
56
- }
57
-
58
- /** Load CL-Bench codebase_adaptation instances (SWE-bench format) from the cloned
59
- * repo's final-dataset.jsonl. Fail loud on a malformed/short record. */
60
- function loadInstances(clbenchDir: string, limit: number, offset: number): Instance[] {
61
- const path = join(clbenchDir, 'data/codebase_adaptation/final-dataset.jsonl')
62
- const text = readFileSync(path, 'utf8')
63
- const out: Instance[] = []
64
- for (const line of text.split('\n')) {
65
- if (line.trim() === '') continue
66
- const d = JSON.parse(line) as { instance_id?: string; repo?: string; base_commit?: string; problem_statement?: string }
67
- if (!d.instance_id || !d.repo || !d.base_commit || !d.problem_statement) {
68
- throw new Error(`malformed codebase_adaptation record: ${line.slice(0, 120)}`)
69
- }
70
- out.push({ instanceId: d.instance_id, repo: d.repo, baseCommit: d.base_commit, problemStatement: d.problem_statement })
71
- }
72
- if (out.length === 0) throw new Error('codebase_adaptation parsed to 0 instances')
73
- if (offset >= out.length) throw new Error(`OFFSET ${offset} >= dataset size ${out.length}`)
74
- return out.slice(offset, offset + limit)
75
- }
76
-
77
- function rolloutPrompt(inst: Instance, lens: string | undefined): string {
78
- return [
79
- lens ? `${lens}\n` : '',
80
- `Clone https://github.com/${inst.repo} into /work, then \`cd /work && git checkout ${inst.baseCommit}\`.`,
81
- '',
82
- 'Resolve this GitHub issue by editing the SOURCE only (never the tests — the evaluation re-runs its own hidden tests on a fresh clone):',
83
- '',
84
- inst.problemStatement,
85
- '',
86
- 'Work iteratively: install the package editable (`pip install -e .`), reproduce the issue, implement the fix, and re-run the existing tests until they pass.',
87
- `When done, from /work run EXACTLY:`,
88
- ` git add -A && git diff --cached -- . ':(exclude)*/test*' > ${PATCH_PATH}`,
89
- `Then stop. The patch file is the only deliverable — do NOT paste the diff in your reply.`,
90
- ].filter((s) => s !== '').join('\n')
91
- }
92
-
93
- interface ShotCfg {
94
- sandboxBaseUrl: string
95
- routerBaseUrl: string
96
- routerKey: string
97
- model: string
98
- /** in-box opencode provider. `openai-compat` (default) is the generic passthrough —
99
- * it does NOT validate the model against opencode's registry, so router-served cheap
100
- * models (deepseek-chat, moonshotai/kimi-k2.6, glm) work; `openai`/`anthropic` only
101
- * accept their registered model names (e.g. gpt-4.1). */
102
- provider: string
103
- timeoutMs: number
104
- }
105
-
106
- interface Shot {
107
- patch: string
108
- /** rollout completed and produced a (possibly empty) patch; false ⇒ infra error (excluded). */
109
- ran: boolean
110
- detail?: string
111
- }
112
-
113
- /** One fault-isolated sandbox rollout → a patch (read from the box FS). ANY rollout
114
- * error becomes a recorded infra failure (ran=false), never a throw that kills the pool. */
115
- async function runRollout(inst: Instance, lens: string | undefined, cfg: ShotCfg): Promise<Shot> {
116
- const client = new Sandbox({ baseUrl: cfg.sandboxBaseUrl, apiKey: cfg.routerKey })
117
- let box: Awaited<ReturnType<typeof acquireSandbox>> | undefined
118
- try {
119
- box = await acquireSandbox(client, {
120
- name: `clbench-cb-${inst.instanceId}-${randomSuffix()}`.replace(/[^a-zA-Z0-9_.-]/g, '_').slice(0, 60),
121
- environment: 'universal',
122
- // backend.model pins provider/model/baseUrl only — in-box model auth is the
123
- // box-provisioned OPENCODE_MODEL_API_KEY (foreign keys are 403'd at egress).
124
- backend: { type: 'opencode', model: { provider: cfg.provider, model: cfg.model, baseUrl: cfg.routerBaseUrl } },
125
- })
126
- const signal = cfg.timeoutMs > 0 ? AbortSignal.timeout(cfg.timeoutMs) : undefined
127
- for await (const _ev of box.streamPrompt(rolloutPrompt(inst, lens), signal ? { signal } : {})) {
128
- // drain; the deliverable is the patch FILE, not the stream
129
- }
130
- let patch = ''
131
- try {
132
- patch = await box.fs.read(PATCH_PATH)
133
- } catch {
134
- patch = '' // missing patch file ⇒ the agent produced nothing (a real empty, ran=true)
135
- }
136
- return { patch, ran: true }
137
- } catch (err) {
138
- return { patch: '', ran: false, detail: `rollout error: ${(err instanceof Error ? err.message : String(err)).slice(0, 200)}` }
139
- } finally {
140
- try {
141
- if (box) await box.delete()
142
- } catch {
143
- // staging reaps on expiry
144
- }
145
- }
146
- }
147
-
148
- /** Score one candidate patch with CL-Bench's deployable pytest checker via the bridge
149
- * (run in CL-Bench's venv, cwd = its repo root so `src.tasks...` resolves). Returns
150
- * pass (0/1) or null on an infra/judge failure (excluded, never scored 0). */
151
- async function judgePatch(inst: Instance, patch: string, clbenchDir: string): Promise<number | null> {
152
- if (patch.trim() === '') return 0 // empty patch is a legitimate fail, not an infra error
153
- const dir = mkdtempSync(join(tmpdir(), 'clbench-cb-'))
154
- const patchFile = join(dir, 'candidate.patch')
155
- writeFileSync(patchFile, patch)
156
- try {
157
- const { stdout } = await execFileAsync(
158
- join(clbenchDir, '.venv/bin/python'),
159
- [
160
- join(process.cwd(), 'scripts/clbench_codebase_judge.py'),
161
- '--dataset',
162
- join(clbenchDir, 'data/codebase_adaptation/final-dataset.jsonl'),
163
- '--instance-id',
164
- inst.instanceId,
165
- '--patch-file',
166
- patchFile,
167
- ],
168
- { cwd: clbenchDir, maxBuffer: 8 * 1024 * 1024, timeout: 600_000 },
169
- )
170
- const last = stdout.trim().split('\n').at(-1) ?? '{}'
171
- const verdict = JSON.parse(last) as { success?: boolean }
172
- return verdict.success ? 1 : 0
173
- } catch (err) {
174
- console.error(` judge infra error ${inst.instanceId}: ${(err instanceof Error ? err.message : String(err)).slice(0, 160)}`)
175
- return null
176
- } finally {
177
- rmSync(dir, { recursive: true, force: true })
178
- }
179
- }
180
-
181
- const pct = (x: number) => `${(x * 100).toFixed(1)}%`
182
- const pp = (x: number) => `${x >= 0 ? '+' : ''}${(x * 100).toFixed(1)}pp`
183
-
184
- async function main(): Promise<void> {
185
- const n = Number(process.env.N ?? 4)
186
- const k = Number(process.env.K ?? 3)
187
- const offset = Number(process.env.OFFSET ?? 0)
188
- const model = process.env.WORKER_MODEL ?? 'deepseek-chat'
189
- // openai-compat = generic passthrough so cheap router models resolve in-box (see ShotCfg).
190
- const provider = process.env.WORKER_PROVIDER ?? 'openai-compat'
191
- const routerBaseUrl = process.env.ROUTER_BASE ?? 'https://router.tangle.tools/v1'
192
- const routerKey = must('TANGLE_API_KEY')
193
- const sandboxBaseUrl = process.env.SANDBOX_BASE_URL ?? 'https://sandbox.tangle.tools'
194
- const clbenchDir = process.env.CLBENCH_DIR ?? '/tmp/clbench-continual'
195
- const rolloutConc = Number(process.env.CONCURRENCY ?? 3)
196
- const judgeConc = Number(process.env.JUDGE_CONCURRENCY ?? 2)
197
- const timeoutMs = process.env.SHOT_TIMEOUT_MS ? Number(process.env.SHOT_TIMEOUT_MS) : 900_000
198
- const corpusPath = process.env.CORPUS ?? '/tmp/clbench-codebase.jsonl'
199
- if (!Number.isInteger(n) || n < 1) throw new Error(`N must be a positive integer, got ${process.env.N}`)
200
- if (!Number.isInteger(k) || k < 1) throw new Error(`K must be a positive integer, got ${process.env.K}`)
201
-
202
- const cfg: ShotCfg = { sandboxBaseUrl, routerBaseUrl, routerKey, model, provider, timeoutMs }
203
- console.log(`=== CL-Bench Codebase Adaptation selector gate · N=${n} K=${k} offset=${offset} model=${provider}/${model} ===`)
204
- console.log(` sandbox=${sandboxBaseUrl} judge=CL-Bench pytest-in-Docker (deployable) clbench=${clbenchDir}`)
205
-
206
- const instances = loadInstances(clbenchDir, n, offset)
207
- console.log(`loaded ${instances.length} instance(s): ${instances.map((i) => i.instanceId).join(', ')}`)
208
-
209
- type Unit = { instIdx: number; arm: 'random' | 'diverse'; shot: number; lens: string | undefined }
210
- const units: Unit[] = []
211
- for (let ii = 0; ii < instances.length; ii += 1) {
212
- const lenses = composeStrategies('', k) // lens prefixes only ('' base ⇒ "<lens>\n\n")
213
- for (let s = 0; s < k; s += 1) {
214
- units.push({ instIdx: ii, arm: 'random', shot: s, lens: undefined })
215
- units.push({ instIdx: ii, arm: 'diverse', shot: s, lens: (lenses[s] as string).trim() })
216
- }
217
- }
218
- console.log(`\n▶ phase 1: ${units.length} rollouts (${instances.length}×${k}×2 arms) via sandbox, conc=${rolloutConc}`)
219
- const shots = await pool(units, rolloutConc, async (u) => {
220
- const inst = instances[u.instIdx] as Instance
221
- const s = await runRollout(inst, u.lens, cfg)
222
- console.log(` rollout ${inst.instanceId} ${u.arm}#${u.shot}: ${s.ran ? `patch ${s.patch.length}B` : `INFRA (${s.detail})`}`)
223
- return s
224
- })
225
-
226
- console.log(`\n▶ phase 2: judging ${shots.length} patches with the deployable checker, conc=${judgeConc}`)
227
- const passes = await pool(units, judgeConc, async (u, i) => {
228
- const shot = shots[i] as Shot
229
- if (!shot.ran) return null // infra error ⇒ excluded
230
- const inst = instances[u.instIdx] as Instance
231
- const p = await judgePatch(inst, shot.patch, clbenchDir)
232
- console.log(` judge ${inst.instanceId} ${u.arm}#${u.shot}: ${p === null ? 'INFRA' : p ? 'PASS' : 'fail'}`)
233
- return p
234
- })
235
-
236
- // Regroup; an attempt with a null pass (infra) is dropped from its arm.
237
- const byInst = instances.map(() => ({ random: [] as (number | null)[], diverse: [] as (number | null)[], rPatch: [] as string[], dPatch: [] as string[] }))
238
- units.forEach((u, i) => {
239
- const grp = byInst[u.instIdx] as { random: (number | null)[]; diverse: (number | null)[]; rPatch: string[]; dPatch: string[] }
240
- const pass = passes[i] as number | null
241
- const patch = (shots[i] as Shot).patch
242
- if (u.arm === 'random') { grp.random[u.shot] = pass; grp.rPatch[u.shot] = patch } else { grp.diverse[u.shot] = pass; grp.dPatch[u.shot] = patch }
243
- })
244
-
245
- // Per-instance {0,1} outcomes; instances with no valid attempt in BOTH arms are excluded.
246
- const blind: number[] = []
247
- const randomAtK: number[] = []
248
- const diverseAtK: number[] = []
249
- const oracleAtK: number[] = []
250
- let excluded = 0
251
- for (const grp of byInst) {
252
- const rValid = grp.random.filter((p): p is number => p !== null && p !== undefined)
253
- const dValid = grp.diverse.filter((p): p is number => p !== null && p !== undefined)
254
- if (rValid.length === 0 || dValid.length === 0) { excluded += 1; continue }
255
- blind.push(rValid[0] as number)
256
- randomAtK.push(rValid[verifierGroundedSelect(rValid)] as number)
257
- diverseAtK.push(dValid[verifierGroundedSelect(dValid)] as number)
258
- oracleAtK.push(dValid.some((p) => p > 0) ? 1 : 0)
259
- }
260
- const rate = (xs: number[]) => (xs.length === 0 ? 0 : xs.reduce((s, x) => s + x, 0) / xs.length)
261
-
262
- console.log(`\n${'='.repeat(78)}`)
263
- console.log(`RESULTS · CL-Bench Codebase Adaptation · n=${blind.length} scored (${excluded} excluded) · k=${k} · model=${model}`)
264
- console.log('='.repeat(78))
265
- console.log(` blind pass@1 ${pct(rate(blind))}`)
266
- console.log(` random@k (verifier-pick) ${pct(rate(randomAtK))}`)
267
- console.log(` diverse@k (verifier-pick) ${pct(rate(diverseAtK))}`)
268
- console.log(` oracle@k (diverse, any) ${pct(rate(oracleAtK))}`)
269
- if (blind.length >= 2) {
270
- const row = (label: string, l: PairedLift) =>
271
- console.log(` ${label.padEnd(34)} ${pp(l.point).padStart(7)} CI [${pp(l.low)}, ${pp(l.high)}] (paired ${l.pairs}, discordant ${l.discordant})`)
272
- console.log(`\n PAIRED LIFTS (95% bootstrap CI):`)
273
- row('random@k − blind (compute)', pairedLift(blind, randomAtK))
274
- row('diverse@k − random@k (verifier)', pairedLift(randomAtK, diverseAtK))
275
- row('diverse@k − blind (total)', pairedLift(blind, diverseAtK))
276
- } else {
277
- console.log('\n (n<2 scored — paired CIs need ≥2; this is a plumbing smoke, not a signal)')
278
- }
279
-
280
- // Corpus: random@k arm, ranked by the deployable pytest verifier.
281
- for (let ii = 0; ii < instances.length; ii += 1) {
282
- const inst = instances[ii] as Instance
283
- const grp = byInst[ii] as { random: (number | null)[]; rPatch: string[] }
284
- const attempts: AttemptRecord[] = grp.random.map((p, round) => ({
285
- round,
286
- prompt: 'clbench-codebase-rollout',
287
- output: (grp.rPatch[round] ?? '').slice(0, 4000),
288
- ...(p === null ? { error: 'infra' } : { valid: p > 0, score: p }),
289
- eventCount: 1,
290
- eventTypes: { 'sandbox.stream': 1 },
291
- traceTail: (grp.rPatch[round] ?? '').slice(-600),
292
- }))
293
- const validPasses = grp.random.filter((p): p is number => p !== null && p !== undefined)
294
- const record = buildRunRecordFromAttempts(attempts, {
295
- benchmark: 'clbench-codebase',
296
- instanceId: inst.instanceId,
297
- condition: `random@${k}`,
298
- model,
299
- // blindResolved reads off the FIRST non-null score (== full pass), not
300
- // attempts[0].valid — a partial-credit first shot is valid but not "blind
301
- // resolved". Pass it explicitly so the helper preserves the exact value.
302
- blindResolved: validPasses[0] === 1,
303
- resolved: validPasses.some((p) => p > 0),
304
- infraError: validPasses.length === 0,
305
- })
306
- await appendRunRecord(corpusPath, record)
307
- }
308
- console.log(`\n=== wrote ${instances.length} task(s) → ${corpusPath} · gate: tsx src/corpus-replay.mts ${corpusPath} --selector=verifier ===`)
309
- }
310
-
311
- main().catch((err) => {
312
- console.error(`clbench-codebase-gate: ${err instanceof Error ? err.message : String(err)}`)
313
- process.exit(1)
314
- })
@@ -1,341 +0,0 @@
1
- /**
2
- * CL-bench (Context Learning) deployable-selector gate — Tencent/Fudan's CL-bench
3
- * (arXiv:2602.03587) repurposed for our verifier-grounded selector question.
4
- *
5
- * CL-bench asks whether a model can learn NEW knowledge from in-context material
6
- * (a rule book, a framework doc, a conversation) at inference time: each record is
7
- * a `messages` conversation (system + context-laden turns, the final turn the task)
8
- * graded against expert `rubrics`. The official metric is BINARY — a task is solved
9
- * only if the response passes EVERY rubric (avg 63 rubrics/task). We keep that binary
10
- * as `resolved`, but the per-rubric pass-count gives a CONTINUOUS score (fraction of
11
- * rubrics satisfied) — the within-task graded variance a selector needs, which the
12
- * deterministic-but-pass/fail benches (aec) lacked.
13
- *
14
- * The CHECKER is the benchmark's own rubric judge (an LLM, per CL-bench's eval.py),
15
- * run by us at inference time — deployable, but NOT deterministic, so treat the judge
16
- * as a noisy verifier: we rank by the rubric FRACTION (variance-reduced over many
17
- * rubrics), not the binary, and the judge model + temperature are pinned for
18
- * test-retest stability. This is the LLM-judge analogue of the HumanEval Docker gate;
19
- * read a positive result as "a deployable rubric-fraction verifier captures selection
20
- * value on a hard context-learning domain", scoped by judge noise.
21
- *
22
- * Router-only (no sandbox): worker + judge are both router chat calls. Two paired arms
23
- * over the same tasks, each "shot" = one stateless completion of the final turn:
24
- * random@K — K completions over the unmodified conversation
25
- * diverse@K — K completions, the i-th with a strategy lens prepended to the system turn
26
- * verifierGroundedSelect ranks the K shots by rubric fraction. Metrics are reported on
27
- * BOTH the continuous fraction (the gate-relevant signal) and the official binary.
28
- * Writes a corpus RunRecord/task (condition random@k) so `corpus-replay --selector` and
29
- * `corpus-report` consume it unchanged. Fail loud.
30
- *
31
- * dotenvx run -f … -- env N=20 K=4 WORKER_MODEL=deepseek-chat JUDGE_MODEL=deepseek-chat \
32
- * CORPUS=/tmp/clbench-ctx.jsonl tsx src/clbench-context-gate.mts
33
- */
34
-
35
- import { execFileSync } from 'node:child_process'
36
- import { existsSync, readFileSync } from 'node:fs'
37
- import { composeStrategies } from './directives'
38
- import { type AttemptRecord, appendRunRecord, buildRunRecordFromAttempts } from './corpus'
39
- import {
40
- benchRouterProfile,
41
- type BenchRouterTarget,
42
- runBenchRouterTurn,
43
- withBenchProfile,
44
- } from './router-turn'
45
- import { selfConsistencySelect, verifierGroundedSelect } from './selector'
46
- import { type PairedLift, pairedLift, pool } from './stats.mts'
47
-
48
- const datasetUrl = 'https://huggingface.co/datasets/tencent/CL-bench/resolve/main/CL-bench.jsonl'
49
-
50
- function must(name: string): string {
51
- const v = process.env[name]
52
- if (!v) throw new Error(`env ${name} is required`)
53
- return v
54
- }
55
-
56
- interface ChatMessage extends Readonly<Record<string, unknown>> {
57
- role: string
58
- content: string
59
- }
60
-
61
- interface CtxTask {
62
- id: string
63
- messages: ChatMessage[]
64
- rubrics: string[]
65
- category: string
66
- }
67
-
68
- /** Fetch the first `count` lines of the (large, ~300MB) CL-bench JSONL via a piped
69
- * `curl | head` so a smoke pulls only a few records, then slice [offset, offset+limit].
70
- * A local cached file (CLBENCH_CTX_FILE) short-circuits the fetch for powered runs.
71
- * Fail loud on a malformed record — a silently-short task set would poison the gate. */
72
- function loadCtxTasks(limit: number, offset: number): CtxTask[] {
73
- const need = offset + limit
74
- // Fetch a 2-line buffer past `need`: on CL-bench's huge multi-KB records, `head`
75
- // closing the pipe can emit a TRUNCATED final line (SIGPIPE mid-write) → invalid
76
- // JSON. Fetching need+2 and parsing only the first `need` complete lines makes the
77
- // truncated tail land in the discarded buffer.
78
- const fetchN = need + 2
79
- let raw: string
80
- const cached = process.env.CLBENCH_CTX_FILE
81
- if (cached) {
82
- if (!existsSync(cached)) throw new Error(`CLBENCH_CTX_FILE not found: ${cached}`)
83
- raw = execFileSync('bash', ['-c', `head -n ${fetchN} ${JSON.stringify(cached)}`], { maxBuffer: 1 << 30 }).toString('utf8')
84
- } else {
85
- // -fsSL: fail on HTTP error, follow redirects (HF resolve 302s to the CDN). curl's
86
- // SIGPIPE (exit 23) when head closes is benign — suppress its stderr; a real fetch
87
- // failure surfaces as 0 parsed tasks below.
88
- raw = execFileSync('bash', ['-c', `curl -fsSL ${JSON.stringify(datasetUrl)} 2>/dev/null | head -n ${fetchN}`], {
89
- maxBuffer: 1 << 30,
90
- }).toString('utf8')
91
- }
92
- const tasks: CtxTask[] = []
93
- // Only the first `need` lines are guaranteed complete (the +2 absorbs head's tail).
94
- const lines = raw.split('\n').filter((l) => l.trim() !== '').slice(0, need)
95
- for (const line of lines) {
96
- const d = JSON.parse(line) as {
97
- messages?: ChatMessage[]
98
- rubrics?: unknown[]
99
- metadata?: { task_id?: string; context_category?: string }
100
- }
101
- const messages = d.messages
102
- const taskId = d.metadata?.task_id
103
- if (!Array.isArray(messages) || messages.length === 0 || !taskId) {
104
- throw new Error(`malformed CL-bench record: ${line.slice(0, 120)}`)
105
- }
106
- // Rubrics are strings or {rubric_criteria} objects (mirrors eval.py's build_rubrics_text).
107
- const rubrics = (d.rubrics ?? []).map((r) =>
108
- typeof r === 'string' ? r : String((r as { rubric_criteria?: string }).rubric_criteria ?? '').trim(),
109
- ).filter((r) => r.length > 0)
110
- if (rubrics.length === 0) throw new Error(`CL-bench record ${taskId} has no rubrics`)
111
- tasks.push({ id: taskId, messages, rubrics, category: d.metadata?.context_category ?? 'Unknown' })
112
- }
113
- if (tasks.length === 0) throw new Error('CL-bench parsed to 0 tasks')
114
- if (offset >= tasks.length) throw new Error(`OFFSET ${offset} >= fetched size ${tasks.length}`)
115
- return tasks.slice(offset, offset + limit)
116
- }
117
-
118
- /** Apply a diversity strategy lens to a conversation by prepending it to the system
119
- * turn (or, if none, inserting a system turn). The non-system context turns — which
120
- * carry the in-context knowledge the task is about — are never mutated. */
121
- function diversifyMessages(messages: ChatMessage[], lensSystem: string, baseSystem: string): ChatMessage[] {
122
- if (messages[0]?.role === 'system') {
123
- return [{ role: 'system', content: lensSystem }, ...messages.slice(1)]
124
- }
125
- return [{ role: 'system', content: composeStrategies(baseSystem, 1)[0] as string }, ...messages]
126
- }
127
-
128
- const judgePrompt = (rubricsText: string, modelOutput: string): string =>
129
- 'You are a rigorous, strict grading teacher. Grade the student response against the 【Rubrics】, ' +
130
- 'checking EACH requirement independently.\n\n' +
131
- `【Rubrics】:\n${rubricsText}\n` +
132
- `【Student Response】:\n${modelOutput}\n\n` +
133
- 'Output ONLY this JSON (no other text):\n' +
134
- '{\n "status": ["yes" or "no", ... one per rubric, in order],\n "all_pass": 0 or 1\n}\n'
135
-
136
- interface RubricVerdict {
137
- /** fraction of rubrics satisfied (0..1) — the continuous within-task signal. */
138
- fraction: number
139
- /** official binary: every rubric satisfied. */
140
- allPass: boolean
141
- /** rubric count actually graded (for diagnostics). */
142
- graded: number
143
- }
144
-
145
- function parseJudge(reply: string, rubricCount: number): RubricVerdict {
146
- let text = reply.trim()
147
- if (text.startsWith('```json')) text = text.slice(7)
148
- if (text.startsWith('```')) text = text.slice(3)
149
- if (text.endsWith('```')) text = text.slice(0, -3)
150
- const obj = JSON.parse(text.trim()) as { status?: unknown[]; all_pass?: unknown }
151
- const status = Array.isArray(obj.status) ? obj.status : []
152
- const yes = status.filter((s) => String(s).trim().toLowerCase() === 'yes').length
153
- const graded = status.length > 0 ? status.length : rubricCount
154
- const fraction = graded > 0 ? yes / graded : 0
155
- // Trust an explicit all_pass when given; else derive from the per-rubric list.
156
- const allPass = obj.all_pass === 1 || obj.all_pass === '1' || (status.length === rubricCount && yes === rubricCount && rubricCount > 0)
157
- return { fraction, allPass, graded }
158
- }
159
-
160
- /** Grade one completion with the rubric judge. A judge API/parse failure is a real
161
- * zero (the response could not be validated) — surfaced, never masked. */
162
- async function judgeRubrics(cfg: BenchRouterTarget, task: CtxTask, output: string): Promise<RubricVerdict> {
163
- if (!output.trim()) return { fraction: 0, allPass: false, graded: 0 }
164
- const rubricsText = task.rubrics.map((r, i) => `${i + 1}. ${r}`).join('\n')
165
- // Fault-isolate the judge: a transient router failure (after retries) or an
166
- // unparseable judge reply scores this attempt 0 (eval.py's convention), it must
167
- // NOT throw — one bad grade would otherwise crash the whole N×K×2 run. graded=0
168
- // marks it as judge-failed so it's distinguishable from a real 0/N rubric pass.
169
- try {
170
- const res = await runBenchRouterTurn(
171
- {
172
- routerBaseUrl: cfg.routerBaseUrl,
173
- routerKey: cfg.routerKey,
174
- profile: withBenchProfile(cfg.profile, {
175
- name: 'clbench-rubric-judge',
176
- temperature: 0,
177
- }),
178
- },
179
- judgePrompt(rubricsText, output),
180
- )
181
- return parseJudge(res.finalText, task.rubrics.length)
182
- } catch {
183
- return { fraction: 0, allPass: false, graded: 0 }
184
- }
185
- }
186
-
187
- const pct = (x: number) => `${(x * 100).toFixed(1)}%`
188
- const pp = (x: number) => `${x >= 0 ? '+' : ''}${(x * 100).toFixed(1)}pp`
189
-
190
- interface Shot {
191
- output: string
192
- verdict: RubricVerdict
193
- }
194
-
195
- async function main(): Promise<void> {
196
- const n = Number(process.env.N ?? 20)
197
- const k = Number(process.env.K ?? 4)
198
- const offset = Number(process.env.OFFSET ?? 0)
199
- const model = process.env.WORKER_MODEL ?? 'deepseek-chat'
200
- const judgeModel = process.env.JUDGE_MODEL ?? model
201
- const routerBaseUrl = process.env.ROUTER_BASE ?? 'https://router.tangle.tools/v1'
202
- const routerKey = must('TANGLE_API_KEY')
203
- const solveConcurrency = Number(process.env.CONCURRENCY ?? 6)
204
- const corpusPath = process.env.CORPUS ?? '/tmp/clbench-ctx.jsonl'
205
- if (!Number.isInteger(n) || n < 1) throw new Error(`N must be a positive integer, got ${process.env.N}`)
206
- if (!Number.isInteger(k) || k < 1) throw new Error(`K must be a positive integer, got ${process.env.K}`)
207
-
208
- const workerCfg: BenchRouterTarget = {
209
- routerBaseUrl,
210
- routerKey,
211
- profile: benchRouterProfile('clbench-context-worker', model, {
212
- temperature: Number(process.env.TEMPERATURE ?? '0.8'),
213
- }),
214
- }
215
- const judgeCfg: BenchRouterTarget = {
216
- routerBaseUrl,
217
- routerKey,
218
- profile: benchRouterProfile('clbench-rubric-judge', judgeModel, { temperature: 0 }),
219
- }
220
-
221
- console.log(`=== CL-bench (Context Learning) selector gate · N=${n} K=${k} offset=${offset} ===`)
222
- console.log(` worker=${model} judge=${judgeModel} (rubric-fraction verifier) router=${routerBaseUrl}`)
223
- console.log(' regime: STATELESS single completions — selector no-self-correction LOWER BOUND, judge is an LLM (noisy verifier)')
224
-
225
- const tasks = loadCtxTasks(n, offset)
226
- console.log(`loaded ${tasks.length} task(s); rubrics/task: ${tasks.map((t) => t.rubrics.length).join(',')}`)
227
-
228
- type Unit = { taskIdx: number; arm: 'random' | 'diverse'; shot: number; messages: ChatMessage[] }
229
- const units: Unit[] = []
230
- for (let ti = 0; ti < tasks.length; ti += 1) {
231
- const task = tasks[ti] as CtxTask
232
- const baseSystem = task.messages[0]?.role === 'system' ? (task.messages[0] as ChatMessage).content : 'You are a helpful assistant.'
233
- const lenses = composeStrategies(baseSystem, k)
234
- for (let s = 0; s < k; s += 1) {
235
- units.push({ taskIdx: ti, arm: 'random', shot: s, messages: task.messages })
236
- units.push({ taskIdx: ti, arm: 'diverse', shot: s, messages: diversifyMessages(task.messages, lenses[s] as string, baseSystem) })
237
- }
238
- }
239
- console.log(`\n▶ solving ${units.length} attempts (${tasks.length} tasks × ${k} shots × 2 arms) via router, conc=${solveConcurrency}`)
240
- const outputs = await pool(units, solveConcurrency, async (u) => {
241
- const system = u.messages.find((message) => message.role === 'system')?.content
242
- const res = await runBenchRouterTurn(
243
- {
244
- routerBaseUrl: workerCfg.routerBaseUrl,
245
- routerKey: workerCfg.routerKey,
246
- profile: withBenchProfile(workerCfg.profile, {
247
- name: 'clbench-context-worker',
248
- ...(system ? { systemPrompt: system } : {}),
249
- }),
250
- },
251
- { messages: u.messages.filter((message) => message.role !== 'system') },
252
- )
253
- return res.finalText
254
- })
255
-
256
- console.log(`▶ grading ${outputs.length} completions with the rubric judge (${judgeModel}), conc=${solveConcurrency}`)
257
- const verdicts = await pool(units, solveConcurrency, (u, i) => judgeRubrics(judgeCfg, tasks[u.taskIdx] as CtxTask, outputs[i] as string))
258
-
259
- // Regroup into per-task arms, shot order preserved.
260
- const byTask = tasks.map(() => ({ random: [] as Shot[], diverse: [] as Shot[] }))
261
- units.forEach((u, i) => {
262
- const shot: Shot = { output: outputs[i] as string, verdict: verdicts[i] as RubricVerdict }
263
- const grp = byTask[u.taskIdx] as { random: Shot[]; diverse: Shot[] }
264
- if (u.arm === 'random') grp.random[u.shot] = shot
265
- else grp.diverse[u.shot] = shot
266
- })
267
-
268
- // Per-task aligned metrics, on BOTH the continuous fraction and the official binary.
269
- const fr = { blind: [] as number[], random: [] as number[], diverse: [] as number[], oracle: [] as number[], sc: [] as number[] }
270
- const bin = { blind: [] as number[], random: [] as number[], diverse: [] as number[], oracle: [] as number[] }
271
- for (const grp of byTask) {
272
- const rFr = grp.random.map((s) => s.verdict.fraction)
273
- const dFr = grp.diverse.map((s) => s.verdict.fraction)
274
- const rIdx = verifierGroundedSelect(rFr) // rank random shots by rubric fraction
275
- const dIdx = verifierGroundedSelect(dFr)
276
- const scIdx = selfConsistencySelect(grp.diverse.map((s) => s.output))
277
- fr.blind.push((grp.random[0] as Shot).verdict.fraction)
278
- fr.random.push((grp.random[rIdx] as Shot).verdict.fraction)
279
- fr.diverse.push((grp.diverse[dIdx] as Shot).verdict.fraction)
280
- fr.oracle.push(Math.max(...dFr))
281
- fr.sc.push((grp.diverse[scIdx] as Shot).verdict.fraction)
282
- bin.blind.push((grp.random[0] as Shot).verdict.allPass ? 1 : 0)
283
- bin.random.push((grp.random[rIdx] as Shot).verdict.allPass ? 1 : 0)
284
- bin.diverse.push((grp.diverse[dIdx] as Shot).verdict.allPass ? 1 : 0)
285
- bin.oracle.push(dFr.some((_, j) => (grp.diverse[j] as Shot).verdict.allPass) ? 1 : 0)
286
- }
287
- const rate = (xs: number[]) => xs.reduce((s, x) => s + x, 0) / xs.length
288
-
289
- console.log(`\n${'='.repeat(78)}`)
290
- console.log(`RESULTS · CL-bench Context Learning · n=${tasks.length} · k=${k} · worker=${model} · judge=${judgeModel}`)
291
- console.log('='.repeat(78))
292
- console.log(' — rubric FRACTION (continuous within-task signal, the gate-relevant metric) —')
293
- console.log(` blind (shot 0) ${pct(rate(fr.blind))}`)
294
- console.log(` random@k (verifier-pick) ${pct(rate(fr.random))}`)
295
- console.log(` diverse@k (verifier-pick) ${pct(rate(fr.diverse))}`)
296
- console.log(` oracle@k (max fraction) ${pct(rate(fr.oracle))}`)
297
- console.log(` self-consistency@k ${pct(rate(fr.sc))}`)
298
- console.log(' — official BINARY all-rubrics-pass (solving rate) —')
299
- console.log(` blind ${pct(rate(bin.blind))} random@k ${pct(rate(bin.random))} diverse@k ${pct(rate(bin.diverse))} oracle@k ${pct(rate(bin.oracle))}`)
300
-
301
- const row = (label: string, l: PairedLift) =>
302
- console.log(` ${label.padEnd(36)} ${pp(l.point).padStart(7)} CI [${pp(l.low)}, ${pp(l.high)}] (paired ${l.pairs}, discordant ${l.discordant})`)
303
- console.log(`\n PAIRED LIFTS on rubric fraction (95% bootstrap CI, B=10000):`)
304
- row('random@k − blind (compute)', pairedLift(fr.blind, fr.random))
305
- row('diverse@k − random@k (verifier)', pairedLift(fr.random, fr.diverse))
306
- row('diverse@k − blind (total)', pairedLift(fr.blind, fr.diverse))
307
- row('verifier-pick − sc-pick (diverse)', pairedLift(fr.sc, fr.diverse))
308
- const ceiling = pairedLift(fr.random, fr.oracle)
309
- row('oracle@k − random@k (ceiling)', ceiling)
310
-
311
- // Corpus: one RunRecord/task for the random@k arm, ranked by the rubric-fraction
312
- // verifier — `corpus-replay --selector=verifier` + `corpus-report` consume it.
313
- for (let ti = 0; ti < tasks.length; ti += 1) {
314
- const task = tasks[ti] as CtxTask
315
- const grp = byTask[ti] as { random: Shot[]; diverse: Shot[] }
316
- const attempts: AttemptRecord[] = grp.random.map((s, round) => ({
317
- round,
318
- prompt: 'clbench-context',
319
- output: s.output.slice(0, 4000),
320
- valid: s.verdict.allPass,
321
- score: s.verdict.fraction,
322
- eventCount: 1,
323
- eventTypes: { 'router.chat': 1 },
324
- traceTail: s.output.slice(-600),
325
- }))
326
- const record = buildRunRecordFromAttempts(attempts, {
327
- benchmark: 'clbench-context',
328
- instanceId: task.id,
329
- condition: `random@${k}`,
330
- model,
331
- infraError: false,
332
- })
333
- await appendRunRecord(corpusPath, record)
334
- }
335
- console.log(`\n=== wrote ${tasks.length} task(s) → ${corpusPath} · gate: tsx src/corpus-replay.mts ${corpusPath} --selector=verifier ===`)
336
- }
337
-
338
- main().catch((err) => {
339
- console.error(`clbench-context-gate: ${err instanceof Error ? err.message : String(err)}`)
340
- process.exit(1)
341
- })