@tangle-network/agent-bench 5.0.0 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/pier-agent.ts CHANGED
@@ -8,6 +8,7 @@ import type {
8
8
  AgentCandidateBenchmarkGraderPort,
9
9
  AgentCandidateExecutionClaimStore,
10
10
  AgentCandidateExecutionFormat,
11
+ AgentCandidateExecutorFinalCapture,
11
12
  AgentCandidateExecutorRequest,
12
13
  AgentCandidateExecutorStopRequest,
13
14
  AgentCandidateExecutorPort,
@@ -44,6 +45,8 @@ export interface StagedPierCandidateExecution {
44
45
  readonly profileDirectory: string
45
46
  readonly planPath: string
46
47
  readonly receiptPath: string
48
+ /** Evaluator-owned copy of the exact graph invocation when the controller supports it. */
49
+ readonly graphInvocationPath?: string
47
50
  readonly agentArgs: readonly string[]
48
51
  /** Executor-only model and trace bindings; never present on the prepared object or disk. */
49
52
  readonly evaluatorEnv: Readonly<Record<string, string>>
@@ -76,6 +79,8 @@ export type PierCandidateTrialIdentity = Readonly<AgentCandidateExecutorStopRequ
76
79
  export interface PierCandidateTrialController<
77
80
  Format extends AgentCandidateExecutionFormat = 'experiment',
78
81
  > {
82
+ /** This controller runs the sealed graph through the protected Pier trial. */
83
+ readonly graphDispatch?: true
79
84
  start(
80
85
  staged: StagedPierCandidateExecution,
81
86
  context: {
@@ -100,6 +105,10 @@ export interface PierCandidateTrialResult {
100
105
  readonly resultBytes: Uint8Array
101
106
  /** Exact `/logs/artifacts/model.patch` bytes emitted before official tests. */
102
107
  readonly taskPatch: Uint8Array
108
+ /** Retained evaluator graph record. Agent metadata and stdout cannot supply this field. */
109
+ readonly graphExecution?: AgentCandidateExecutorFinalCapture['graphExecution']
110
+ /** The trusted coordinator reached a graph deliverable that may be independently graded. */
111
+ readonly graphDelivered?: boolean
103
112
  }
104
113
 
105
114
  export interface PierCandidateOfficialResult {
@@ -361,8 +370,13 @@ async function stageKnowledge(
361
370
  export async function stagePreparedPierCandidateExecution(
362
371
  options: StagePreparedPierCandidateOptions<AgentCandidateExecutionFormat>,
363
372
  request: AgentCandidateExecutorRequest<AgentCandidateExecutionFormat>,
373
+ graphDispatch?: true,
364
374
  ): Promise<StagedPierCandidateExecution> {
365
375
  const { prepared } = options
376
+ const graph = request.executionPlan.value.material.launch.graph
377
+ if (graph && graphDispatch !== true) {
378
+ throw new Error('this Pier process adapter cannot execute a sealed graph invocation')
379
+ }
366
380
  nonEmpty(options.pierVersion, 'pierVersion')
367
381
  const directory = absoluteHostPath(options.directory, 'directory')
368
382
  await mkdir(directory, { mode: 0o700 })
@@ -428,6 +442,9 @@ export async function stagePreparedPierCandidateExecution(
428
442
 
429
443
  const planPath = join(directory, 'execution-plan.json')
430
444
  const receiptPath = join(directory, 'materialization-receipt.json')
445
+ const graphInvocationPath = graph
446
+ ? await stageGraphInvocation(directory, graph.invocation, request.graphInvocation)
447
+ : undefined
431
448
  await Promise.all([
432
449
  writeFile(planPath, request.executionPlan.bytes, { mode: 0o600, flag: 'wx' }),
433
450
  writeFile(receiptPath, request.materializationReceipt.bytes, { mode: 0o600, flag: 'wx' }),
@@ -466,12 +483,26 @@ export async function stagePreparedPierCandidateExecution(
466
483
  profileDirectory,
467
484
  planPath,
468
485
  receiptPath,
486
+ ...(graphInvocationPath ? { graphInvocationPath } : {}),
469
487
  agentArgs,
470
488
  evaluatorEnv: protectedEnvironment(prepared, request),
471
489
  attemptArgs: ['--n-attempts', '1', '--max-retries', '0'],
472
490
  }
473
491
  }
474
492
 
493
+ async function stageGraphInvocation(
494
+ directory: string,
495
+ artifact: { sha256: string; byteLength: number },
496
+ bytes: Uint8Array | undefined,
497
+ ): Promise<string> {
498
+ if (!bytes || bytes.byteLength !== artifact.byteLength || sha256(bytes) !== artifact.sha256) {
499
+ throw new Error('Pier graph invocation bytes differ from the sealed plan')
500
+ }
501
+ const path = join(directory, 'graph-invocation.json')
502
+ await writeFile(path, bytes, { mode: 0o600, flag: 'wx' })
503
+ return path
504
+ }
505
+
475
506
  function exceptionType(value: unknown): string | undefined {
476
507
  const info = value && typeof value === 'object' ? (value as Record<string, unknown>) : undefined
477
508
  for (const key of ['exception_type', 'type', 'name']) {
@@ -532,6 +563,11 @@ function sealPierTrialResult(value: PierCandidateTrialResult): PierCandidateTria
532
563
  assert.deepEqual(parsed, value.value, 'Pier parsed result differs from result.json bytes')
533
564
  const resultBytes = Uint8Array.from(value.resultBytes)
534
565
  const taskPatch = Uint8Array.from(value.taskPatch)
566
+ const graph = value.graphExecution
567
+ if (graph && !(graph.record instanceof Uint8Array)) {
568
+ throw new Error('Pier graph execution requires raw evaluator record bytes')
569
+ }
570
+ const graphExecution = graph && Object.freeze({ ...graph, record: Uint8Array.from(graph.record) })
535
571
  return Object.freeze({
536
572
  value: parsed,
537
573
  get resultBytes(): Uint8Array {
@@ -540,6 +576,8 @@ function sealPierTrialResult(value: PierCandidateTrialResult): PierCandidateTria
540
576
  get taskPatch(): Uint8Array {
541
577
  return Uint8Array.from(taskPatch)
542
578
  },
579
+ ...(graphExecution ? { graphExecution } : {}),
580
+ ...(value.graphDelivered === undefined ? {} : { graphDelivered: value.graphDelivered }),
543
581
  })
544
582
  }
545
583
 
@@ -614,6 +652,7 @@ export function createPierCandidateExecutionOptions<Format extends AgentCandidat
614
652
  const trialIdentity = (executionId: string, executionPlanDigest: string): string =>
615
653
  JSON.stringify([executionId, executionPlanDigest])
616
654
  const executor: AgentCandidateExecutorPort<Format> = {
655
+ ...(options.controller.graphDispatch ? { graphDispatch: true } : {}),
617
656
  execute: async (request, context) => {
618
657
  context.signal.throwIfAborted()
619
658
  if (
@@ -622,7 +661,11 @@ export function createPierCandidateExecutionOptions<Format extends AgentCandidat
622
661
  ) {
623
662
  throw new Error('Pier executor received a different prepared candidate')
624
663
  }
625
- const staged = await stagePreparedPierCandidateExecution(options, request)
664
+ const staged = await stagePreparedPierCandidateExecution(
665
+ options,
666
+ request,
667
+ options.controller.graphDispatch,
668
+ )
626
669
  context.signal.throwIfAborted()
627
670
  const identity = trialIdentity(request.executionId, request.executionPlan.value.digest)
628
671
  if (trials.has(identity)) throw new Error('Pier trial identity is already active')
@@ -692,6 +735,11 @@ export function createPierCandidateExecutionOptions<Format extends AgentCandidat
692
735
  result = recovered ? sealPierTrialResult(recovered) : undefined
693
736
  }
694
737
  if (!result) return {}
738
+ if (result.graphExecution && result.graphDelivered === false) {
739
+ trials.delete(identity)
740
+ officialResults.delete(request.executionId)
741
+ return { graphExecution: result.graphExecution }
742
+ }
695
743
  officialResults.set(request.executionId, result)
696
744
  const task = options.prepared.benchmark.task
697
745
  const outcome = task.outcome
@@ -707,7 +755,10 @@ export function createPierCandidateExecutionOptions<Format extends AgentCandidat
707
755
  patch: result.taskPatch,
708
756
  })
709
757
  trials.delete(identity)
710
- return { taskOutcome }
758
+ return {
759
+ taskOutcome,
760
+ ...(result.graphExecution ? { graphExecution: result.graphExecution } : {}),
761
+ }
711
762
  },
712
763
  }
713
764
  const grader: AgentCandidateBenchmarkGraderPort = {
@@ -105,6 +105,8 @@ export interface FilePierCandidateTrialControllerOptions<
105
105
  > {
106
106
  /** Shared evaluator-owned control root, available to crash-recovery workers. */
107
107
  readonly directory: string
108
+ /** Both the registered launch and durable result reader handle sealed graph dispatch. */
109
+ readonly graphDispatch?: true
108
110
  readonly launch?: (
109
111
  staged: StagedPierCandidateExecution,
110
112
  context: {
@@ -137,6 +139,8 @@ export interface CreatePierTaskTrialControllerOptions {
137
139
  readonly prefix?: readonly string[]
138
140
  }
139
141
  readonly dockerConnection?: PierDockerConnection
142
+ /** Allow the bundled graph coordinator for the approved zero-model task cohort. */
143
+ readonly graphDispatch?: true
140
144
  }
141
145
 
142
146
  /** Run one approved Pier task and reopen its official result through the durable controller. */
@@ -158,16 +162,21 @@ export function createPierTaskTrialController<
158
162
  const { prefix = [], env, ...command } = options.command
159
163
  const argumentsPrefix = [...prefix]
160
164
  const environment = { ...env }
165
+ const graphDriver = fileURLToPath(new URL('../pier_agents/graph_driver.mjs', import.meta.url))
161
166
  const readResult = async ({ jobsDirectory, jobName }: { jobsDirectory: string; jobName: string }) =>
162
167
  readOfficialTrial(join(jobsDirectory, jobName), maxEvidenceBytes)
163
168
  return new FilePierCandidateTrialController<Format>({
164
169
  directory: options.directory,
165
170
  dockerConnection: options.dockerConnection,
171
+ ...(options.graphDispatch ? { graphDispatch: true } : {}),
166
172
  readResult,
167
173
  launch(staged, { request }) {
168
174
  const task = tasks.get(request.benchmark.task.digest)
169
175
  if (!task) throw new Error('Pier has no directory for this approved task')
170
176
  assertRealDirectory(task, 'Pier task directory')
177
+ if (staged.graphInvocationPath && request.benchmark.task.limits.maxModelCalls !== 0) {
178
+ throw new Error('The bundled Pier graph coordinator requires a zero-model task')
179
+ }
171
180
  const jobName = `candidate-${trialKey({
172
181
  executionId: request.executionId,
173
182
  executionPlanDigest: request.executionPlan.value.digest,
@@ -178,6 +187,13 @@ export function createPierTaskTrialController<
178
187
  ...argumentsPrefix,
179
188
  'run', '--path', task,
180
189
  ...staged.agentArgs,
190
+ ...(staged.graphInvocationPath
191
+ ? [
192
+ '--agent-kwarg', `graph_invocation_path=${staged.graphInvocationPath}`,
193
+ '--agent-kwarg', `graph_node_path=${process.execPath}`,
194
+ '--agent-kwarg', `graph_driver_path=${graphDriver}`,
195
+ ]
196
+ : []),
181
197
  ...staged.attemptArgs,
182
198
  ...Object.keys(staged.evaluatorEnv).flatMap((name) => ['--agent-env', `${name}=\${${name}}`]),
183
199
  '--env', 'docker', '--job-name', jobName, '--jobs-dir', jobsDirectory,
@@ -213,11 +229,53 @@ function readOfficialTrial(directory: string, maxEvidenceBytes: number): PierCan
213
229
  if (result) throw new Error('Expected one official result for the approved Pier task')
214
230
  const artifacts = join(trial, 'artifacts')
215
231
  assertRealDirectory(artifacts, 'Pier trial artifacts directory')
216
- result = { value, resultBytes, taskPatch: readOfficialTrialFile(join(artifacts, 'model.patch'), maxEvidenceBytes) }
232
+ const taskPatch = readOfficialTrialFile(join(artifacts, 'model.patch'), maxEvidenceBytes)
233
+ result = { value, resultBytes, taskPatch, ...readOfficialGraph(value, taskPatch) }
217
234
  }
218
235
  return result
219
236
  }
220
237
 
238
+ function readOfficialGraph(
239
+ value: unknown,
240
+ patch: Uint8Array,
241
+ ): Pick<PierCandidateTrialResult, 'graphExecution' | 'graphDelivered'> {
242
+ const raw = (value as {
243
+ agent_result?: { metadata?: { graphExecution?: unknown } }
244
+ }).agent_result?.metadata?.graphExecution
245
+ if (raw === undefined) return {}
246
+ const graph = raw as {
247
+ runId: string
248
+ graphDigest: `sha256:${string}`
249
+ invocationDigest: `sha256:${string}`
250
+ record: string
251
+ delivered: boolean
252
+ }
253
+ if (
254
+ typeof graph.runId !== 'string' ||
255
+ !graph.runId ||
256
+ !sha256Pattern.test(graph.graphDigest) ||
257
+ !sha256Pattern.test(graph.invocationDigest) ||
258
+ typeof graph.delivered !== 'boolean' ||
259
+ typeof graph.record !== 'string'
260
+ ) {
261
+ throw new Error('Pier emitted invalid evaluator graph evidence')
262
+ }
263
+ const record = Buffer.from(graph.record, 'base64')
264
+ if (!record.length || record.toString('base64') !== graph.record) {
265
+ throw new Error('Pier emitted invalid evaluator graph record bytes')
266
+ }
267
+ return {
268
+ graphDelivered: graph.delivered,
269
+ graphExecution: {
270
+ runId: graph.runId,
271
+ graphDigest: graph.graphDigest,
272
+ invocationDigest: graph.invocationDigest,
273
+ taskArtifactDigest: `sha256:${createHash('sha256').update(patch).digest('hex')}`,
274
+ record,
275
+ },
276
+ }
277
+ }
278
+
221
279
  function readOfficialTrialFile(path: string, maxEvidenceBytes: number): Buffer {
222
280
  const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)
223
281
  try {
@@ -620,6 +678,7 @@ function assertRealDirectory(path: string, label: string): void {
620
678
  export class FilePierCandidateTrialController<
621
679
  Format extends AgentCandidateExecutionFormat = 'experiment',
622
680
  > implements PierCandidateTrialController<Format> {
681
+ readonly graphDispatch?: true
623
682
  private readonly directory: string
624
683
  private readonly launch?: NonNullable<FilePierCandidateTrialControllerOptions<Format>['launch']>
625
684
  private readonly readResult?: NonNullable<FilePierCandidateTrialControllerOptions<Format>['readResult']>
@@ -631,6 +690,10 @@ export class FilePierCandidateTrialController<
631
690
  this.directory = absolutePath(options.directory, 'Pier controller directory')
632
691
  this.launch = options.launch
633
692
  this.readResult = options.readResult
693
+ if (options.graphDispatch && (!options.launch || !options.readResult)) {
694
+ throw new Error('Pier graph dispatch requires both launch and durable graph capture')
695
+ }
696
+ this.graphDispatch = options.graphDispatch
634
697
  const configuredDocker = options.dockerConnection
635
698
  if (configuredDocker?.id === defaultDockerConnectionId) {
636
699
  throw new Error(`${defaultDockerConnectionId} is reserved for the implicit local connection`)
@@ -6,12 +6,15 @@
6
6
  * memorized) — reported, never claimed clean.
7
7
  *
8
8
  * CALIBRATE first (cost gate): TANGLE_API_KEY=… CALIBRATE=1 N=3 tsx bench/src/swe-self-improve.mts
9
- * Full run: TANGLE_API_KEY=… TRAIN_N=4 SELECTION_N=12 TEST_N=12 tsx bench/src/swe-self-improve.mts
9
+ * Full run (set FINAL_EVIDENCE_LEDGER and FINAL_EVIDENCE_REQUEST_ID first):
10
+ * TANGLE_API_KEY=… TRAIN_N=4 SELECTION_N=12 TEST_N=12 tsx bench/src/swe-self-improve.mts
10
11
  *
11
12
  * The run directory is kept (`OUT_DIR`, default `.swe-run`): its ledger is the checkpoint, so the
12
13
  * same command continues an interrupted search.
13
14
  */
15
+ import { readFileSync } from 'node:fs'
14
16
  import { join } from 'node:path'
17
+ import { openFinalEvidenceLedger } from '@tangle-network/agent-eval/experiment'
15
18
  import { type AgentProfile, canonicalCandidateDigest } from '@tangle-network/agent-interface'
16
19
  import {
17
20
  refine,
@@ -21,6 +24,23 @@ import {
21
24
  } from '@tangle-network/agent-runtime/kernel'
22
25
  import { createSweBenchEnvironment } from './swe-bench-env'
23
26
 
27
+ function sweFinalEvidence() {
28
+ const path = process.env.FINAL_EVIDENCE_LEDGER
29
+ const requestId = process.env.FINAL_EVIDENCE_REQUEST_ID
30
+ if (path === undefined && requestId === undefined) return undefined
31
+ if (!path?.trim() || !requestId?.trim()) {
32
+ throw new Error('Set FINAL_EVIDENCE_LEDGER and FINAL_EVIDENCE_REQUEST_ID together')
33
+ }
34
+ const sources = ['./swe-bench-env.ts', './benchmarks/swe-bench.ts', './benchmarks/_harness.ts']
35
+ return {
36
+ ledger: openFinalEvidenceLedger({ path }),
37
+ requestId,
38
+ evaluatorDigest: canonicalCandidateDigest(
39
+ sources.map((file) => readFileSync(new URL(file, import.meta.url), 'utf8')),
40
+ ),
41
+ }
42
+ }
43
+
24
44
  async function main(): Promise<void> {
25
45
  const routerKey = process.env.TANGLE_API_KEY
26
46
  if (!routerKey) throw new Error('TANGLE_API_KEY required (worker + author call the router)')
@@ -74,6 +94,7 @@ async function main(): Promise<void> {
74
94
  return
75
95
  }
76
96
 
97
+ const finalEvidence = sweFinalEvidence()
77
98
  const trainN = Number(process.env.TRAIN_N ?? 4)
78
99
  const selectionN = Number(process.env.SELECTION_N ?? 12)
79
100
  const testN = Number(process.env.TEST_N ?? 12)
@@ -83,6 +104,7 @@ async function main(): Promise<void> {
83
104
  train: all.slice(0, trainN),
84
105
  selection: all.slice(trainN, trainN + selectionN),
85
106
  test: all.slice(trainN + selectionN),
107
+ finalEvidence,
86
108
  claim: {
87
109
  use: 'comparison',
88
110
  population: { id: 'swe-bench-verified', description: 'SWE-bench Verified instances' },