@tangle-network/agent-bench 3.0.0 → 4.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.
@@ -19,6 +19,7 @@ import { canonicalJson, InMemoryTraceStore } from '@tangle-network/agent-eval'
19
19
  import {
20
20
  sealCandidateBenchmarkSuite,
21
21
  sealCandidateBenchmarkTask,
22
+ sealCandidateExperiment,
22
23
  } from '@tangle-network/agent-eval/contract'
23
24
  import type {
24
25
  AgentCandidateArtifactRef,
@@ -26,6 +27,18 @@ import type {
26
27
  AgentCandidateWorkspaceSnapshotEvidence,
27
28
  Sha256Digest,
28
29
  } from '@tangle-network/agent-interface'
30
+ import {
31
+ addSourceText,
32
+ applyKnowledgeWriteBlocks,
33
+ improveKnowledgeBase,
34
+ initKnowledgeBase,
35
+ type KnowledgeImprovementEvaluationInput,
36
+ knowledgeImprovementCandidateRef,
37
+ } from '@tangle-network/agent-knowledge'
38
+ import {
39
+ buildKnowledgeImprovementExperimentBundles,
40
+ captureKnowledgeImprovementCandidatePair,
41
+ } from '@tangle-network/agent-runtime'
29
42
  import {
30
43
  createAgentCandidateWorkspacePort,
31
44
  disposePreparedAgentCandidateExecution,
@@ -38,8 +51,9 @@ import {
38
51
  sealAgentCandidateBundle,
39
52
  verifyAgentCandidateBundle,
40
53
  } from '@tangle-network/agent-runtime/candidate-execution'
54
+ import { executeAgentCandidateExperimentCell } from '@tangle-network/agent-runtime/intelligence'
41
55
 
42
- import { executePreparedPierCandidate } from '../src/pier-agent'
56
+ import { createPierCandidateExecutionOptions } from '../src/pier-agent'
43
57
  import { createPierResultGrader } from '../src/pier-result-grader'
44
58
  import { FilePierCandidateTrialController } from '../src/pier-trial-controller'
45
59
 
@@ -260,6 +274,57 @@ function outputArtifactStore(graderBytes: Uint8Array): {
260
274
  }
261
275
  }
262
276
 
277
+ async function measuredKnowledge(bundle: AgentCandidateBundle) {
278
+ const root = path.join(scratch, 'curated-knowledge')
279
+ await initKnowledgeBase(root)
280
+ const source = await addSourceText(root, {
281
+ uri: 'inline://release-policy',
282
+ title: 'Release policy',
283
+ text: 'The status must be ready.',
284
+ })
285
+ const update = (directory: string, fact: string) =>
286
+ applyKnowledgeWriteBlocks(directory, `---FILE: knowledge/release-policy.md---
287
+ ---
288
+ id: release-policy
289
+ title: Release policy
290
+ sources:
291
+ - ${source.id}
292
+ ---
293
+
294
+ ${fact}[^${source.id}#all]
295
+ ---END FILE---`)
296
+ await update(root, 'The status must be pending.')
297
+ const judge = async ({ candidateRoot }: KnowledgeImprovementEvaluationInput) => {
298
+ const page = readFileSync(path.join(candidateRoot, 'knowledge', 'release-policy.md'), 'utf8')
299
+ const passed = page.includes(source.id) && page.includes('The status must be ready.')
300
+ return {
301
+ score: Number(passed),
302
+ passed,
303
+ provenance: { evaluator: 'fixture-release-policy', version: '1', method: 'deterministic' as const },
304
+ }
305
+ }
306
+ const result = await improveKnowledgeBase({
307
+ root,
308
+ goal: 'Correct the release policy from its recorded source',
309
+ implementationRef: sha256(Buffer.from(judge.toString())),
310
+ maxCandidates: 1,
311
+ enabledPhases: ['knowledge-update', 'promotion'],
312
+ updateKnowledge: async ({ candidateRoot }) => {
313
+ await update(candidateRoot, 'The status must be ready.')
314
+ return { applied: true, summary: 'Use the recorded status' }
315
+ },
316
+ evaluateDevelopment: judge,
317
+ evaluate: judge,
318
+ })
319
+ return buildKnowledgeImprovementExperimentBundles(
320
+ bundle,
321
+ await captureKnowledgeImprovementCandidatePair({
322
+ root,
323
+ candidate: knowledgeImprovementCandidateRef(result),
324
+ }),
325
+ )
326
+ }
327
+
263
328
  try {
264
329
  if (!prepareOnly) {
265
330
  const pierHead = output('git', ['rev-parse', 'HEAD'], pierRepo)
@@ -319,10 +384,15 @@ try {
319
384
  mkdirSync(candidateRoot)
320
385
  mkdirSync(profileRoot)
321
386
  const instruction = readFileSync(path.join(taskDir, 'instruction.md'), 'utf8')
322
- const runner = `import pathlib, sys
387
+ const runner = `import json, os, pathlib, sys
323
388
  task = pathlib.Path.cwd()
324
389
  profile = task / 'AGENTS.md'
325
390
  assert profile.is_file() and profile.read_text().strip()
391
+ knowledge = pathlib.Path(os.environ['TANGLE_CANDIDATE_KNOWLEDGE_ROOT'])
392
+ policy = (knowledge / 'knowledge/release-policy.md').read_text()
393
+ assert 'The status must be ready.' in policy
394
+ retrieval = pathlib.Path(os.environ['TANGLE_CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG'])
395
+ assert json.loads(retrieval.read_text()) == {'topK': 2}
326
396
  assert sys.argv[-1] == ${JSON.stringify(instruction)}
327
397
  ${proofArm === 'success' ? "(task / 'src/status.txt').write_text('ready\\nowner=tangle\\n')" : ''}
328
398
  `
@@ -381,7 +451,14 @@ ${proofArm === 'success' ? "(task / 'src/status.txt').write_text('ready\\nowner=
381
451
  },
382
452
  memory: { mode: 'disabled' as const },
383
453
  }
384
- const bundle: AgentCandidateBundle = sealAgentCandidateBundle(bundleWithoutDigest)
454
+ const knowledge = await measuredKnowledge(sealAgentCandidateBundle(bundleWithoutDigest))
455
+ const retrievalConfig = embedded(Buffer.from('{"topK":2}', 'utf8'))
456
+ if (!knowledge.baseline.knowledge || !knowledge.candidate.knowledge)
457
+ throw new Error('Pier proof needs both measured Knowledge snapshots')
458
+ const bundle = sealAgentCandidateBundle({
459
+ ...bundleWithoutDigest,
460
+ knowledge: { ...knowledge.candidate.knowledge, retrievalConfig },
461
+ })
385
462
  const container: ResolvedAgentCandidateContainer = {
386
463
  source: 'evaluator-task-container',
387
464
  image: fixtureImage,
@@ -529,9 +606,9 @@ ${proofArm === 'success' ? "(task / 'src/status.txt').write_text('ready\\nowner=
529
606
  },
530
607
  }
531
608
 
532
- const verified = await verifyAgentCandidateBundle(bundle, ports)
533
- const prepared = await prepareAgentCandidateExecution(verified, task, ports)
534
609
  if (prepareOnly) {
610
+ const verified = await verifyAgentCandidateBundle(bundle, ports)
611
+ const prepared = await prepareAgentCandidateExecution(verified, task, ports)
535
612
  const disposal = await disposePreparedAgentCandidateExecution(prepared)
536
613
  if (disposal.disposed !== true) throw new Error('prepared candidate was not disposed')
537
614
  process.stdout.write(
@@ -647,32 +724,71 @@ ${proofArm === 'success' ? "(task / 'src/status.txt').write_text('ready\\nowner=
647
724
  }
648
725
  },
649
726
  })
650
- const finalized = await executePreparedPierCandidate({
651
- prepared,
652
- directory: path.join(scratch, 'sealed'),
653
- pierVersion: pinnedPierVersion,
654
- traceStore,
655
- claimStore,
656
- outputArtifacts,
657
- grader,
658
- controller,
727
+ const experiment = sealCandidateExperiment({
728
+ kind: 'agent-candidate-experiment',
729
+ digestAlgorithm: 'rfc8785-sha256',
730
+ baseline: sealAgentCandidateBundle({
731
+ ...bundleWithoutDigest,
732
+ profile: { ...bundleWithoutDigest.profile, name: 'pier-control-baseline' },
733
+ knowledge: { ...knowledge.baseline.knowledge, retrievalConfig },
734
+ }),
735
+ candidate: bundle,
736
+ candidateLineage: { source: 'human' },
737
+ benchmark,
738
+ policy: {
739
+ confidenceLevel: 0.95,
740
+ resamples: 500,
741
+ bootstrapSeed: 42,
742
+ deltaThreshold: 0,
743
+ minProductiveRuns: 3,
744
+ budgetUsd: 0,
745
+ criticalDimensions: [],
746
+ regressionTolerance: 0,
747
+ },
659
748
  })
660
- if (!finalized.succeeded) {
661
- throw new Error(`runtime rejected the protected Pier capture: ${finalized.reason}`)
662
- }
749
+ const evidence = await executeAgentCandidateExperimentCell({
750
+ experiment,
751
+ arm: 'candidate',
752
+ bundle,
753
+ task: benchmarkTask,
754
+ benchmarkCell: { suiteDigest: benchmark.suite.digest, taskIndex: 0, repetition: 0 },
755
+ seed: 42,
756
+ executionId,
757
+ executionRoots: task.executionRoots,
758
+ stagingRoots: task.stagingRoots,
759
+ ports,
760
+ execution: (prepared) =>
761
+ createPierCandidateExecutionOptions({
762
+ prepared,
763
+ directory: path.join(scratch, 'sealed'),
764
+ pierVersion: pinnedPierVersion,
765
+ traceStore,
766
+ claimStore,
767
+ outputArtifacts,
768
+ grader,
769
+ controller,
770
+ }),
771
+ })
772
+ const { materializationReceipt, receipt } = evidence
663
773
  if (!acceptedRewards || !acceptedTrialPath) {
664
774
  throw new Error('atomic Pier executor returned without accepted verifier evidence')
665
775
  }
776
+ const patch = readFileSync(
777
+ path.join(jobsDir, path.dirname(acceptedTrialPath), 'artifacts', 'model.patch'),
778
+ 'utf8',
779
+ )
780
+ if (patch.includes('.tangle/knowledge') || patch.includes('The status must be ready.'))
781
+ throw new Error('protected Knowledge leaked into the task patch')
666
782
  if (
667
- finalized.receipt.value.benchmarkResult.material.score !== expectedReward ||
668
- finalized.receipt.value.benchmarkResult.material.passed !== (expectedReward === 1)
783
+ receipt.benchmarkResult.material.score !== expectedReward ||
784
+ receipt.benchmarkResult.material.passed !== (expectedReward === 1)
669
785
  ) {
670
786
  throw new Error(
671
- `runtime receipt rejected the official Pier result: ${JSON.stringify(finalized.receipt.value.benchmarkResult.material)}`,
787
+ `runtime receipt rejected the official Pier result: ${JSON.stringify(receipt.benchmarkResult.material)}`,
672
788
  )
673
789
  }
674
790
  assertTreeOmits(scratch, 'zero-model-proof')
675
- const usage = finalized.receipt.value.modelSettlement.material.usage
791
+ const usage = receipt.modelSettlement.material.usage
676
792
  if (
677
793
  usage.modelCalls !== 0 ||
678
794
  usage.inputTokens !== 0 ||
@@ -680,7 +796,7 @@ ${proofArm === 'success' ? "(task / 'src/status.txt').write_text('ready\\nowner=
680
796
  usage.cachedInputTokens !== 0 ||
681
797
  usage.reasoningTokens !== 0 ||
682
798
  usage.costUsdNanos !== 0 ||
683
- finalized.receipt.value.trace.modelCallCount !== 0
799
+ receipt.trace.modelCallCount !== 0
684
800
  ) {
685
801
  throw new Error(`runtime minted nonzero usage for a zero-model run: ${JSON.stringify(usage)}`)
686
802
  }
@@ -703,9 +819,10 @@ ${proofArm === 'success' ? "(task / 'src/status.txt').write_text('ready\\nowner=
703
819
  manifestDigest: identity.manifestDigest,
704
820
  platform,
705
821
  },
706
- executionPlanDigest: prepared.executionPlan.value.digest,
707
- materializationReceiptDigest: prepared.materializationReceipt.digest,
708
- runReceiptDigest: finalized.receipt.digest,
822
+ experimentDigest: experiment.digest,
823
+ executionPlanDigest: materializationReceipt.executionPlan.digest,
824
+ materializationReceiptDigest: materializationReceipt.digest,
825
+ runReceiptDigest: receipt.digest,
709
826
  trial: acceptedTrialPath,
710
827
  },
711
828
  null,
package/src/index.ts CHANGED
@@ -82,6 +82,7 @@ export {
82
82
  type RunBenchmarksReport,
83
83
  } from './run-benchmarks'
84
84
  export {
85
+ createPierCandidateExecutionOptions,
85
86
  createPierCandidateRecoveryExecutor,
86
87
  executePreparedPierCandidate,
87
88
  type ExecutePreparedPierCandidateOptions,
@@ -95,6 +96,8 @@ export {
95
96
  type StagedPierCandidateExecution,
96
97
  } from './pier-agent'
97
98
  export {
99
+ createPierTaskTrialController,
100
+ type CreatePierTaskTrialControllerOptions,
98
101
  FilePierCandidateTrialController,
99
102
  type FilePierCandidateTrialControllerOptions,
100
103
  type PierCandidateProcessSpec,
package/src/pier-agent.ts CHANGED
@@ -7,12 +7,14 @@ import { dirname, isAbsolute, join, resolve } from 'node:path'
7
7
  import type {
8
8
  AgentCandidateBenchmarkGraderPort,
9
9
  AgentCandidateExecutionClaimStore,
10
+ AgentCandidateExecutionFormat,
10
11
  AgentCandidateExecutorRequest,
11
12
  AgentCandidateExecutorStopRequest,
12
13
  AgentCandidateExecutorPort,
13
14
  AgentCandidateOutputArtifactPort,
14
15
  AgentCandidateProtectedRunCapture,
15
16
  AgentCandidateRunFinalization,
17
+ ExecutePreparedAgentCandidateOptions,
16
18
  PreparedAgentCandidateExecution,
17
19
  } from '@tangle-network/agent-runtime/candidate-execution'
18
20
 
@@ -24,8 +26,10 @@ import { capturePierTaskOutcome } from './pier-task-outcome'
24
26
  const adapterImportPath = 'pier_agents.tangle_candidate:TangleCandidateAgent'
25
27
  const sha256Pattern = /^sha256:[a-f0-9]{64}$/
26
28
 
27
- interface StagePreparedPierCandidateOptions {
28
- readonly prepared: PreparedAgentCandidateExecution
29
+ interface StagePreparedPierCandidateOptions<
30
+ Format extends AgentCandidateExecutionFormat = 'experiment',
31
+ > {
32
+ readonly prepared: PreparedAgentCandidateExecution<Format>
29
33
  /** Evaluator-owned directory persisted with the Pier trial. */
30
34
  readonly directory: string
31
35
  /** Exact Pier package version pinned by the experiment contract. */
@@ -69,11 +73,13 @@ export type PierCandidateTrialIdentity = Readonly<AgentCandidateExecutorStopRequ
69
73
  * Evaluator-owned lifecycle whose stop path works without the process-local
70
74
  * handle returned by `start`.
71
75
  */
72
- export interface PierCandidateTrialController {
76
+ export interface PierCandidateTrialController<
77
+ Format extends AgentCandidateExecutionFormat = 'experiment',
78
+ > {
73
79
  start(
74
80
  staged: StagedPierCandidateExecution,
75
81
  context: {
76
- readonly request: AgentCandidateExecutorRequest
82
+ readonly request: AgentCandidateExecutorRequest<Format>
77
83
  readonly traceStore: TraceStore
78
84
  readonly signal: AbortSignal
79
85
  readonly deadlineAtMs: number
@@ -114,7 +120,9 @@ export interface PierCandidateGraderPort {
114
120
  }): Promise<RuntimeGraderResult>
115
121
  }
116
122
 
117
- export interface ExecutePreparedPierCandidateOptions extends StagePreparedPierCandidateOptions {
123
+ export interface ExecutePreparedPierCandidateOptions<
124
+ Format extends AgentCandidateExecutionFormat = 'experiment',
125
+ > extends StagePreparedPierCandidateOptions<Format> {
118
126
  readonly traceStore: TraceStore
119
127
  /** Durable one-shot store shared by every process capable of running this benchmark. */
120
128
  readonly claimStore: AgentCandidateExecutionClaimStore
@@ -124,13 +132,13 @@ export interface ExecutePreparedPierCandidateOptions extends StagePreparedPierCa
124
132
  * Starts exactly one Pier trial synchronously and persists its non-secret
125
133
  * process/container identity before returning.
126
134
  */
127
- readonly controller: PierCandidateTrialController
135
+ readonly controller: PierCandidateTrialController<Format>
128
136
  }
129
137
 
130
138
  /** Recovery-only runtime executor for an expired attempt owned by another process. */
131
- export function createPierCandidateRecoveryExecutor(
132
- controller: PierCandidateTrialController,
133
- ): AgentCandidateExecutorPort {
139
+ export function createPierCandidateRecoveryExecutor<Format extends AgentCandidateExecutionFormat>(
140
+ controller: PierCandidateTrialController<Format>,
141
+ ): AgentCandidateExecutorPort<Format> {
134
142
  return {
135
143
  execute: async () => {
136
144
  throw new Error('recovery-only Pier executor cannot start a candidate')
@@ -279,8 +287,8 @@ async function materializeExecutorFiles(
279
287
  }
280
288
 
281
289
  function protectedEnvironment(
282
- prepared: PreparedAgentCandidateExecution,
283
- request: AgentCandidateExecutorRequest,
290
+ prepared: PreparedAgentCandidateExecution<AgentCandidateExecutionFormat>,
291
+ request: AgentCandidateExecutorRequest<AgentCandidateExecutionFormat>,
284
292
  ): Readonly<Record<string, string>> {
285
293
  const protectedEntries: Array<readonly [string, string]> = []
286
294
  for (const [name, value] of Object.entries(request.launch.env)) {
@@ -299,14 +307,60 @@ function protectedEnvironment(
299
307
  return Object.freeze(Object.fromEntries(protectedEntries))
300
308
  }
301
309
 
310
+ async function stageKnowledge(
311
+ directory: string,
312
+ prepared: PreparedAgentCandidateExecution<AgentCandidateExecutionFormat>,
313
+ request: AgentCandidateExecutorRequest<AgentCandidateExecutionFormat>,
314
+ ): Promise<string[]> {
315
+ const knowledge = request.knowledge
316
+ const declared = prepared.bundle.knowledge
317
+ if (!knowledge && !declared) return []
318
+ if (!knowledge || !declared || knowledge.snapshot.digest !== declared.snapshot.digest)
319
+ throw new Error('Pier knowledge input differs from the prepared bundle')
320
+
321
+ const { digest: bundleDigest, ...material } = prepared.bundle
322
+ const bundleBytes = Buffer.from(canonicalJson(material), 'utf8')
323
+ if (sha256(bundleBytes) !== bundleDigest)
324
+ throw new Error('Pier bundle bytes do not match their sealed digest')
325
+ const bundlePath = join(directory, 'knowledge-bundle.json')
326
+ const knowledgeDir = join(directory, 'knowledge')
327
+ const files = knowledge.files.map((file) => ({ ...file, path: `files/${file.path}` }))
328
+ const expected = declared.snapshot.material.files.map((file) => ({
329
+ ...file,
330
+ path: `files/${file.path}`,
331
+ }))
332
+ if (declared.retrievalConfig && knowledge.retrievalConfig) {
333
+ files.push({ path: 'retrieval.json', mode: 0o644, bytes: knowledge.retrievalConfig })
334
+ expected.push({
335
+ path: 'retrieval.json',
336
+ mode: 0o644,
337
+ sha256: declared.retrievalConfig.sha256,
338
+ byteLength: declared.retrievalConfig.byteLength,
339
+ })
340
+ } else if (declared.retrievalConfig || knowledge.retrievalConfig) {
341
+ throw new Error('Pier retrieval configuration differs from the prepared bundle')
342
+ }
343
+ await materializeExecutorFiles(knowledgeDir, files, expected, 'knowledge executor input')
344
+ // The evaluator-side adapter reads this to verify the snapshot and optional retrieval
345
+ // configuration against the already signed bundle digest. It never enters the container.
346
+ await writeFile(bundlePath, bundleBytes, { mode: 0o600, flag: 'wx' })
347
+ await mkdir(join(knowledgeDir, 'files'), { mode: 0o700, recursive: true })
348
+ return [
349
+ '--agent-kwarg',
350
+ `knowledge_bundle_path=${bundlePath}`,
351
+ '--agent-kwarg',
352
+ `knowledge_dir=${knowledgeDir}`,
353
+ ]
354
+ }
355
+
302
356
  /**
303
357
  * Persist the runtime's exact canonical bytes and return only Pier transport
304
358
  * arguments. No benchmark-specific plan or candidate-authored telemetry exists.
305
359
  */
306
360
  /** @internal Package-private transport seam exercised by adapter tests. */
307
361
  export async function stagePreparedPierCandidateExecution(
308
- options: StagePreparedPierCandidateOptions,
309
- request: AgentCandidateExecutorRequest,
362
+ options: StagePreparedPierCandidateOptions<AgentCandidateExecutionFormat>,
363
+ request: AgentCandidateExecutorRequest<AgentCandidateExecutionFormat>,
310
364
  ): Promise<StagedPierCandidateExecution> {
311
365
  const { prepared } = options
312
366
  nonEmpty(options.pierVersion, 'pierVersion')
@@ -402,6 +456,7 @@ export async function stagePreparedPierCandidateExecution(
402
456
  if (candidateDirectory !== undefined) {
403
457
  agentArgs.push('--agent-kwarg', `candidate_dir=${candidateDirectory}`)
404
458
  }
459
+ agentArgs.push(...(await stageKnowledge(directory, prepared, request)))
405
460
 
406
461
  return {
407
462
  executionId: request.executionId,
@@ -428,7 +483,7 @@ function exceptionType(value: unknown): string | undefined {
428
483
  /** Read only identity and termination from Pier; usage always comes from agent-eval. */
429
484
  /** @internal Package-private result parser exercised by adapter tests. */
430
485
  export function protectedCaptureFromPierResult(
431
- request: AgentCandidateExecutorRequest,
486
+ request: AgentCandidateExecutorRequest<AgentCandidateExecutionFormat>,
432
487
  value: unknown,
433
488
  ): AgentCandidateProtectedRunCapture {
434
489
  const result = record(value, 'Pier trial result') as PierResultLike
@@ -436,7 +491,7 @@ export function protectedCaptureFromPierResult(
436
491
  const metadata = record(agentResult.metadata, 'Pier agent_result.metadata')
437
492
  const expected = {
438
493
  executionId: request.executionId,
439
- bundleDigest: request.executionPlan.value.material.runCell.bundleDigest,
494
+ bundleDigest: request.materializationReceipt.value.bundleDigest,
440
495
  executionPlanDigest: request.executionPlan.value.digest,
441
496
  materializationReceiptDigest: request.materializationReceipt.digest,
442
497
  }
@@ -547,10 +602,10 @@ export async function awaitAbortableTrial<T>(
547
602
  })
548
603
  }
549
604
 
550
- /** Execute and finalize through the runtime's only gradable candidate path. */
551
- export async function executePreparedPierCandidate(
552
- options: ExecutePreparedPierCandidateOptions,
553
- ): Promise<AgentCandidateRunFinalization> {
605
+ /** Bind Pier and its separate verifier to Runtime's prepared experiment cell. */
606
+ export function createPierCandidateExecutionOptions<Format extends AgentCandidateExecutionFormat>(
607
+ options: ExecutePreparedPierCandidateOptions<Format>,
608
+ ): ExecutePreparedAgentCandidateOptions<Format> {
554
609
  const trials = new Map<
555
610
  string,
556
611
  { readonly handle: PierCandidateTrialHandle; result?: PierCandidateTrialResult }
@@ -558,9 +613,15 @@ export async function executePreparedPierCandidate(
558
613
  const officialResults = new Map<string, PierCandidateTrialResult>()
559
614
  const trialIdentity = (executionId: string, executionPlanDigest: string): string =>
560
615
  JSON.stringify([executionId, executionPlanDigest])
561
- const executor: AgentCandidateExecutorPort = {
616
+ const executor: AgentCandidateExecutorPort<Format> = {
562
617
  execute: async (request, context) => {
563
618
  context.signal.throwIfAborted()
619
+ if (
620
+ request.executionId !== options.prepared.executionId ||
621
+ request.materializationReceipt.digest !== options.prepared.materializationReceipt.digest
622
+ ) {
623
+ throw new Error('Pier executor received a different prepared candidate')
624
+ }
564
625
  const staged = await stagePreparedPierCandidateExecution(options, request)
565
626
  context.signal.throwIfAborted()
566
627
  const identity = trialIdentity(request.executionId, request.executionPlan.value.digest)
@@ -638,25 +699,34 @@ export async function executePreparedPierCandidate(
638
699
  run: async (input) => {
639
700
  const official = officialResults.get(input.executionId)
640
701
  if (!official) throw new Error('Pier official result is missing for executable grading')
641
- return await options.grader.run({
642
- ...input,
643
- officialResult: {
644
- value: parseExactJson(official.resultBytes, 'Pier result.json'),
645
- bytes: Uint8Array.from(official.resultBytes),
646
- },
647
- })
702
+ try {
703
+ return await options.grader.run({
704
+ ...input,
705
+ officialResult: {
706
+ value: parseExactJson(official.resultBytes, 'Pier result.json'),
707
+ bytes: Uint8Array.from(official.resultBytes),
708
+ },
709
+ })
710
+ } finally {
711
+ officialResults.delete(input.executionId)
712
+ }
648
713
  },
649
714
  }
650
- try {
651
- return await executePreparedAgentCandidate(options.prepared, {
652
- executor,
653
- grader,
654
- outputArtifacts: options.outputArtifacts,
655
- traceStore: options.traceStore,
656
- claimStore: options.claimStore,
657
- })
658
- } finally {
659
- officialResults.clear()
660
- trials.clear()
715
+ return {
716
+ executor,
717
+ grader,
718
+ outputArtifacts: options.outputArtifacts,
719
+ traceStore: options.traceStore,
720
+ claimStore: options.claimStore,
661
721
  }
662
722
  }
723
+
724
+ /** Execute and finalize through the runtime's only gradable candidate path. */
725
+ export async function executePreparedPierCandidate<Format extends AgentCandidateExecutionFormat>(
726
+ options: ExecutePreparedPierCandidateOptions<Format>,
727
+ ): Promise<AgentCandidateRunFinalization> {
728
+ return await executePreparedAgentCandidate(
729
+ options.prepared,
730
+ createPierCandidateExecutionOptions(options),
731
+ )
732
+ }
@@ -11,7 +11,7 @@ import type { AgentCandidateExecutorRequest } from '@tangle-network/agent-runtim
11
11
  import { InMemoryTraceStore } from '@tangle-network/agent-eval'
12
12
 
13
13
  import { createStagedPierCandidateExecutionFixture } from './pier-agent.test-fixtures.mts'
14
- import { FilePierCandidateTrialController } from './pier-trial-controller'
14
+ import { createPierTaskTrialController, FilePierCandidateTrialController } from './pier-trial-controller'
15
15
 
16
16
  // Process identity and restart recovery require Linux /proc start-time receipts.
17
17
  const execFileAsync = promisify(execFile)
@@ -31,6 +31,53 @@ function testRequest(executionId: string, executionPlanDigest: `sha256:${string}
31
31
  }
32
32
  }
33
33
 
34
+ test('launches a configured task and reopens its exact Pier files after restart', { skip: process.platform !== 'linux' }, async () => {
35
+ const root = await mkdtemp(path.join(tmpdir(), 'pier-task-trial-'))
36
+ const task = path.join(root, 'approved-task')
37
+ const jobsDirectory = path.join(root, 'jobs')
38
+ const command = path.join(root, 'pier.mjs')
39
+ const fakeDocker = path.join(root, 'docker')
40
+ const taskDigest = `sha256:${'a'.repeat(64)}` as const
41
+ const { staged, context } = testRequest('approved-task', `sha256:${'b'.repeat(64)}`)
42
+ Object.assign(context.request, { benchmark: { task: { digest: taskDigest } } })
43
+ let handle: ReturnType<FilePierCandidateTrialController['start']> | undefined
44
+ try {
45
+ await mkdir(task)
46
+ await writeFile(fakeDocker, '#!/bin/sh\nexit 0\n', { mode: 0o700 })
47
+ await writeFile(command, `import assert from 'node:assert/strict';
48
+ import { mkdirSync, writeFileSync } from 'node:fs';
49
+ import { join } from 'node:path';
50
+ const args = process.argv.slice(2);
51
+ const option = (name) => args[args.indexOf(name) + 1];
52
+ assert.equal(args[0], 'run');
53
+ assert.equal(option('--path'), ${JSON.stringify(task)});
54
+ assert.equal(option('--env'), 'docker');
55
+ assert.equal(option('--n-attempts'), '1');
56
+ assert.equal(option('--max-retries'), '0');
57
+ const dir = join(option('--jobs-dir'), option('--job-name'), 'approved-task__trial');
58
+ mkdirSync(join(dir, 'artifacts'), { recursive: true });
59
+ writeFileSync(join(dir, 'result.json'), '{"trial_name":"approved-task__trial"}\\n');
60
+ writeFileSync(join(dir, 'artifacts', 'model.patch'), 'retained patch\\n');
61
+ `)
62
+ const options = {
63
+ directory: path.join(root, 'controller'),
64
+ jobsDirectory,
65
+ maxEvidenceBytes: 1024,
66
+ tasks: [{ taskDigest, directory: task }],
67
+ command: { command: process.execPath, cwd: root, env: {}, prefix: [command], dockerCommand: fakeDocker },
68
+ }
69
+ const controller = createPierTaskTrialController(options)
70
+ handle = controller.start(staged, context)
71
+ const result = await handle.result
72
+ assert.equal(Buffer.from(result.resultBytes).toString(), '{"trial_name":"approved-task__trial"}\n')
73
+ assert.equal(Buffer.from(result.taskPatch).toString(), 'retained patch\n')
74
+ assert.deepEqual(await createPierTaskTrialController(options).captureResult(handle.identity), result)
75
+ } finally {
76
+ if (handle) await handle.terminateAndWait()
77
+ await rm(root, { recursive: true, force: true })
78
+ }
79
+ })
80
+
34
81
  test('an existing Pier job is rejected without deleting or starting it', async () => {
35
82
  const root = await mkdtemp(path.join(tmpdir(), 'pier-controller-scope-'))
36
83
  const controlRoot = path.join(root, 'control')