@tangle-network/agent-bench 4.0.0 → 4.0.3

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.
@@ -0,0 +1,352 @@
1
+ import { execFileSync, spawn } from 'node:child_process'
2
+ import {
3
+ closeSync,
4
+ createReadStream,
5
+ existsSync,
6
+ fsyncSync,
7
+ openSync,
8
+ readFileSync,
9
+ readdirSync,
10
+ renameSync,
11
+ writeFileSync,
12
+ } from 'node:fs'
13
+ import { basename, isAbsolute, join, resolve } from 'node:path'
14
+
15
+ const identityFile = 'identity.json'
16
+ const terminalFile = 'terminal.json'
17
+ const stopFile = 'stop-requested'
18
+
19
+ function fail(message) {
20
+ throw new Error(message)
21
+ }
22
+
23
+ function readJson(path, label) {
24
+ let value
25
+ try {
26
+ value = JSON.parse(readFileSync(path, 'utf8'))
27
+ } catch (error) {
28
+ throw new Error(`${label} is not valid JSON`, { cause: error })
29
+ }
30
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
31
+ fail(`${label} must be an object`)
32
+ }
33
+ return value
34
+ }
35
+
36
+ function syncDirectory(directory) {
37
+ const fd = openSync(directory, 'r')
38
+ try {
39
+ fsyncSync(fd)
40
+ } finally {
41
+ closeSync(fd)
42
+ }
43
+ }
44
+
45
+ function writeJsonAtomic(directory, name, value) {
46
+ const target = join(directory, name)
47
+ const temporary = join(directory, `.${name}.${process.pid}.tmp`)
48
+ const fd = openSync(temporary, 'wx', 0o600)
49
+ try {
50
+ writeFileSync(fd, `${JSON.stringify(value)}\n`, 'utf8')
51
+ fsyncSync(fd)
52
+ } finally {
53
+ closeSync(fd)
54
+ }
55
+ renameSync(temporary, target)
56
+ syncDirectory(directory)
57
+ }
58
+
59
+ async function readControlInput() {
60
+ const chunks = []
61
+ for await (const chunk of createReadStream('', { fd: 3 })) {
62
+ chunks.push(Buffer.from(chunk))
63
+ }
64
+ const bytes = Buffer.concat(chunks)
65
+ if (bytes.byteLength === 0) fail('Pier supervisor received no launch request')
66
+ return JSON.parse(bytes.toString('utf8'))
67
+ }
68
+
69
+ function processIdentity(pid) {
70
+ const text = readFileSync(`/proc/${pid}/stat`, 'utf8')
71
+ const closing = text.lastIndexOf(')')
72
+ if (closing < 0) fail(`cannot parse process identity for ${pid}`)
73
+ const fields = text.slice(closing + 2).trim().split(/\s+/)
74
+ const processGroupId = Number(fields[2])
75
+ const sessionId = Number(fields[3])
76
+ const startTicks = fields[19]
77
+ if (
78
+ !Number.isSafeInteger(processGroupId) ||
79
+ !Number.isSafeInteger(sessionId) ||
80
+ !/^\d+$/.test(startTicks ?? '')
81
+ ) {
82
+ fail(`cannot parse process identity for ${pid}`)
83
+ }
84
+ return { pid, processGroupId, sessionId, startTicks }
85
+ }
86
+
87
+ function processMatches(identity) {
88
+ try {
89
+ const current = processIdentity(identity.pid)
90
+ return (
91
+ current.startTicks === identity.startTicks &&
92
+ current.processGroupId === identity.processGroupId &&
93
+ current.sessionId === identity.sessionId
94
+ )
95
+ } catch (error) {
96
+ if (error?.code === 'ENOENT' || error?.code === 'ESRCH') return false
97
+ throw error
98
+ }
99
+ }
100
+
101
+ function sessionMembers(sessionId) {
102
+ const members = []
103
+ for (const entry of readdirSync('/proc', { withFileTypes: true })) {
104
+ if (!entry.isDirectory() || !/^\d+$/.test(entry.name)) continue
105
+ try {
106
+ const identity = processIdentity(Number(entry.name))
107
+ if (identity.sessionId === sessionId) members.push(identity)
108
+ } catch (error) {
109
+ if (error?.code !== 'ENOENT') throw error
110
+ }
111
+ }
112
+ return members
113
+ }
114
+
115
+ async function signalSessionUntilEmpty(identity, signal, timeoutMs) {
116
+ const deadline = Date.now() + timeoutMs
117
+ while (true) {
118
+ const members = sessionMembers(identity.sessionId)
119
+ if (members.length === 0) return true
120
+ for (const member of members) {
121
+ try {
122
+ process.kill(member.pid, signal)
123
+ } catch (error) {
124
+ if (error?.code !== 'ESRCH') throw error
125
+ }
126
+ }
127
+ if (Date.now() >= deadline) return false
128
+ await new Promise((resolveWait) => setTimeout(resolveWait, 20))
129
+ }
130
+ }
131
+
132
+ function sanitizeProject(value) {
133
+ let project = value.toLowerCase()
134
+ if (!/^[a-z0-9]/.test(project)) project = `0${project}`
135
+ return project.replace(/[^a-z0-9_-]/g, '-')
136
+ }
137
+
138
+ function trialProjects(jobsDirectory, jobName) {
139
+ const jobRoot = join(jobsDirectory, jobName)
140
+ if (!existsSync(jobRoot)) return []
141
+ return readdirSync(jobRoot, { withFileTypes: true })
142
+ .filter((entry) => entry.isDirectory() && !entry.isSymbolicLink())
143
+ .map((entry) => sanitizeProject(entry.name))
144
+ }
145
+
146
+ function matchingContainers(dockerCommand, projects) {
147
+ if (projects.length === 0) return []
148
+ const output = execFileSync(
149
+ dockerCommand,
150
+ ['ps', '-a', '--format', '{{.ID}}\t{{.Label "com.docker.compose.project"}}'],
151
+ { encoding: 'utf8', timeout: 30_000, maxBuffer: 4 * 1024 * 1024 },
152
+ )
153
+ const matches = []
154
+ for (const line of output.split('\n')) {
155
+ if (!line) continue
156
+ const tab = line.indexOf('\t')
157
+ if (tab < 1) continue
158
+ const id = line.slice(0, tab)
159
+ const project = line.slice(tab + 1)
160
+ if (
161
+ projects.some(
162
+ (expected) =>
163
+ project === expected || project.startsWith(`${expected}__verifier__`),
164
+ )
165
+ ) {
166
+ matches.push(id)
167
+ }
168
+ }
169
+ return matches
170
+ }
171
+
172
+ function removeTrialContainers(config) {
173
+ const projects = trialProjects(config.jobsDirectory, config.jobName)
174
+ const containers = matchingContainers(config.dockerCommand, projects)
175
+ if (containers.length > 0) {
176
+ try {
177
+ execFileSync(config.dockerCommand, ['rm', '-f', ...containers], {
178
+ encoding: 'utf8',
179
+ timeout: 30_000,
180
+ maxBuffer: 4 * 1024 * 1024,
181
+ })
182
+ } catch (error) {
183
+ if (matchingContainers(config.dockerCommand, projects).length > 0) throw error
184
+ }
185
+ }
186
+ const remaining = matchingContainers(config.dockerCommand, projects)
187
+ if (remaining.length > 0) {
188
+ fail(`Pier task containers survived removal: ${remaining.join(', ')}`)
189
+ }
190
+ return containers.length
191
+ }
192
+
193
+ async function waitForExit(exited, timeoutMs) {
194
+ return await Promise.race([
195
+ exited.then(() => true),
196
+ new Promise((resolveTimeout) => setTimeout(() => resolveTimeout(false), timeoutMs)),
197
+ ])
198
+ }
199
+
200
+ const directory = resolve(process.argv[2] ?? '')
201
+ if (!isAbsolute(directory) || basename(directory) === '') {
202
+ fail('Pier supervisor control directory must be absolute')
203
+ }
204
+
205
+ let config
206
+ let child
207
+ let childIdentity
208
+ let stopRequested = existsSync(join(directory, stopFile))
209
+ let stopping
210
+
211
+ async function stopChild() {
212
+ if (!child) return
213
+ if (!childIdentity) {
214
+ try {
215
+ child.process.kill('SIGKILL')
216
+ } catch (error) {
217
+ if (error?.code !== 'ESRCH') throw error
218
+ }
219
+ if (!(await waitForExit(child.exited, 5_000))) {
220
+ fail('Pier process with unreadable identity survived SIGKILL')
221
+ }
222
+ return
223
+ }
224
+ if (!(await signalSessionUntilEmpty(childIdentity, 'SIGTERM', 2_000))) {
225
+ if (!(await signalSessionUntilEmpty(childIdentity, 'SIGKILL', 5_000))) {
226
+ fail(`Pier process session ${childIdentity.sessionId} survived SIGKILL`)
227
+ }
228
+ }
229
+ if (!(await waitForExit(child.exited, 5_000))) {
230
+ fail(`Pier process session ${childIdentity.sessionId} retained child processes`)
231
+ }
232
+ }
233
+
234
+ function requestStop() {
235
+ stopRequested = true
236
+ stopping ??= stopChild()
237
+ }
238
+
239
+ process.on('SIGTERM', requestStop)
240
+ process.on('SIGINT', requestStop)
241
+
242
+ try {
243
+ config = await readControlInput()
244
+ if (
245
+ !config ||
246
+ typeof config !== 'object' ||
247
+ typeof config.command !== 'string' ||
248
+ !Array.isArray(config.args) ||
249
+ typeof config.cwd !== 'string' ||
250
+ !config.env ||
251
+ typeof config.env !== 'object' ||
252
+ typeof config.jobsDirectory !== 'string' ||
253
+ typeof config.jobName !== 'string' ||
254
+ typeof config.dockerCommand !== 'string'
255
+ ) {
256
+ fail('Pier supervisor launch request is malformed')
257
+ }
258
+
259
+ const identity = readJson(join(directory, identityFile), 'Pier trial identity')
260
+ if (stopRequested || existsSync(join(directory, stopFile))) {
261
+ const removedContainers = removeTrialContainers(config)
262
+ writeJsonAtomic(directory, terminalFile, {
263
+ schemaVersion: 1,
264
+ kind: 'pier-trial-terminal',
265
+ status: 'stopped',
266
+ processExited: true,
267
+ containersRemoved: true,
268
+ removedContainers,
269
+ })
270
+ process.exitCode = 0
271
+ } else {
272
+ const spawned = spawn(config.command, config.args, {
273
+ cwd: config.cwd,
274
+ env: config.env,
275
+ detached: true,
276
+ stdio: 'ignore',
277
+ })
278
+ if (spawned.pid === undefined) fail('Pier process started without a pid')
279
+ const exited = new Promise((resolveExit) => {
280
+ let settled = false
281
+ spawned.once('error', (error) => {
282
+ if (settled) return
283
+ settled = true
284
+ resolveExit({ code: null, signal: null, error })
285
+ })
286
+ spawned.once('close', (code, signal) => {
287
+ if (settled) return
288
+ settled = true
289
+ resolveExit({ code, signal })
290
+ })
291
+ })
292
+ child = { process: spawned, exited }
293
+ childIdentity = processIdentity(spawned.pid)
294
+ writeJsonAtomic(directory, identityFile, {
295
+ ...identity,
296
+ state: 'running',
297
+ pier: childIdentity,
298
+ })
299
+
300
+ if (stopRequested || existsSync(join(directory, stopFile))) {
301
+ stopRequested = true
302
+ stopping = stopChild()
303
+ }
304
+ const exit = await exited
305
+ if (stopping) await stopping
306
+ else await stopChild()
307
+ const removedContainers = removeTrialContainers(config)
308
+ const status = stopRequested ? 'stopped' : exit.code === 0 ? 'completed' : 'failed'
309
+ writeJsonAtomic(directory, terminalFile, {
310
+ schemaVersion: 1,
311
+ kind: 'pier-trial-terminal',
312
+ status,
313
+ processExited: true,
314
+ containersRemoved: true,
315
+ removedContainers,
316
+ exitCode: exit.code,
317
+ signal: exit.signal,
318
+ ...(exit.error ? { error: 'Pier process failed to start' } : {}),
319
+ ...(status === 'failed' && !exit.error
320
+ ? { error: `Pier process exited ${exit.signal ?? exit.code ?? 'without status'}` }
321
+ : {}),
322
+ })
323
+ }
324
+ } catch (error) {
325
+ const cleanupErrors = []
326
+ try {
327
+ requestStop()
328
+ if (stopping) await stopping
329
+ } catch (cleanup) {
330
+ cleanupErrors.push(cleanup)
331
+ }
332
+ if (config) {
333
+ try {
334
+ removeTrialContainers(config)
335
+ } catch (cleanup) {
336
+ cleanupErrors.push(cleanup)
337
+ }
338
+ }
339
+ writeJsonAtomic(directory, terminalFile, {
340
+ schemaVersion: 1,
341
+ kind: 'pier-trial-terminal',
342
+ status: 'failed',
343
+ processExited: !childIdentity || !processMatches(childIdentity),
344
+ containersRemoved: cleanupErrors.length === 0,
345
+ error: `${error instanceof Error ? error.message : String(error)}${
346
+ cleanupErrors.length > 0
347
+ ? `; cleanup failed: ${cleanupErrors.map((item) => item?.message ?? String(item)).join('; ')}`
348
+ : ''
349
+ }`,
350
+ })
351
+ process.exitCode = 1
352
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-bench",
3
- "version": "4.0.0",
3
+ "version": "4.0.3",
4
4
  "type": "module",
5
5
  "description": "Benchmark adapters and execution for agent-runtime across coding, tool-use, RAG, memory, browser, and terminal tasks.",
6
6
  "repository": {
@@ -29,7 +29,7 @@
29
29
  },
30
30
  "dependencies": {
31
31
  "@tangle-network/agent-eval": "^2.0.29",
32
- "@tangle-network/agent-interface": "^5.10.33",
32
+ "@tangle-network/agent-interface": "^5.10.34",
33
33
  "@tangle-network/agent-knowledge": "^23.0.0",
34
34
  "@tangle-network/agent-runtime": "^11.0.0",
35
35
  "@tangle-network/sandbox": "^1.0.233"
@@ -66,7 +66,7 @@
66
66
  },
67
67
  "scripts": {
68
68
  "prebuild": "pnpm --dir .. build",
69
- "build": "tsdown",
69
+ "build": "tsdown && cp src/pier-trial-supervisor.mjs dist/",
70
70
  "gate": "tsx src/corpus-replay.mts corpus/finsearch.jsonl --selector",
71
71
  "gate-cli": "tsx src/gate-cli.mts",
72
72
  "run-benchmarks": "tsx src/run-benchmarks-cli.mts",
@@ -100,7 +100,7 @@ writeFileSync(
100
100
  join(reportDir, 'results.json'),
101
101
  JSON.stringify({
102
102
  resolved_ids: [taskId],
103
- results: [{ task_id: taskId, is_resolved: true, parser_results: { installedVenv: true } }],
103
+ results: [{ task_id: taskId, is_resolved: true, parser_results: { installedVenv: 'passed' } }],
104
104
  }),
105
105
  )
106
106
  `,
@@ -306,6 +306,7 @@ for name in sorted(expected):
306
306
  await run('npm', ['exec', '--', 'tsx', 'index.ts'], consumerDir)
307
307
  await run('npm', ['exec', '--', 'tsx', 'managed-execution.ts'], consumerDir)
308
308
  const installedPackage = path.join(consumerDir, 'node_modules', '@tangle-network', 'agent-bench')
309
+ await access(path.join(installedPackage, 'dist', 'pier-trial-supervisor.mjs'))
309
310
  const prepared = await run(
310
311
  'npm',
311
312
  [
@@ -55,7 +55,7 @@ import { executeAgentCandidateExperimentCell } from '@tangle-network/agent-runti
55
55
 
56
56
  import { createPierCandidateExecutionOptions } from '../src/pier-agent'
57
57
  import { createPierResultGrader } from '../src/pier-result-grader'
58
- import { FilePierCandidateTrialController } from '../src/pier-trial-controller'
58
+ import { createPierTaskTrialController } from '../src/pier-trial-controller'
59
59
 
60
60
  const pinnedPierCommit = 'e69a20e4e0ac073ec71fde0274bab3d9f40bac87'
61
61
  const pinnedPierVersion = '0.3.0'
@@ -624,104 +624,16 @@ ${proofArm === 'success' ? "(task / 'src/status.txt').write_text('ready\\nowner=
624
624
  const claimStore = new FileAgentCandidateExecutionClaimStore({
625
625
  directory: path.join(scratch, 'claims'),
626
626
  })
627
- let acceptedRewards: { reward: number; patch_applied: number } | undefined
628
- let acceptedTrialPath: string | undefined
629
- const jobName = `tangle-runtime-candidate-no-model-${proofArm}`
630
- const controller = new FilePierCandidateTrialController({
627
+ const controller = createPierTaskTrialController({
631
628
  directory: path.join(scratch, 'trial-control'),
632
- readResult: async ({ jobsDirectory, jobName }) => {
633
- const trialResult = findTrialResult(path.join(jobsDirectory, jobName))
634
- if (!trialResult) return undefined
635
- return {
636
- value: trialResult.value,
637
- resultBytes: readFileSync(trialResult.path),
638
- taskPatch: readFileSync(
639
- path.join(path.dirname(trialResult.path), 'artifacts', 'model.patch'),
640
- ),
641
- }
642
- },
643
- launch: (staged, { request }) => {
644
- const evaluatorArgs = Object.keys(staged.evaluatorEnv).flatMap((name) => [
645
- '--agent-env',
646
- `${name}=\${${name}}`,
647
- ])
648
- return {
649
- command: 'uv',
650
- args: [
651
- 'run',
652
- 'pier',
653
- 'run',
654
- '--path',
655
- taskDir,
656
- ...staged.agentArgs,
657
- ...staged.attemptArgs,
658
- ...evaluatorArgs,
659
- '--env',
660
- 'docker',
661
- '--job-name',
662
- jobName,
663
- '--jobs-dir',
664
- jobsDir,
665
- '--n-concurrent',
666
- '1',
667
- '--agent-timeout-multiplier',
668
- '2',
669
- '--quiet',
670
- ],
671
- cwd: pierRepo,
672
- env: { ...process.env, PYTHONPATH: benchDir, ...staged.evaluatorEnv },
673
- jobsDirectory: jobsDir,
674
- jobName,
675
- readResult: async () => {
676
- const trialResult = findTrialResult(jobsDir)
677
- if (!trialResult) throw new Error(`Pier emitted no trial result under ${jobsDir}`)
678
- const result = trialResult.value
679
- if (result.exception_info !== null) {
680
- throw new Error(
681
- `Pier trial captured an exception: ${JSON.stringify(result.exception_info)}`,
682
- )
683
- }
684
- const rewards = result.verifier_result?.rewards
685
- if (
686
- rewards?.reward !== expectedReward ||
687
- rewards?.patch_applied !== expectedPatchApplied
688
- ) {
689
- throw new Error(
690
- `Pier ${proofArm} control returned unexpected rewards: ${JSON.stringify(rewards)}`,
691
- )
692
- }
693
- const agentResult = result.agent_result
694
- for (const name of ['n_input_tokens', 'n_cache_tokens', 'n_output_tokens', 'cost_usd']) {
695
- if (agentResult?.[name] !== null) {
696
- throw new Error(
697
- `Pier must not author protected usage ${name}: ${agentResult?.[name]}`,
698
- )
699
- }
700
- }
701
- const observedElapsedMs = agentResult?.metadata?.observedElapsedMs
702
- if (!Number.isInteger(observedElapsedMs) || observedElapsedMs < 0) {
703
- throw new Error(`Pier omitted protected elapsed time: ${observedElapsedMs}`)
704
- }
705
- const endedAt = Date.now()
706
- await traceStore.appendRun({
707
- runId: request.trace.runId,
708
- scenarioId: benchmarkTask.scenario.id,
709
- startedAt: endedAt - observedElapsedMs,
710
- endedAt,
711
- status: 'completed',
712
- tags: { ...request.trace.tags },
713
- })
714
- acceptedRewards = rewards
715
- acceptedTrialPath = path.relative(jobsDir, trialResult.path)
716
- return {
717
- value: result,
718
- resultBytes: readFileSync(trialResult.path),
719
- taskPatch: readFileSync(
720
- path.join(path.dirname(trialResult.path), 'artifacts', 'model.patch'),
721
- ),
722
- }
723
- },
724
- }
629
+ jobsDirectory: jobsDir,
630
+ maxEvidenceBytes: 16 * 1024 * 1024,
631
+ tasks: [{ taskDigest: benchmarkTask.digest, directory: taskDir }],
632
+ command: {
633
+ command: 'uv',
634
+ prefix: ['run', '--frozen', 'pier'],
635
+ cwd: pierRepo,
636
+ env: { ...process.env, PYTHONPATH: benchDir },
725
637
  },
726
638
  })
727
639
  const experiment = sealCandidateExperiment({
@@ -770,9 +682,31 @@ ${proofArm === 'success' ? "(task / 'src/status.txt').write_text('ready\\nowner=
770
682
  }),
771
683
  })
772
684
  const { materializationReceipt, receipt } = evidence
773
- if (!acceptedRewards || !acceptedTrialPath) {
774
- throw new Error('atomic Pier executor returned without accepted verifier evidence')
685
+ const trialResult = findTrialResult(jobsDir)
686
+ if (!trialResult) throw new Error(`Pier emitted no trial result under ${jobsDir}`)
687
+ const { exception_info, verifier_result, agent_result } = trialResult.value
688
+ if (exception_info !== null) {
689
+ throw new Error(`Pier trial captured an exception: ${JSON.stringify(exception_info)}`)
690
+ }
691
+ const acceptedRewards = verifier_result?.rewards
692
+ if (
693
+ acceptedRewards?.reward !== expectedReward ||
694
+ acceptedRewards?.patch_applied !== expectedPatchApplied
695
+ ) {
696
+ throw new Error(
697
+ `Pier ${proofArm} control returned unexpected rewards: ${JSON.stringify(acceptedRewards)}`,
698
+ )
699
+ }
700
+ for (const name of ['n_input_tokens', 'n_cache_tokens', 'n_output_tokens', 'cost_usd']) {
701
+ if (agent_result?.[name] !== null) {
702
+ throw new Error(`Pier must not author protected usage ${name}: ${agent_result?.[name]}`)
703
+ }
704
+ }
705
+ const observedElapsedMs = agent_result?.metadata?.observedElapsedMs
706
+ if (!Number.isInteger(observedElapsedMs) || observedElapsedMs < 0) {
707
+ throw new Error(`Pier omitted protected elapsed time: ${observedElapsedMs}`)
775
708
  }
709
+ const acceptedTrialPath = path.relative(jobsDir, trialResult.path)
776
710
  const patch = readFileSync(
777
711
  path.join(jobsDir, path.dirname(acceptedTrialPath), 'artifacts', 'model.patch'),
778
712
  'utf8',
@@ -16,7 +16,8 @@
16
16
  * argv, and the results.json shape.
17
17
  */
18
18
 
19
- import { join } from 'node:path'
19
+ import { randomUUID } from 'node:crypto'
20
+ import { isAbsolute, join } from 'node:path'
20
21
  import {
21
22
  benchRoot,
22
23
  preflightVenvImports,
@@ -61,7 +62,12 @@ interface TbTaskRow {
61
62
 
62
63
  interface TbReport {
63
64
  resolved_ids?: string[]
64
- results?: Array<{ task_id: string; is_resolved: boolean | null; parser_results?: unknown }>
65
+ results?: Array<{
66
+ task_id: string
67
+ is_resolved: boolean | null
68
+ failure_mode?: string
69
+ parser_results?: Record<string, string> | null
70
+ }>
65
71
  }
66
72
 
67
73
  /** Enumerate dataset tasks via tb's Dataset loader (caches from the registry on
@@ -138,11 +144,16 @@ export function createTerminalBenchAdapter(): RuntimeBenchmark {
138
144
  },
139
145
 
140
146
  async evaluate(task: BenchTask, artifact: string): Promise<BenchEvaluation> {
141
- const runId = safeRunId('bench', `${task.id}-${Date.now()}`)
147
+ const runId = safeRunId('bench', `${task.id}-${randomUUID()}`)
148
+ const evidenceRoot = process.env.TERMINAL_BENCH_EVIDENCE_DIR
149
+ if (evidenceRoot && !isAbsolute(evidenceRoot)) {
150
+ throw new Error('TERMINAL_BENCH_EVIDENCE_DIR must be an absolute path')
151
+ }
142
152
  return runStagedJudge({
143
153
  tmpPrefix: 'tbench-',
144
154
  bin: terminalBenchBin(),
145
155
  cwd: () => benchRoot,
156
+ ...(evidenceRoot && { capture: { destination: join(evidenceRoot, runId) } }),
146
157
  async stage(dir) {
147
158
  await stageFile(join(dir, 'attempt.sh'), artifact)
148
159
  },
@@ -163,12 +174,34 @@ export function createTerminalBenchAdapter(): RuntimeBenchmark {
163
174
  ],
164
175
  async parseReport(dir) {
165
176
  const report = await readJsonReport<TbReport>(join(dir, 'runs', runId, 'results.json'))
166
- const resolved = (report.resolved_ids ?? []).includes(task.id)
167
- const trial = report.results?.find((r) => r.task_id === task.id)
177
+ const trials = report?.results
178
+ const trial = trials?.[0]
179
+ if (!Array.isArray(trials) || trials.length !== 1 || trial?.task_id !== task.id) {
180
+ throw new Error(`terminal-bench: report has no unique trial for ${task.id}`)
181
+ }
182
+ const checks = trial.parser_results
183
+ if (
184
+ typeof trial.is_resolved !== 'boolean' ||
185
+ !checks || Array.isArray(checks) || typeof checks !== 'object' ||
186
+ Object.keys(checks).length === 0
187
+ ) {
188
+ throw new Error(`terminal-bench: no verifier verdict for ${task.id} (${trial.failure_mode ?? 'unknown'})`)
189
+ }
190
+ const resolved = trial.is_resolved
191
+ const statuses = Object.values(checks)
192
+ if (
193
+ statuses.some((status) => status !== 'passed' && status !== 'failed') ||
194
+ statuses.every((status) => status === 'passed') !== resolved ||
195
+ !Array.isArray(report.resolved_ids) ||
196
+ report.resolved_ids.length !== Number(resolved) ||
197
+ report.resolved_ids.includes(task.id) !== resolved
198
+ ) {
199
+ throw new Error(`terminal-bench: report outcome disagrees with trial ${task.id}`)
200
+ }
168
201
  return {
169
202
  passed: resolved,
170
203
  score: resolved ? 1 : 0,
171
- notes: JSON.stringify(trial?.parser_results ?? report.resolved_ids ?? {}),
204
+ notes: JSON.stringify(checks),
172
205
  raw: {},
173
206
  }
174
207
  },
package/src/pier-agent.ts CHANGED
@@ -626,6 +626,7 @@ export function createPierCandidateExecutionOptions<Format extends AgentCandidat
626
626
  context.signal.throwIfAborted()
627
627
  const identity = trialIdentity(request.executionId, request.executionPlan.value.digest)
628
628
  if (trials.has(identity)) throw new Error('Pier trial identity is already active')
629
+ const startedAt = Date.now()
629
630
  const trial = options.controller.start(staged, {
630
631
  request,
631
632
  traceStore: context.traceStore,
@@ -645,9 +646,26 @@ export function createPierCandidateExecutionOptions<Format extends AgentCandidat
645
646
  }
646
647
  trials.set(identity, active)
647
648
  const result = sealPierTrialResult(await awaitAbortableTrial(trial, context.signal))
649
+ const endedAt = Math.max(startedAt, Date.now())
648
650
  active.result = result
649
651
  officialResults.set(request.executionId, result)
650
- return protectedCaptureFromPierResult(request, result.value)
652
+ const capture = protectedCaptureFromPierResult(request, result.value)
653
+ // Custom controllers may already retain a terminal trace. The standard task controller
654
+ // supplies official results; the execution boundary records its observed trial interval.
655
+ if (!(await context.traceStore.getRun(request.trace.runId))) {
656
+ await context.traceStore.appendRun({
657
+ runId: request.trace.runId,
658
+ scenarioId: request.benchmark.task.scenario.id,
659
+ startedAt,
660
+ endedAt,
661
+ status:
662
+ capture.termination.kind === 'exit' && capture.termination.exitCode === 0
663
+ ? 'completed'
664
+ : 'failed',
665
+ tags: request.trace.tags,
666
+ })
667
+ }
668
+ return capture
651
669
  },
652
670
  stop: async (request) => {
653
671
  assertTerminationAcknowledged(