@tangle-network/agent-bench 5.0.0 → 7.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,10 @@ 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
84
+ /** This controller can launch the signed profile as a leaf of the sealed graph. */
85
+ readonly graphLeafDispatch?: true
79
86
  start(
80
87
  staged: StagedPierCandidateExecution,
81
88
  context: {
@@ -100,6 +107,12 @@ export interface PierCandidateTrialResult {
100
107
  readonly resultBytes: Uint8Array
101
108
  /** Exact `/logs/artifacts/model.patch` bytes emitted before official tests. */
102
109
  readonly taskPatch: Uint8Array
110
+ /** Retained evaluator graph record. Agent metadata and stdout cannot supply this field. */
111
+ readonly graphExecution?: AgentCandidateExecutorFinalCapture['graphExecution']
112
+ /** The trusted coordinator reached a graph deliverable that may be independently graded. */
113
+ readonly graphDelivered?: boolean
114
+ /** Evaluator-side observation of the signed native graph leaf. */
115
+ readonly nativeEvidence?: Uint8Array
103
116
  }
104
117
 
105
118
  export interface PierCandidateOfficialResult {
@@ -361,8 +374,13 @@ async function stageKnowledge(
361
374
  export async function stagePreparedPierCandidateExecution(
362
375
  options: StagePreparedPierCandidateOptions<AgentCandidateExecutionFormat>,
363
376
  request: AgentCandidateExecutorRequest<AgentCandidateExecutionFormat>,
377
+ graphDispatch?: true,
364
378
  ): Promise<StagedPierCandidateExecution> {
365
379
  const { prepared } = options
380
+ const graph = request.executionPlan.value.material.launch.graph
381
+ if (graph && graphDispatch !== true) {
382
+ throw new Error('this Pier process adapter cannot execute a sealed graph invocation')
383
+ }
366
384
  nonEmpty(options.pierVersion, 'pierVersion')
367
385
  const directory = absoluteHostPath(options.directory, 'directory')
368
386
  await mkdir(directory, { mode: 0o700 })
@@ -428,6 +446,9 @@ export async function stagePreparedPierCandidateExecution(
428
446
 
429
447
  const planPath = join(directory, 'execution-plan.json')
430
448
  const receiptPath = join(directory, 'materialization-receipt.json')
449
+ const graphInvocationPath = graph
450
+ ? await stageGraphInvocation(directory, graph.invocation, request.graphInvocation)
451
+ : undefined
431
452
  await Promise.all([
432
453
  writeFile(planPath, request.executionPlan.bytes, { mode: 0o600, flag: 'wx' }),
433
454
  writeFile(receiptPath, request.materializationReceipt.bytes, { mode: 0o600, flag: 'wx' }),
@@ -466,12 +487,26 @@ export async function stagePreparedPierCandidateExecution(
466
487
  profileDirectory,
467
488
  planPath,
468
489
  receiptPath,
490
+ ...(graphInvocationPath ? { graphInvocationPath } : {}),
469
491
  agentArgs,
470
492
  evaluatorEnv: protectedEnvironment(prepared, request),
471
493
  attemptArgs: ['--n-attempts', '1', '--max-retries', '0'],
472
494
  }
473
495
  }
474
496
 
497
+ async function stageGraphInvocation(
498
+ directory: string,
499
+ artifact: { sha256: string; byteLength: number },
500
+ bytes: Uint8Array | undefined,
501
+ ): Promise<string> {
502
+ if (!bytes || bytes.byteLength !== artifact.byteLength || sha256(bytes) !== artifact.sha256) {
503
+ throw new Error('Pier graph invocation bytes differ from the sealed plan')
504
+ }
505
+ const path = join(directory, 'graph-invocation.json')
506
+ await writeFile(path, bytes, { mode: 0o600, flag: 'wx' })
507
+ return path
508
+ }
509
+
475
510
  function exceptionType(value: unknown): string | undefined {
476
511
  const info = value && typeof value === 'object' ? (value as Record<string, unknown>) : undefined
477
512
  for (const key of ['exception_type', 'type', 'name']) {
@@ -532,6 +567,12 @@ function sealPierTrialResult(value: PierCandidateTrialResult): PierCandidateTria
532
567
  assert.deepEqual(parsed, value.value, 'Pier parsed result differs from result.json bytes')
533
568
  const resultBytes = Uint8Array.from(value.resultBytes)
534
569
  const taskPatch = Uint8Array.from(value.taskPatch)
570
+ const graph = value.graphExecution
571
+ if (graph && !(graph.record instanceof Uint8Array)) {
572
+ throw new Error('Pier graph execution requires raw evaluator record bytes')
573
+ }
574
+ const graphExecution = graph && Object.freeze({ ...graph, record: Uint8Array.from(graph.record) })
575
+ const nativeEvidence = value.nativeEvidence && Uint8Array.from(value.nativeEvidence)
535
576
  return Object.freeze({
536
577
  value: parsed,
537
578
  get resultBytes(): Uint8Array {
@@ -540,6 +581,9 @@ function sealPierTrialResult(value: PierCandidateTrialResult): PierCandidateTria
540
581
  get taskPatch(): Uint8Array {
541
582
  return Uint8Array.from(taskPatch)
542
583
  },
584
+ ...(graphExecution ? { graphExecution } : {}),
585
+ ...(value.graphDelivered === undefined ? {} : { graphDelivered: value.graphDelivered }),
586
+ ...(nativeEvidence ? { nativeEvidence } : {}),
543
587
  })
544
588
  }
545
589
 
@@ -614,6 +658,7 @@ export function createPierCandidateExecutionOptions<Format extends AgentCandidat
614
658
  const trialIdentity = (executionId: string, executionPlanDigest: string): string =>
615
659
  JSON.stringify([executionId, executionPlanDigest])
616
660
  const executor: AgentCandidateExecutorPort<Format> = {
661
+ ...(options.controller.graphDispatch ? { graphDispatch: true } : {}),
617
662
  execute: async (request, context) => {
618
663
  context.signal.throwIfAborted()
619
664
  if (
@@ -622,7 +667,11 @@ export function createPierCandidateExecutionOptions<Format extends AgentCandidat
622
667
  ) {
623
668
  throw new Error('Pier executor received a different prepared candidate')
624
669
  }
625
- const staged = await stagePreparedPierCandidateExecution(options, request)
670
+ const staged = await stagePreparedPierCandidateExecution(
671
+ options,
672
+ request,
673
+ options.controller.graphDispatch,
674
+ )
626
675
  context.signal.throwIfAborted()
627
676
  const identity = trialIdentity(request.executionId, request.executionPlan.value.digest)
628
677
  if (trials.has(identity)) throw new Error('Pier trial identity is already active')
@@ -692,6 +741,11 @@ export function createPierCandidateExecutionOptions<Format extends AgentCandidat
692
741
  result = recovered ? sealPierTrialResult(recovered) : undefined
693
742
  }
694
743
  if (!result) return {}
744
+ if (result.graphExecution && result.graphDelivered === false) {
745
+ trials.delete(identity)
746
+ officialResults.delete(request.executionId)
747
+ return { graphExecution: result.graphExecution, ...(result.nativeEvidence ? { evidence: result.nativeEvidence } : {}) }
748
+ }
695
749
  officialResults.set(request.executionId, result)
696
750
  const task = options.prepared.benchmark.task
697
751
  const outcome = task.outcome
@@ -707,7 +761,11 @@ export function createPierCandidateExecutionOptions<Format extends AgentCandidat
707
761
  patch: result.taskPatch,
708
762
  })
709
763
  trials.delete(identity)
710
- return { taskOutcome }
764
+ return {
765
+ taskOutcome,
766
+ ...(result.graphExecution ? { graphExecution: result.graphExecution } : {}),
767
+ ...(result.nativeEvidence ? { evidence: result.nativeEvidence } : {}),
768
+ }
711
769
  },
712
770
  }
713
771
  const grader: AgentCandidateBenchmarkGraderPort = {
@@ -27,7 +27,7 @@ import type {
27
27
  AgentCandidateExecutorRequest,
28
28
  } from '@tangle-network/agent-runtime/candidate-execution'
29
29
 
30
- import type { TraceStore } from '@tangle-network/agent-eval'
30
+ import { canonicalJson, type TraceStore } from '@tangle-network/agent-eval'
31
31
 
32
32
  import type {
33
33
  PierCandidateTerminationAcknowledgement,
@@ -105,6 +105,10 @@ 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
110
+ /** Registered graph dispatch can start the signed profile as a leaf. */
111
+ readonly graphLeafDispatch?: true
108
112
  readonly launch?: (
109
113
  staged: StagedPierCandidateExecution,
110
114
  context: {
@@ -137,6 +141,10 @@ export interface CreatePierTaskTrialControllerOptions {
137
141
  readonly prefix?: readonly string[]
138
142
  }
139
143
  readonly dockerConnection?: PierDockerConnection
144
+ /** Allow the bundled graph coordinator for approved tasks. */
145
+ readonly graphDispatch?: true
146
+ /** Allow the signed process launch to run once as the admitted graph leaf. */
147
+ readonly graphLeafDispatch?: true
140
148
  }
141
149
 
142
150
  /** Run one approved Pier task and reopen its official result through the durable controller. */
@@ -158,16 +166,28 @@ export function createPierTaskTrialController<
158
166
  const { prefix = [], env, ...command } = options.command
159
167
  const argumentsPrefix = [...prefix]
160
168
  const environment = { ...env }
169
+ const graphDriver = fileURLToPath(new URL('../pier_agents/graph_driver.mjs', import.meta.url))
161
170
  const readResult = async ({ jobsDirectory, jobName }: { jobsDirectory: string; jobName: string }) =>
162
171
  readOfficialTrial(join(jobsDirectory, jobName), maxEvidenceBytes)
163
172
  return new FilePierCandidateTrialController<Format>({
164
173
  directory: options.directory,
165
174
  dockerConnection: options.dockerConnection,
175
+ ...(options.graphDispatch ? { graphDispatch: true } : {}),
176
+ ...(options.graphLeafDispatch ? { graphLeafDispatch: true } : {}),
166
177
  readResult,
167
178
  launch(staged, { request }) {
168
179
  const task = tasks.get(request.benchmark.task.digest)
169
180
  if (!task) throw new Error('Pier has no directory for this approved task')
170
181
  assertRealDirectory(task, 'Pier task directory')
182
+ if (staged.graphInvocationPath && request.benchmark.task.limits.maxModelCalls !== 0) {
183
+ const { limits, model } = request.executionPlan.value.material
184
+ if (
185
+ !options.graphLeafDispatch || limits.maxCostUsd !== 0 ||
186
+ model.access.network.mode !== 'gateway-only' || model.access.network.domains.length !== 1
187
+ ) {
188
+ throw new Error('A model-backed Pier graph requires an admitted profile leaf and a zero-cost gateway grant')
189
+ }
190
+ }
171
191
  const jobName = `candidate-${trialKey({
172
192
  executionId: request.executionId,
173
193
  executionPlanDigest: request.executionPlan.value.digest,
@@ -178,6 +198,14 @@ export function createPierTaskTrialController<
178
198
  ...argumentsPrefix,
179
199
  'run', '--path', task,
180
200
  ...staged.agentArgs,
201
+ ...(staged.graphInvocationPath
202
+ ? [
203
+ '--agent-kwarg', `graph_invocation_path=${staged.graphInvocationPath}`,
204
+ '--agent-kwarg', `graph_node_path=${process.execPath}`,
205
+ '--agent-kwarg', `graph_driver_path=${graphDriver}`,
206
+ ...(options.graphLeafDispatch ? ['--agent-kwarg', 'graph_leaf_dispatch=true'] : []),
207
+ ]
208
+ : []),
181
209
  ...staged.attemptArgs,
182
210
  ...Object.keys(staged.evaluatorEnv).flatMap((name) => ['--agent-env', `${name}=\${${name}}`]),
183
211
  '--env', 'docker', '--job-name', jobName, '--jobs-dir', jobsDirectory,
@@ -213,11 +241,66 @@ function readOfficialTrial(directory: string, maxEvidenceBytes: number): PierCan
213
241
  if (result) throw new Error('Expected one official result for the approved Pier task')
214
242
  const artifacts = join(trial, 'artifacts')
215
243
  assertRealDirectory(artifacts, 'Pier trial artifacts directory')
216
- result = { value, resultBytes, taskPatch: readOfficialTrialFile(join(artifacts, 'model.patch'), maxEvidenceBytes) }
244
+ const taskPatch = readOfficialTrialFile(join(artifacts, 'model.patch'), maxEvidenceBytes)
245
+ result = { value, resultBytes, taskPatch, ...readOfficialGraph(value, taskPatch) }
217
246
  }
218
247
  return result
219
248
  }
220
249
 
250
+ function readOfficialGraph(
251
+ value: unknown,
252
+ patch: Uint8Array,
253
+ ): Pick<PierCandidateTrialResult, 'graphExecution' | 'graphDelivered' | 'nativeEvidence'> {
254
+ const raw = (value as {
255
+ agent_result?: { metadata?: { graphExecution?: unknown } }
256
+ }).agent_result?.metadata?.graphExecution
257
+ if (raw === undefined) return {}
258
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
259
+ throw new Error('Pier emitted invalid evaluator graph evidence')
260
+ }
261
+ const graph = raw as {
262
+ runId: string
263
+ graphDigest: `sha256:${string}`
264
+ invocationDigest: `sha256:${string}`
265
+ record: string
266
+ delivered: boolean
267
+ nativeEvidence?: Record<string, unknown>
268
+ }
269
+ if (
270
+ typeof graph.runId !== 'string' ||
271
+ !graph.runId ||
272
+ !sha256Pattern.test(graph.graphDigest) ||
273
+ !sha256Pattern.test(graph.invocationDigest) ||
274
+ typeof graph.delivered !== 'boolean' ||
275
+ typeof graph.record !== 'string'
276
+ ) {
277
+ throw new Error('Pier emitted invalid evaluator graph evidence')
278
+ }
279
+ const record = Buffer.from(graph.record, 'base64')
280
+ if (!record.length || record.toString('base64') !== graph.record) {
281
+ throw new Error('Pier emitted invalid evaluator graph record bytes')
282
+ }
283
+ return {
284
+ graphDelivered: graph.delivered,
285
+ ...(graph.nativeEvidence ? {
286
+ nativeEvidence: Buffer.from(canonicalJson({
287
+ ...graph.nativeEvidence,
288
+ kind: 'pier-native-graph-leaf',
289
+ runId: graph.runId,
290
+ graphDigest: graph.graphDigest,
291
+ invocationDigest: graph.invocationDigest,
292
+ })),
293
+ } : {}),
294
+ graphExecution: {
295
+ runId: graph.runId,
296
+ graphDigest: graph.graphDigest,
297
+ invocationDigest: graph.invocationDigest,
298
+ taskArtifactDigest: `sha256:${createHash('sha256').update(patch).digest('hex')}`,
299
+ record,
300
+ },
301
+ }
302
+ }
303
+
221
304
  function readOfficialTrialFile(path: string, maxEvidenceBytes: number): Buffer {
222
305
  const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)
223
306
  try {
@@ -620,6 +703,8 @@ function assertRealDirectory(path: string, label: string): void {
620
703
  export class FilePierCandidateTrialController<
621
704
  Format extends AgentCandidateExecutionFormat = 'experiment',
622
705
  > implements PierCandidateTrialController<Format> {
706
+ readonly graphDispatch?: true
707
+ readonly graphLeafDispatch?: true
623
708
  private readonly directory: string
624
709
  private readonly launch?: NonNullable<FilePierCandidateTrialControllerOptions<Format>['launch']>
625
710
  private readonly readResult?: NonNullable<FilePierCandidateTrialControllerOptions<Format>['readResult']>
@@ -631,6 +716,14 @@ export class FilePierCandidateTrialController<
631
716
  this.directory = absolutePath(options.directory, 'Pier controller directory')
632
717
  this.launch = options.launch
633
718
  this.readResult = options.readResult
719
+ if (options.graphDispatch && (!options.launch || !options.readResult)) {
720
+ throw new Error('Pier graph dispatch requires both launch and durable graph capture')
721
+ }
722
+ if (options.graphLeafDispatch && !options.graphDispatch) {
723
+ throw new Error('A protected Pier profile leaf requires graph dispatch')
724
+ }
725
+ this.graphDispatch = options.graphDispatch
726
+ this.graphLeafDispatch = options.graphLeafDispatch
634
727
  const configuredDocker = options.dockerConnection
635
728
  if (configuredDocker?.id === defaultDockerConnectionId) {
636
729
  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' },