@tangle-network/agent-bench 3.0.0 → 4.0.2

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,10 +51,11 @@ 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
- import { FilePierCandidateTrialController } from '../src/pier-trial-controller'
58
+ import { createPierTaskTrialController } from '../src/pier-trial-controller'
45
59
 
46
60
  const pinnedPierCommit = 'e69a20e4e0ac073ec71fde0274bab3d9f40bac87'
47
61
  const pinnedPierVersion = '0.3.0'
@@ -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(
@@ -547,132 +624,105 @@ ${proofArm === 'success' ? "(task / 'src/status.txt').write_text('ready\\nowner=
547
624
  const claimStore = new FileAgentCandidateExecutionClaimStore({
548
625
  directory: path.join(scratch, 'claims'),
549
626
  })
550
- let acceptedRewards: { reward: number; patch_applied: number } | undefined
551
- let acceptedTrialPath: string | undefined
552
- const jobName = `tangle-runtime-candidate-no-model-${proofArm}`
553
- const controller = new FilePierCandidateTrialController({
627
+ const controller = createPierTaskTrialController({
554
628
  directory: path.join(scratch, 'trial-control'),
555
- readResult: async ({ jobsDirectory, jobName }) => {
556
- const trialResult = findTrialResult(path.join(jobsDirectory, jobName))
557
- if (!trialResult) return undefined
558
- return {
559
- value: trialResult.value,
560
- resultBytes: readFileSync(trialResult.path),
561
- taskPatch: readFileSync(
562
- path.join(path.dirname(trialResult.path), 'artifacts', 'model.patch'),
563
- ),
564
- }
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 },
565
637
  },
566
- launch: (staged, { request }) => {
567
- const evaluatorArgs = Object.keys(staged.evaluatorEnv).flatMap((name) => [
568
- '--agent-env',
569
- `${name}=\${${name}}`,
570
- ])
571
- return {
572
- command: 'uv',
573
- args: [
574
- 'run',
575
- 'pier',
576
- 'run',
577
- '--path',
578
- taskDir,
579
- ...staged.agentArgs,
580
- ...staged.attemptArgs,
581
- ...evaluatorArgs,
582
- '--env',
583
- 'docker',
584
- '--job-name',
585
- jobName,
586
- '--jobs-dir',
587
- jobsDir,
588
- '--n-concurrent',
589
- '1',
590
- '--agent-timeout-multiplier',
591
- '2',
592
- '--quiet',
593
- ],
594
- cwd: pierRepo,
595
- env: { ...process.env, PYTHONPATH: benchDir, ...staged.evaluatorEnv },
596
- jobsDirectory: jobsDir,
597
- jobName,
598
- readResult: async () => {
599
- const trialResult = findTrialResult(jobsDir)
600
- if (!trialResult) throw new Error(`Pier emitted no trial result under ${jobsDir}`)
601
- const result = trialResult.value
602
- if (result.exception_info !== null) {
603
- throw new Error(
604
- `Pier trial captured an exception: ${JSON.stringify(result.exception_info)}`,
605
- )
606
- }
607
- const rewards = result.verifier_result?.rewards
608
- if (
609
- rewards?.reward !== expectedReward ||
610
- rewards?.patch_applied !== expectedPatchApplied
611
- ) {
612
- throw new Error(
613
- `Pier ${proofArm} control returned unexpected rewards: ${JSON.stringify(rewards)}`,
614
- )
615
- }
616
- const agentResult = result.agent_result
617
- for (const name of ['n_input_tokens', 'n_cache_tokens', 'n_output_tokens', 'cost_usd']) {
618
- if (agentResult?.[name] !== null) {
619
- throw new Error(
620
- `Pier must not author protected usage ${name}: ${agentResult?.[name]}`,
621
- )
622
- }
623
- }
624
- const observedElapsedMs = agentResult?.metadata?.observedElapsedMs
625
- if (!Number.isInteger(observedElapsedMs) || observedElapsedMs < 0) {
626
- throw new Error(`Pier omitted protected elapsed time: ${observedElapsedMs}`)
627
- }
628
- const endedAt = Date.now()
629
- await traceStore.appendRun({
630
- runId: request.trace.runId,
631
- scenarioId: benchmarkTask.scenario.id,
632
- startedAt: endedAt - observedElapsedMs,
633
- endedAt,
634
- status: 'completed',
635
- tags: { ...request.trace.tags },
636
- })
637
- acceptedRewards = rewards
638
- acceptedTrialPath = path.relative(jobsDir, trialResult.path)
639
- return {
640
- value: result,
641
- resultBytes: readFileSync(trialResult.path),
642
- taskPatch: readFileSync(
643
- path.join(path.dirname(trialResult.path), 'artifacts', 'model.patch'),
644
- ),
645
- }
646
- },
647
- }
638
+ })
639
+ const experiment = sealCandidateExperiment({
640
+ kind: 'agent-candidate-experiment',
641
+ digestAlgorithm: 'rfc8785-sha256',
642
+ baseline: sealAgentCandidateBundle({
643
+ ...bundleWithoutDigest,
644
+ profile: { ...bundleWithoutDigest.profile, name: 'pier-control-baseline' },
645
+ knowledge: { ...knowledge.baseline.knowledge, retrievalConfig },
646
+ }),
647
+ candidate: bundle,
648
+ candidateLineage: { source: 'human' },
649
+ benchmark,
650
+ policy: {
651
+ confidenceLevel: 0.95,
652
+ resamples: 500,
653
+ bootstrapSeed: 42,
654
+ deltaThreshold: 0,
655
+ minProductiveRuns: 3,
656
+ budgetUsd: 0,
657
+ criticalDimensions: [],
658
+ regressionTolerance: 0,
648
659
  },
649
660
  })
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,
661
+ const evidence = await executeAgentCandidateExperimentCell({
662
+ experiment,
663
+ arm: 'candidate',
664
+ bundle,
665
+ task: benchmarkTask,
666
+ benchmarkCell: { suiteDigest: benchmark.suite.digest, taskIndex: 0, repetition: 0 },
667
+ seed: 42,
668
+ executionId,
669
+ executionRoots: task.executionRoots,
670
+ stagingRoots: task.stagingRoots,
671
+ ports,
672
+ execution: (prepared) =>
673
+ createPierCandidateExecutionOptions({
674
+ prepared,
675
+ directory: path.join(scratch, 'sealed'),
676
+ pierVersion: pinnedPierVersion,
677
+ traceStore,
678
+ claimStore,
679
+ outputArtifacts,
680
+ grader,
681
+ controller,
682
+ }),
659
683
  })
660
- if (!finalized.succeeded) {
661
- throw new Error(`runtime rejected the protected Pier capture: ${finalized.reason}`)
684
+ const { materializationReceipt, receipt } = 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)}`)
662
690
  }
663
- if (!acceptedRewards || !acceptedTrialPath) {
664
- throw new Error('atomic Pier executor returned without accepted verifier evidence')
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
+ )
665
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}`)
708
+ }
709
+ const acceptedTrialPath = path.relative(jobsDir, trialResult.path)
710
+ const patch = readFileSync(
711
+ path.join(jobsDir, path.dirname(acceptedTrialPath), 'artifacts', 'model.patch'),
712
+ 'utf8',
713
+ )
714
+ if (patch.includes('.tangle/knowledge') || patch.includes('The status must be ready.'))
715
+ throw new Error('protected Knowledge leaked into the task patch')
666
716
  if (
667
- finalized.receipt.value.benchmarkResult.material.score !== expectedReward ||
668
- finalized.receipt.value.benchmarkResult.material.passed !== (expectedReward === 1)
717
+ receipt.benchmarkResult.material.score !== expectedReward ||
718
+ receipt.benchmarkResult.material.passed !== (expectedReward === 1)
669
719
  ) {
670
720
  throw new Error(
671
- `runtime receipt rejected the official Pier result: ${JSON.stringify(finalized.receipt.value.benchmarkResult.material)}`,
721
+ `runtime receipt rejected the official Pier result: ${JSON.stringify(receipt.benchmarkResult.material)}`,
672
722
  )
673
723
  }
674
724
  assertTreeOmits(scratch, 'zero-model-proof')
675
- const usage = finalized.receipt.value.modelSettlement.material.usage
725
+ const usage = receipt.modelSettlement.material.usage
676
726
  if (
677
727
  usage.modelCalls !== 0 ||
678
728
  usage.inputTokens !== 0 ||
@@ -680,7 +730,7 @@ ${proofArm === 'success' ? "(task / 'src/status.txt').write_text('ready\\nowner=
680
730
  usage.cachedInputTokens !== 0 ||
681
731
  usage.reasoningTokens !== 0 ||
682
732
  usage.costUsdNanos !== 0 ||
683
- finalized.receipt.value.trace.modelCallCount !== 0
733
+ receipt.trace.modelCallCount !== 0
684
734
  ) {
685
735
  throw new Error(`runtime minted nonzero usage for a zero-model run: ${JSON.stringify(usage)}`)
686
736
  }
@@ -703,9 +753,10 @@ ${proofArm === 'success' ? "(task / 'src/status.txt').write_text('ready\\nowner=
703
753
  manifestDigest: identity.manifestDigest,
704
754
  platform,
705
755
  },
706
- executionPlanDigest: prepared.executionPlan.value.digest,
707
- materializationReceiptDigest: prepared.materializationReceipt.digest,
708
- runReceiptDigest: finalized.receipt.digest,
756
+ experimentDigest: experiment.digest,
757
+ executionPlanDigest: materializationReceipt.executionPlan.digest,
758
+ materializationReceiptDigest: materializationReceipt.digest,
759
+ runReceiptDigest: receipt.digest,
709
760
  trial: acceptedTrialPath,
710
761
  },
711
762
  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,