@tangle-network/agent-bench 0.3.6 → 0.3.7

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 (91) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/dist/adapters.js +2 -2
  3. package/dist/benchmarks/humaneval.d.ts +10 -1
  4. package/dist/benchmarks/humaneval.js +5 -3
  5. package/dist/{chunk-PPYSEKFM.js → chunk-5H5XV76F.js} +73 -15
  6. package/dist/chunk-5H5XV76F.js.map +1 -0
  7. package/dist/{chunk-5SBJCB6W.js → chunk-PWQVGAJB.js} +2 -2
  8. package/dist/index.js +2 -2
  9. package/package.json +5 -4
  10. package/scripts/run-package-tests.mjs +30 -8
  11. package/scripts/verify-pier-agent.mts +1 -0
  12. package/src/benchmarks/humaneval.test.mts +122 -0
  13. package/src/benchmarks/humaneval.ts +100 -27
  14. package/src/david-attribution.mts +78 -0
  15. package/src/david-goliath.mts +149 -0
  16. package/src/hev-improve.mts +25 -6
  17. package/src/humaneval-object-ablation.mts +201 -0
  18. package/src/live-improve-campaign-mbpp.mts +641 -0
  19. package/src/live-improve-campaign.mts +500 -0
  20. package/src/mbpp-structural.mts +12 -7
  21. package/src/stream-observe.py +45 -0
  22. package/src/stream-observe.tpl.html +247 -0
  23. package/src/supervisor-arena.mts +816 -0
  24. package/src/swe-arena/analyze.ts +211 -0
  25. package/src/swe-arena/arms.ts +788 -0
  26. package/src/swe-arena/bootstrap-meta.mts +188 -0
  27. package/src/swe-arena/bootstrap-meta.test.mts +51 -0
  28. package/src/swe-arena/calibrate.ts +116 -0
  29. package/src/swe-arena/capabilities.mts +76 -0
  30. package/src/swe-arena/capabilities.test.mts +57 -0
  31. package/src/swe-arena/capacity.ts +194 -0
  32. package/src/swe-arena/cell-evidence.mts +405 -0
  33. package/src/swe-arena/cell-evidence.test.mts +248 -0
  34. package/src/swe-arena/diagnosis-ensemble.test.mts +210 -0
  35. package/src/swe-arena/diagnosis-ensemble.ts +520 -0
  36. package/src/swe-arena/execution.test.mts +1170 -0
  37. package/src/swe-arena/fixtures/analyze.py +80 -0
  38. package/src/swe-arena/fixtures/excludes.txt +8 -0
  39. package/src/swe-arena/fixtures/gen1-salvage/README.md +45 -0
  40. package/src/swe-arena/fixtures/gen1-salvage/cand0-e6d7361.diff +116 -0
  41. package/src/swe-arena/fixtures/gen1-salvage/cand1-76a8590.diff +293 -0
  42. package/src/swe-arena/fixtures/holdout-preregister.log +12 -0
  43. package/src/swe-arena/fixtures/holdout.json +44 -0
  44. package/src/swe-arena/fixtures/instances.json +146 -0
  45. package/src/swe-arena/fixtures/ledger.jsonl +12 -0
  46. package/src/swe-arena/fixtures/patches/pallets__flask-5014.solo.patch +36 -0
  47. package/src/swe-arena/fixtures/patches/pydata__xarray-4687.sup.patch +33 -0
  48. package/src/swe-arena/fixtures/rejudge.jsonl +15 -0
  49. package/src/swe-arena/fixtures/rematch.jsonl +3 -0
  50. package/src/swe-arena/fixtures/rematch2.jsonl +3 -0
  51. package/src/swe-arena/fixtures/rematch3.jsonl +3 -0
  52. package/src/swe-arena/fixtures/sup-journal-true.json +19 -0
  53. package/src/swe-arena/fixtures/verify/astropy__astropy-13033.sh +48 -0
  54. package/src/swe-arena/fixtures/verify/django__django-11532.sh +50 -0
  55. package/src/swe-arena/fixtures/verify/matplotlib__matplotlib-20826.sh +76 -0
  56. package/src/swe-arena/fixtures/verify/pydata__xarray-4687.sh +44 -0
  57. package/src/swe-arena/fixtures/verify/pytest-dev__pytest-6197.sh +32 -0
  58. package/src/swe-arena/fixtures/verify/sphinx-doc__sphinx-9658.sh +51 -0
  59. package/src/swe-arena/fixtures/worker-tokens.json +42 -0
  60. package/src/swe-arena/fixtures.ts +104 -0
  61. package/src/swe-arena/holdout-certify.mts +408 -0
  62. package/src/swe-arena/holdout-certify.test.mts +160 -0
  63. package/src/swe-arena/judge-child.mts +37 -0
  64. package/src/swe-arena/manifest.mts +293 -0
  65. package/src/swe-arena/manifest.test.mts +169 -0
  66. package/src/swe-arena/materialize.ts +142 -0
  67. package/src/swe-arena/outer-loop.mts +2145 -0
  68. package/src/swe-arena/outer-loop.test.mts +696 -0
  69. package/src/swe-arena/parity.test.mts +87 -0
  70. package/src/swe-arena/proc.test.mts +174 -0
  71. package/src/swe-arena/proc.ts +260 -0
  72. package/src/swe-arena/profiles/default-author.profile.json +4 -0
  73. package/src/swe-arena/proposer-fanout.mts +489 -0
  74. package/src/swe-arena/proposer-fanout.test.mts +372 -0
  75. package/src/swe-arena/reconcile.ts +0 -0
  76. package/src/swe-arena/replay.mts +183 -0
  77. package/src/swe-arena/replay.test.mts +300 -0
  78. package/src/swe-arena/run-experiment.mts +361 -0
  79. package/src/swe-arena/run-supervisor.mjs +297 -0
  80. package/src/swe-arena/run-supervisor.test.mts +498 -0
  81. package/src/swe-arena/serialized-judge.ts +414 -0
  82. package/src/swe-arena/types.ts +166 -0
  83. package/src/swe-code-improve.mts +328 -0
  84. package/src/swe-emit-patch.mts +104 -0
  85. package/src/swe-improve.mts +232 -0
  86. package/src/swe-jail.ts +2 -2
  87. package/src/swe-local-proof.mts +169 -0
  88. package/src/swe-repro-calibrate.mts +446 -0
  89. package/src/swe-stream.mts +1497 -0
  90. package/dist/chunk-PPYSEKFM.js.map +0 -1
  91. /package/dist/{chunk-5SBJCB6W.js.map → chunk-PWQVGAJB.js.map} +0 -0
@@ -0,0 +1,160 @@
1
+ import { mkdtemp, rm, writeFile } from 'node:fs/promises'
2
+ import { tmpdir } from 'node:os'
3
+ import { join } from 'node:path'
4
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest'
5
+ import type { ReplicateRun } from './cell-evidence.mts'
6
+ import {
7
+ assertHoldoutBaselineMap,
8
+ decideHoldoutCertification,
9
+ DEFAULT_HOLDOUT_REPS,
10
+ holdoutReps,
11
+ loadHoldoutCells,
12
+ type HoldoutCellRow,
13
+ } from './holdout-certify.mts'
14
+
15
+ const IIDS = ['a', 'b', 'c']
16
+
17
+ const runs = (spec: Record<string, Array<boolean | null>>): ReplicateRun[] =>
18
+ Object.entries(spec).flatMap(([iid, reps]) => reps.map((resolved) => ({ iid, resolved })))
19
+
20
+ describe('holdoutReps', () => {
21
+ it('defaults to 2 — the gen-2 postmortem protocol', () => {
22
+ expect(DEFAULT_HOLDOUT_REPS).toBe(2)
23
+ expect(holdoutReps({})).toBe(2)
24
+ expect(holdoutReps({ holdoutRepsPerInstance: 3 })).toBe(3)
25
+ })
26
+
27
+ it('rejects non-positive/non-integer reps', () => {
28
+ expect(() => holdoutReps({ holdoutRepsPerInstance: 0 })).toThrow(/positive integer/)
29
+ expect(() => holdoutReps({ holdoutRepsPerInstance: 1.5 })).toThrow(/positive integer/)
30
+ })
31
+ })
32
+
33
+ describe('assertHoldoutBaselineMap', () => {
34
+ it('requires a same-protocol verdict for EVERY holdout instance', () => {
35
+ expect(() => assertHoldoutBaselineMap({ a: true }, IIDS)).toThrow(/missing same-protocol verdicts.*b, c/)
36
+ })
37
+
38
+ it('rejects verdicts for non-holdout instances', () => {
39
+ expect(() => assertHoldoutBaselineMap({ a: true, b: false, c: true, z: true }, IIDS)).toThrow(/non-holdout/)
40
+ })
41
+
42
+ it('accepts a complete map', () => {
43
+ expect(() => assertHoldoutBaselineMap({ a: true, b: false, c: true }, IIDS)).not.toThrow()
44
+ })
45
+ })
46
+
47
+ describe('decideHoldoutCertification — 2-rep fail-closed aggregation', () => {
48
+ const parent = { a: true, b: false, c: true } // parent 2/3 same-protocol
49
+
50
+ it('an instance resolves only when BOTH reps resolve (T/F counts as unresolved)', () => {
51
+ const d = decideHoldoutCertification({
52
+ candidateRuns: runs({ a: [true, true], b: [true, false], c: [true, true] }),
53
+ parentVerdicts: parent,
54
+ iids: IIDS,
55
+ reps: 2,
56
+ })
57
+ expect(d.candResolved).toBe(2) // a + c; b's discordant pair is fail-closed
58
+ expect(d.parentResolved).toBe(2)
59
+ expect(d.coverageComplete).toBe(true)
60
+ expect(d.certified).toBe(true) // non-regression: 2 >= 2
61
+ expect(d.perInstance.find((p) => p.iid === 'b')).toMatchObject({ candidate: false, parent: false, discordant: false })
62
+ })
63
+
64
+ it('regression fails certification even with complete coverage', () => {
65
+ const d = decideHoldoutCertification({
66
+ candidateRuns: runs({ a: [true, true], b: [false, false], c: [false, true] }),
67
+ parentVerdicts: parent,
68
+ iids: IIDS,
69
+ reps: 2,
70
+ })
71
+ expect(d.candResolved).toBe(1)
72
+ expect(d.certified).toBe(false)
73
+ expect(d.reasons.join(' ')).toMatch(/regression: candidate 1 < parent 2/)
74
+ expect(d.perInstance.find((p) => p.iid === 'c')).toMatchObject({ candidate: false, parent: true, discordant: true })
75
+ })
76
+
77
+ it('an inconclusive replicate (errored cell) blocks coverage and certification — fail-closed', () => {
78
+ const d = decideHoldoutCertification({
79
+ candidateRuns: runs({ a: [true, true], b: [false, false], c: [true, null] }),
80
+ parentVerdicts: parent,
81
+ iids: IIDS,
82
+ reps: 2,
83
+ })
84
+ expect(d.coverageComplete).toBe(false)
85
+ expect(d.certified).toBe(false)
86
+ expect(d.reasons.join(' ')).toMatch(/coverage incomplete/)
87
+ expect(d.perInstance.find((p) => p.iid === 'c')).toMatchObject({ candidate: null, discordant: false })
88
+ })
89
+
90
+ it('a missing replicate (only 1 of 2 reps ran) blocks coverage', () => {
91
+ const d = decideHoldoutCertification({
92
+ candidateRuns: runs({ a: [true, true], b: [true, true], c: [true] }),
93
+ parentVerdicts: parent,
94
+ iids: IIDS,
95
+ reps: 2,
96
+ })
97
+ expect(d.coverageComplete).toBe(false)
98
+ expect(d.certified).toBe(false)
99
+ })
100
+
101
+ it('gen-2 shape: one discordant instance under 1-rep would have failed; the same data at 2 reps needs both reps', () => {
102
+ // At 1 rep a single flipped cell decided the gen-2 verdict. The 2-rep
103
+ // protocol requires the flip to REPLICATE before it counts either way.
104
+ const oneRep = decideHoldoutCertification({
105
+ candidateRuns: runs({ a: [true], b: [false], c: [false] }),
106
+ parentVerdicts: parent,
107
+ iids: IIDS,
108
+ reps: 1,
109
+ })
110
+ expect(oneRep.certified).toBe(false) // 1 < 2 — the gen-2 outcome
111
+ const twoRep = decideHoldoutCertification({
112
+ candidateRuns: runs({ a: [true, true], b: [false, false], c: [true, true] }),
113
+ parentVerdicts: parent,
114
+ iids: IIDS,
115
+ reps: 2,
116
+ })
117
+ expect(twoRep.certified).toBe(true) // c held up under replication
118
+ })
119
+
120
+ it('validates the parent map before deciding', () => {
121
+ expect(() =>
122
+ decideHoldoutCertification({
123
+ candidateRuns: runs({ a: [true, true] }),
124
+ parentVerdicts: { a: true },
125
+ iids: IIDS,
126
+ reps: 2,
127
+ }),
128
+ ).toThrow(/missing same-protocol verdicts/)
129
+ })
130
+ })
131
+
132
+ describe('loadHoldoutCells', () => {
133
+ let dir: string
134
+ beforeEach(async () => {
135
+ dir = await mkdtemp(join(tmpdir(), 'holdout-cells-'))
136
+ })
137
+ afterEach(async () => {
138
+ await rm(dir, { recursive: true, force: true })
139
+ })
140
+
141
+ it('returns [] for a missing file and round-trips schema-valid rows', async () => {
142
+ const path = join(dir, 'cells.jsonl')
143
+ expect(await loadHoldoutCells(path)).toEqual([])
144
+ const row: HoldoutCellRow = {
145
+ schema: 'swe-arena.holdout-cell.v1',
146
+ at: new Date(0).toISOString(),
147
+ commit: 'abc123',
148
+ side: 'candidate',
149
+ iid: 'a',
150
+ rep: 0,
151
+ resolved: true,
152
+ verifyPass: true,
153
+ wallS: 100,
154
+ runDir: '/tmp/x',
155
+ }
156
+ await writeFile(path, `${JSON.stringify(row)}\n${JSON.stringify({ schema: 'other' })}\n`)
157
+ const rows = await loadHoldoutCells(path)
158
+ expect(rows).toEqual([row]) // foreign schemas are dropped
159
+ })
160
+ })
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Judge child entrypoint — the experiment's `judge.mts`, tracked. One patch,
3
+ * one official swebench verdict, printed as a single `JUDGE_RESULT {...}` line
4
+ * that serialized-judge.ts parses. Runs as a CHILD process (not in-process) so
5
+ * the judge ceiling can SIGKILL a hung swebench run without taking the
6
+ * experiment down, exactly like the bash `timeout N node judge.mts`.
7
+ *
8
+ * usage: node --import tsx src/swe-arena/judge-child.mts <instance_id> <patchPath>
9
+ */
10
+
11
+ import { readFileSync } from 'node:fs'
12
+ import { createSweBenchAdapter } from '../benchmarks/swe-bench.ts'
13
+
14
+ const [, , iid, patchPath] = process.argv
15
+ if (!iid || !patchPath) {
16
+ console.error('usage: node --import tsx judge-child.mts <instance_id> <patchPath>')
17
+ process.exit(2)
18
+ }
19
+ const patch = readFileSync(patchPath, 'utf8')
20
+ const adapter = createSweBenchAdapter()
21
+ const [task] = await adapter.loadTasks({ ids: [iid], split: 'test' })
22
+ if (!task) {
23
+ console.log(JSON.stringify({ iid, error: 'no-task' }))
24
+ process.exit(2)
25
+ }
26
+ const t0 = Date.now()
27
+ const score = await adapter.judge(task, patch)
28
+ console.log(
29
+ 'JUDGE_RESULT ' +
30
+ JSON.stringify({
31
+ iid,
32
+ resolved: score.resolved,
33
+ score: score.score,
34
+ secs: Math.round((Date.now() - t0) / 1000),
35
+ patch_bytes: patch.length,
36
+ }),
37
+ )
@@ -0,0 +1,293 @@
1
+ /**
2
+ * Rollout manifest — a pure READER/JOIN over what the round already writes.
3
+ * No new capture pipeline: the lib's improve() run emits loop-provenance.json,
4
+ * per-cell cached results, and the durable cost log; the swe-arena dispatch
5
+ * emits arm result/judge files, candidate patches, and proposer-shot receipts.
6
+ * This module joins them into one versioned per-generation manifest of
7
+ * (state, action, outcome, cost, artifactPaths) triples.
8
+ *
9
+ * tsx src/swe-arena/manifest.mts <outDir> # writes <outDir>/rollout-manifest.json
10
+ *
11
+ * Sources (all optional — a missing file is a labeled gap, never a crash):
12
+ * - <outDir>/improve-run/loop-provenance.json (lib)
13
+ * - <outDir>/improve-run/cost-ledger.jsonl (lib, durable receipts)
14
+ * - <outDir>/improve-run/baseline and gen-N/candidate-K (lib, per-cell caches)
15
+ * - <outDir>/candidates/<commit10>.patch (ours, diff writing)
16
+ * - <outDir>/proposer-shots/genN-candK-shotS.json (ours, shot receipts)
17
+ * - per-cell artifact.runDir result.json + judge.json (ours, arm + judge)
18
+ */
19
+
20
+ import { readdir, readFile, writeFile } from 'node:fs/promises'
21
+ import { existsSync } from 'node:fs'
22
+ import { join } from 'node:path'
23
+ import { pathToFileURL } from 'node:url'
24
+ import {
25
+ loadCampaignCells,
26
+ loadCandidateCellGroups,
27
+ perInstanceFromCells,
28
+ replicateRunsFromCells,
29
+ resolvedInstanceCount,
30
+ sumWallSFromCells,
31
+ type EvidenceCell,
32
+ type StaircasePerInstance,
33
+ } from './cell-evidence.mts'
34
+
35
+ export const ROLLOUT_SCHEMA = 'swe-arena.rollout.v1'
36
+
37
+ export interface RolloutCost {
38
+ /** Σ campaign-cell CostLedger spend (worker receipts) across the cells. */
39
+ cellCostUsd: number
40
+ cellTokensIn: number
41
+ cellTokensOut: number
42
+ /** Σ runtime spend-tree usd/tokens off the artifacts (telemetry-gap nulls skipped). */
43
+ armSpentUsd: number
44
+ armSpentTokens: number
45
+ wallS: number
46
+ judgeWallS: number
47
+ /** Durable cost-ledger receipts whose tags name this campaign dir. */
48
+ receiptCallIds: string[]
49
+ }
50
+
51
+ export interface RolloutEntry {
52
+ state: {
53
+ generation: number
54
+ /** -1 candidateIndex = the baseline campaign. */
55
+ candidateIndex: number
56
+ campaignDir: string
57
+ commit: string | null
58
+ }
59
+ action: {
60
+ /** Candidate diff written at dispatch time (null for the baseline / a
61
+ * resumed-only run whose diff was not rewritten). */
62
+ diffPath: string | null
63
+ /** Persisted proposer-shot receipts for this (generation, candidate). */
64
+ shotReceiptPaths: string[]
65
+ }
66
+ outcome: {
67
+ perInstance: StaircasePerInstance[]
68
+ resolvedCount: number
69
+ cellsCached: number
70
+ }
71
+ cost: RolloutCost
72
+ artifactPaths: {
73
+ cells: string[]
74
+ armResults: string[]
75
+ judgeVerdicts: string[]
76
+ patches: string[]
77
+ }
78
+ }
79
+
80
+ export interface RolloutGeneration {
81
+ generation: number
82
+ rollouts: RolloutEntry[]
83
+ }
84
+
85
+ export interface RolloutManifest {
86
+ schema: typeof ROLLOUT_SCHEMA
87
+ outDir: string
88
+ at: string
89
+ /** The lib's durable provenance record, verbatim (null = not emitted). */
90
+ provenance: unknown | null
91
+ /** Improvement-set ids inferred from the baseline cells. */
92
+ instances: string[]
93
+ generations: RolloutGeneration[]
94
+ }
95
+
96
+ interface LedgerReceipt {
97
+ callId: string
98
+ tags?: Record<string, string>
99
+ [k: string]: unknown
100
+ }
101
+
102
+ /** Settled receipts out of the lib's append-only cost-ledger.jsonl. */
103
+ export async function loadLedgerReceipts(improveRunDir: string): Promise<LedgerReceipt[]> {
104
+ const raw = await readFile(join(improveRunDir, 'cost-ledger.jsonl'), 'utf8').catch(() => '')
105
+ const receipts: LedgerReceipt[] = []
106
+ for (const line of raw.split('\n')) {
107
+ if (!line.trim()) continue
108
+ let event: Record<string, unknown>
109
+ try {
110
+ event = JSON.parse(line) as Record<string, unknown>
111
+ } catch {
112
+ continue
113
+ }
114
+ const record = event.record as Record<string, unknown> | undefined
115
+ if (record && record.status === 'settled' && typeof record.callId === 'string') {
116
+ receipts.push(record as unknown as LedgerReceipt)
117
+ }
118
+ }
119
+ return receipts
120
+ }
121
+
122
+ function costFromCells(
123
+ cells: EvidenceCell[],
124
+ campaignDir: string,
125
+ receipts: LedgerReceipt[],
126
+ ): RolloutCost {
127
+ let cellCostUsd = 0
128
+ let cellTokensIn = 0
129
+ let cellTokensOut = 0
130
+ let armSpentUsd = 0
131
+ let armSpentTokens = 0
132
+ let judgeWallS = 0
133
+ for (const cell of cells) {
134
+ cellCostUsd += cell.costUsd ?? 0
135
+ cellTokensIn += cell.tokenUsage?.input ?? 0
136
+ cellTokensOut += cell.tokenUsage?.output ?? 0
137
+ const a = cell.artifact
138
+ if (a !== null && a.kind === 'swe-arm') {
139
+ armSpentUsd += a.spentUsd ?? 0
140
+ armSpentTokens += a.spentTokens ?? 0
141
+ judgeWallS += a.judgeWallS ?? 0
142
+ }
143
+ }
144
+ return {
145
+ cellCostUsd: Number(cellCostUsd.toFixed(6)),
146
+ cellTokensIn,
147
+ cellTokensOut,
148
+ armSpentUsd: Number(armSpentUsd.toFixed(6)),
149
+ armSpentTokens,
150
+ wallS: sumWallSFromCells(cells),
151
+ judgeWallS,
152
+ receiptCallIds: receipts
153
+ .filter((r) => r.tags?.runDir === campaignDir)
154
+ .map((r) => r.callId)
155
+ .sort(),
156
+ }
157
+ }
158
+
159
+ function artifactPathsFromCells(cells: EvidenceCell[], campaignDir: string): RolloutEntry['artifactPaths'] {
160
+ const armResults: string[] = []
161
+ const judgeVerdicts: string[] = []
162
+ const patches: string[] = []
163
+ for (const cell of cells) {
164
+ const a = cell.artifact
165
+ if (a === null || a.kind !== 'swe-arm') continue
166
+ if (a.runDir) {
167
+ const resultPath = join(a.runDir, 'result.json')
168
+ const judgePath = join(a.runDir, 'judge.json')
169
+ if (existsSync(resultPath)) armResults.push(resultPath)
170
+ if (existsSync(judgePath)) judgeVerdicts.push(judgePath)
171
+ }
172
+ if (a.patchPath && existsSync(a.patchPath)) patches.push(a.patchPath)
173
+ }
174
+ return {
175
+ // The campaign dir holds the per-cell cached-result.json score records.
176
+ cells: cells.length > 0 ? [campaignDir] : [],
177
+ armResults: [...new Set(armResults)].sort(),
178
+ judgeVerdicts: [...new Set(judgeVerdicts)].sort(),
179
+ patches: [...new Set(patches)].sort(),
180
+ }
181
+ }
182
+
183
+ async function shotReceiptPathsFor(
184
+ outDir: string,
185
+ generation: number,
186
+ candidateIndex: number,
187
+ ): Promise<string[]> {
188
+ const shotDir = join(outDir, 'proposer-shots')
189
+ const names = await readdir(shotDir).catch(() => [])
190
+ return names
191
+ .filter((n) => n.startsWith(`gen${generation}-cand${candidateIndex}-`) && n.endsWith('.json'))
192
+ .sort()
193
+ .map((n) => join(shotDir, n))
194
+ }
195
+
196
+ /** Build the rollout manifest for one round outDir. Pure join — reads only. */
197
+ export async function buildRolloutManifest(outDir: string): Promise<RolloutManifest> {
198
+ const improveRunDir = join(outDir, 'improve-run')
199
+ const provenanceRaw = await readFile(join(improveRunDir, 'loop-provenance.json'), 'utf8').catch(() => null)
200
+ const provenance = provenanceRaw === null ? null : (JSON.parse(provenanceRaw) as unknown)
201
+ const receipts = await loadLedgerReceipts(improveRunDir)
202
+
203
+ const baselineDir = join(improveRunDir, 'baseline')
204
+ const baselineCells = await loadCampaignCells(baselineDir)
205
+ const instances = [...new Set(baselineCells.map((c) => c.scenarioId))].sort()
206
+
207
+ const generations = new Map<number, RolloutGeneration>()
208
+ const genOf = (g: number): RolloutGeneration => {
209
+ const existing = generations.get(g)
210
+ if (existing) return existing
211
+ const fresh: RolloutGeneration = { generation: g, rollouts: [] }
212
+ generations.set(g, fresh)
213
+ return fresh
214
+ }
215
+
216
+ if (baselineCells.length > 0) {
217
+ genOf(-1).rollouts.push({
218
+ state: { generation: -1, candidateIndex: -1, campaignDir: baselineDir, commit: baselineCells[0]?.artifact?.commit ?? null },
219
+ action: { diffPath: null, shotReceiptPaths: [] },
220
+ outcome: {
221
+ perInstance: perInstanceFromCells(baselineCells),
222
+ resolvedCount: resolvedInstanceCount(
223
+ replicateRunsFromCells(baselineCells),
224
+ instances,
225
+ maxRep(baselineCells) + 1,
226
+ ),
227
+ cellsCached: baselineCells.length,
228
+ },
229
+ cost: costFromCells(baselineCells, baselineDir, receipts),
230
+ artifactPaths: artifactPathsFromCells(baselineCells, baselineDir),
231
+ })
232
+ }
233
+
234
+ for (const group of await loadCandidateCellGroups(improveRunDir)) {
235
+ const diffPath = group.commit ? join(outDir, 'candidates', `${group.commit.slice(0, 10)}.patch`) : null
236
+ genOf(group.generation).rollouts.push({
237
+ state: {
238
+ generation: group.generation,
239
+ candidateIndex: group.candidateIndex,
240
+ campaignDir: group.dir,
241
+ commit: group.commit,
242
+ },
243
+ action: {
244
+ diffPath: diffPath !== null && existsSync(diffPath) ? diffPath : null,
245
+ shotReceiptPaths: await shotReceiptPathsFor(outDir, group.generation, group.candidateIndex),
246
+ },
247
+ outcome: {
248
+ perInstance: perInstanceFromCells(group.cells),
249
+ resolvedCount: resolvedInstanceCount(
250
+ replicateRunsFromCells(group.cells),
251
+ instances,
252
+ maxRep(group.cells) + 1,
253
+ ),
254
+ cellsCached: group.cells.length,
255
+ },
256
+ cost: costFromCells(group.cells, group.dir, receipts),
257
+ artifactPaths: artifactPathsFromCells(group.cells, group.dir),
258
+ })
259
+ }
260
+
261
+ return {
262
+ schema: ROLLOUT_SCHEMA,
263
+ outDir,
264
+ at: new Date().toISOString(),
265
+ provenance,
266
+ instances,
267
+ generations: [...generations.values()].sort((a, b) => a.generation - b.generation),
268
+ }
269
+ }
270
+
271
+ /** Replicate count inferred from the cells themselves (reps = max rep index
272
+ * + 1). The manifest is a reader with no config in scope; an incomplete
273
+ * candidate under-infers reps and its resolvedCount stays fail-closed. */
274
+ const maxRep = (cells: EvidenceCell[]): number => cells.reduce((m, c) => Math.max(m, c.rep), 0)
275
+
276
+ export async function writeRolloutManifest(outDir: string): Promise<string> {
277
+ const manifest = await buildRolloutManifest(outDir)
278
+ const path = join(outDir, 'rollout-manifest.json')
279
+ await writeFile(path, JSON.stringify(manifest, null, 2))
280
+ return path
281
+ }
282
+
283
+ const isMain = process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href
284
+
285
+ if (isMain) {
286
+ const outDir = process.argv[2]
287
+ if (!outDir) {
288
+ console.error('usage: tsx src/swe-arena/manifest.mts <outDir>')
289
+ process.exit(2)
290
+ }
291
+ const path = await writeRolloutManifest(outDir)
292
+ console.log(`rollout manifest → ${path}`)
293
+ }
@@ -0,0 +1,169 @@
1
+ /**
2
+ * Rollout-manifest reader: a synthetic round outDir with the lib's files
3
+ * (loop-provenance.json, cost-ledger.jsonl, per-cell caches) and the
4
+ * swe-arena files (arm result/judge json, patches, shot receipts) joins into
5
+ * one versioned manifest. Pure reads — nothing is dispatched.
6
+ */
7
+
8
+ import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
9
+ import { tmpdir } from 'node:os'
10
+ import { join } from 'node:path'
11
+ import { afterAll, describe, expect, it } from 'vitest'
12
+ import type { R4Artifact } from './cell-evidence.mts'
13
+ import { buildRolloutManifest, loadLedgerReceipts, ROLLOUT_SCHEMA, writeRolloutManifest } from './manifest.mts'
14
+
15
+ const IID = 'django__django-11532'
16
+
17
+ describe('rollout manifest (synthetic outDir)', () => {
18
+ let outDir: string
19
+ let armRunDir: string
20
+ let candDir: string
21
+
22
+ afterAll(async () => {
23
+ await rm(outDir, { recursive: true, force: true })
24
+ })
25
+
26
+ async function writeCell(campaignDir: string, rep: number, artifact: R4Artifact, costUsd: number): Promise<void> {
27
+ const cellDir = join(campaignDir, `cell-${IID}-r${rep}`)
28
+ await mkdir(cellDir, { recursive: true })
29
+ await writeFile(
30
+ join(cellDir, 'cached-result.json'),
31
+ JSON.stringify({
32
+ cellId: `cell-${IID}-r${rep}`,
33
+ scenarioId: IID,
34
+ rep,
35
+ artifact,
36
+ costUsd,
37
+ tokenUsage: { input: 400, output: 100 },
38
+ judgeScores: {},
39
+ durationMs: 5,
40
+ seed: 42,
41
+ cached: false,
42
+ }),
43
+ )
44
+ }
45
+
46
+ async function makeOutDir(): Promise<void> {
47
+ outDir = await mkdtemp(join(tmpdir(), 'r4-manifest-'))
48
+ const improveRun = join(outDir, 'improve-run')
49
+
50
+ // Arm run dir the artifacts point at (ours: result.json + judge.json).
51
+ armRunDir = join(outDir, 'arm-runs', 'cafebabe00', 'rep-0', 'runs', IID, 'R4')
52
+ await mkdir(armRunDir, { recursive: true })
53
+ await writeFile(join(armRunDir, 'result.json'), JSON.stringify({ arm: 'R4', iid: IID }))
54
+ await writeFile(join(armRunDir, 'judge.json'), JSON.stringify({ iid: IID, resolved: true, wallS: 31 }))
55
+ const patchPath = join(outDir, 'patches', `${IID}.r4.patch`)
56
+ await mkdir(join(outDir, 'patches'), { recursive: true })
57
+ await writeFile(patchPath, 'diff --git a b\n')
58
+
59
+ const artifact = (resolved: boolean): R4Artifact => ({
60
+ kind: 'swe-arm',
61
+ iid: IID,
62
+ commit: 'cafebabe0012345678',
63
+ resolved,
64
+ verifyPass: resolved,
65
+ patchLines: 4,
66
+ wallS: 120,
67
+ spentTokens: 2000,
68
+ spentUsd: 0.02,
69
+ recoveredTokens: 2500,
70
+ workerTokIn: 400,
71
+ workerTokOut: 100,
72
+ judgeAttempts: 1,
73
+ judgeWallS: 31,
74
+ runDir: armRunDir,
75
+ patchPath,
76
+ })
77
+
78
+ // Lib: baseline campaign cells (different commit).
79
+ const baselineDir = join(improveRun, 'baseline')
80
+ await writeCell(baselineDir, 0, { ...artifact(true), commit: 'basecommit12345678' }, 0.01)
81
+ await writeCell(baselineDir, 1, { ...artifact(true), commit: 'basecommit12345678' }, 0.01)
82
+
83
+ // Lib: gen-0 candidate campaign cells.
84
+ candDir = join(improveRun, 'gen-0', 'candidate-0')
85
+ await writeCell(candDir, 0, artifact(false), 0.02)
86
+ await writeCell(candDir, 1, artifact(false), 0.02)
87
+
88
+ // Lib: durable provenance + cost log.
89
+ await writeFile(
90
+ join(improveRun, 'loop-provenance.json'),
91
+ JSON.stringify({ schema: 'tangle.loop-provenance', runId: 'r4-test', candidates: [] }),
92
+ )
93
+ await writeFile(
94
+ join(improveRun, 'cost-ledger.jsonl'),
95
+ [
96
+ JSON.stringify({ version: 1, record: { status: 'pending', callId: 'p1', channel: 'agent', phase: 'x', actor: 'a', model: 'm', timestamp: 1 } }),
97
+ JSON.stringify({ version: 1, record: { status: 'settled', callId: 'c1', channel: 'agent', phase: 'search.candidate', actor: 'a', model: 'm', timestamp: 2, inputTokens: 400, outputTokens: 100, costUsd: 0.02, costUnknown: false, tags: { runDir: candDir, cellId: `cell-${IID}-r0` } } }),
98
+ JSON.stringify({ version: 1, record: { status: 'settled', callId: 'c2', channel: 'judge', phase: 'search.candidate', actor: 'j', model: 'swe-bench-official-judge', timestamp: 3, inputTokens: 0, outputTokens: 0, costUsd: 0, costUnknown: false, tags: { runDir: candDir, cellId: `cell-${IID}-r1` } } }),
99
+ 'garbage line',
100
+ ].join('\n'),
101
+ )
102
+
103
+ // Ours: candidate diff + proposer shot receipt.
104
+ await mkdir(join(outDir, 'candidates'), { recursive: true })
105
+ await writeFile(join(outDir, 'candidates', 'cafebabe00.patch'), 'diff --git x y\n')
106
+ await mkdir(join(outDir, 'proposer-shots'), { recursive: true })
107
+ await writeFile(join(outDir, 'proposer-shots', 'gen0-cand0-shot1.json'), JSON.stringify({ receipt: { shot: 1 } }))
108
+ }
109
+
110
+ it('joins lib + swe-arena files into versioned per-generation rollout triples', async () => {
111
+ await makeOutDir()
112
+ const manifest = await buildRolloutManifest(outDir)
113
+
114
+ expect(manifest.schema).toBe(ROLLOUT_SCHEMA)
115
+ expect(manifest.instances).toEqual([IID])
116
+ expect((manifest.provenance as { schema: string }).schema).toBe('tangle.loop-provenance')
117
+ expect(manifest.generations.map((g) => g.generation)).toEqual([-1, 0])
118
+
119
+ const baseline = manifest.generations[0]!.rollouts[0]!
120
+ expect(baseline.state).toMatchObject({ generation: -1, candidateIndex: -1, commit: 'basecommit12345678' })
121
+ expect(baseline.outcome.resolvedCount).toBe(1)
122
+ expect(baseline.outcome.perInstance).toHaveLength(2)
123
+ expect(baseline.action.shotReceiptPaths).toEqual([])
124
+
125
+ const cand = manifest.generations[1]!.rollouts[0]!
126
+ expect(cand.state).toMatchObject({ generation: 0, candidateIndex: 0, commit: 'cafebabe0012345678', campaignDir: candDir })
127
+ expect(cand.outcome.resolvedCount).toBe(0)
128
+ expect(cand.outcome.cellsCached).toBe(2)
129
+ // Cost joins: cell ledger spend + artifact spend-tree + judge wall.
130
+ expect(cand.cost.cellCostUsd).toBeCloseTo(0.04, 6)
131
+ expect(cand.cost.cellTokensIn).toBe(800)
132
+ expect(cand.cost.armSpentUsd).toBeCloseTo(0.04, 6)
133
+ expect(cand.cost.armSpentTokens).toBe(4000)
134
+ expect(cand.cost.wallS).toBe(240)
135
+ expect(cand.cost.judgeWallS).toBe(62)
136
+ expect(cand.cost.receiptCallIds).toEqual(['c1', 'c2'])
137
+ // Artifact joins: our arm/judge/patch files + the shot receipt.
138
+ expect(cand.artifactPaths.armResults).toEqual([join(armRunDir, 'result.json')])
139
+ expect(cand.artifactPaths.judgeVerdicts).toEqual([join(armRunDir, 'judge.json')])
140
+ expect(cand.artifactPaths.patches).toHaveLength(1)
141
+ expect(cand.action.diffPath).toBe(join(outDir, 'candidates', 'cafebabe00.patch'))
142
+ expect(cand.action.shotReceiptPaths).toEqual([join(outDir, 'proposer-shots', 'gen0-cand0-shot1.json')])
143
+ })
144
+
145
+ it('loadLedgerReceipts keeps settled records only and survives garbage lines', async () => {
146
+ const receipts = await loadLedgerReceipts(join(outDir, 'improve-run'))
147
+ expect(receipts.map((r) => r.callId)).toEqual(['c1', 'c2'])
148
+ })
149
+
150
+ it('writeRolloutManifest emits <outDir>/rollout-manifest.json (the CLI body)', async () => {
151
+ const path = await writeRolloutManifest(outDir)
152
+ expect(path).toBe(join(outDir, 'rollout-manifest.json'))
153
+ const parsed = JSON.parse(await readFile(path, 'utf8')) as { schema: string }
154
+ expect(parsed.schema).toBe(ROLLOUT_SCHEMA)
155
+ })
156
+
157
+ it('a bare outDir (no improve-run yet) yields an empty, well-formed manifest', async () => {
158
+ const empty = await mkdtemp(join(tmpdir(), 'r4-manifest-empty-'))
159
+ try {
160
+ const manifest = await buildRolloutManifest(empty)
161
+ expect(manifest.schema).toBe(ROLLOUT_SCHEMA)
162
+ expect(manifest.provenance).toBeNull()
163
+ expect(manifest.instances).toEqual([])
164
+ expect(manifest.generations).toEqual([])
165
+ } finally {
166
+ await rm(empty, { recursive: true, force: true })
167
+ }
168
+ })
169
+ })