跳到主要内容
chapter-21 第六部分 · 验证与交付 · 实现笔记

21 · 固定任务集与确定性判分

里程碑 → 受控任务集产出状态、usage、审批与 metadata 完整的 run 目录

第 20 章让同一次 run 在终端和管道里都能看清。但 GIF 和干净的日志只能证明“它运行过”,证明不了它做对了。

本章绕开交互壳,直接调用 runAgent。流程是:

  1. 把固定任务复制到一个独立的临时目录。
  2. 在这个目录里执行任务。
  3. 执行结束后,用确定性 oracle 判分。oracle 指判断结果对错的程序化规则,同样的输入永远给出同样的判定。
  4. 把配置、结构化 transcript、usage 和环境元数据写进 run 目录。这个目录不能被覆盖。

本章只造 harness(运行和记录评测的那套脚手架),不比较特性效果。它能用一份指定配置跑完整个任务集,结果出现 fail、timeout 或 budget_exceeded 都是允许的。到第 22 章,才把同一个任务按三份冻结配置重复运行,再汇总统计。

能力边界与控制流

task manifest + eval config
  → 校验 manifest / version / fixture 范围,计算 hash
  → mkdtemp() 创建本 attempt 独立目录
  → cp(fixture, workspace),不修改、不 reset 共享目录
  → buildSystemPrompt()(只有基础行为,attempt 之间逐字节相同)
  → readContextSnapshot(cwd = workspace)(首轮作为完整 context 消息)
  → runAgent({
      callModel: 精确 model + maxTokens,
      beforeToolCall: 显式 approval policy + 全量记录,
      afterToolCall: 与 CLI 相同的结果治理,
      timeout signal, maxTurns, compaction/todo flags
    })
  → 三类 oracle:exit code / file state / structured transcript
  → attempt.json + transcript.json + oracle.json
  → 删除本 attempt 临时副本

临时副本只保证一件事:每次 attempt(一次具体的运行尝试)的起始状态可复现。它不是 sandbox,也不提供安全保护。Bash 仍然以当前用户的权限运行,能访问 workspace 外的路径、网络和继承来的环境变量。

所以本 harness 只运行仓库自带、人工审查过的 fixture(预先准备好的测试项目)。另外还做了两件事:

  • 工具进程只收到白名单里的环境变量。
  • HOME 和 npm cache 指到 attempt 目录里面。

这些措施都不能当成操作系统级的隔离。

权限也不绕过第 08 章:

  • 配置必须明确写出 allow_all_recorded 或 deny_all。
  • 选 allow_all_recorded 时,调用仍然经过 prepare → beforeToolCall → execute,每次批准都写进 transcript。
  • 工具结果和 CLI 一样,继续经过 afterToolCall。eval 不能为了方便跳过截断。
  • 配置里缺 policy 时,整轮在创建 run 目录之前就拒绝启动,不会悄悄默认全部放行。

冻结采样参数,但不要承诺逐字复现

到目前为止,model.ts 只设了 max_tokens,temperature 一直用 provider 的默认值。交互式 CLI 这样做没问题,但拿来当量尺就不行:

  • 默认值不由我们控制。它一变,以前的结论也跟着变。
  • 记录里根本没有这个字段,事后查不出来。

所以 EvalConfig 显式写出 temperature,构造 CallModel 时传下去。它和精确的 model ID 一起,写进每个 attempt 的 metadata。

同样的道理,CLI 和 eval 要用同一个值。否则实验测的是一个 temperature 更低的 agent,结论不适用于真正交给用户的那个 agent。

这条规则有一个边界情况,模型越新越容易碰到:temperature 不一定能设。

  • 较新的模型:只要 temperature、top_p、top_k 不是默认值,就一律返回 400,和是否开启思考无关。
  • 较老的模型:开启思考之后,temperature 和 top_k 不能用。

也就是说,在一部分模型上,“显式冻结 temperature”会直接让请求失败。不变的是这条规则的目的:不让任何采样配置成为实验里没被记录、却会影响结果的变量。具体做法看模型:

  • 能设,就显式设并记录。
  • 不能设,就把“该模型不接受采样参数”作为一条 metadata 记下来。不要留一个空字段,让后来的人以为是忘了填。

但是,即使冻结了采样参数,也不能承诺逐字复现。Messages API 没有 seed。低 temperature 只是让输出更集中,不会让输出变得确定。这正是第 22 章必须重复运行、报告分布,而不是比较两次单跑的根本原因。

分三类看:

  • 能冻结的是输入:task / fixture / config / pricing hash、git SHA、精确 model、temperature、SDK / Node / OS。
  • 能保留的是事实:结构化 transcript 和 usage。
  • 模型采样本身:只能测量,不能消除。

attempt 之间的缓存前缀

每个 attempt 都在新的 mkdtemp 目录里运行,所以每次的 cwd 都不同。

第 11 章做过一个决定:把项目和环境信息整个移出 system。这个决定在这里也用得上。会变的部分都在缓存断点之后,所以 tools 和 system 组成的前缀在 attempt 之间仍然可以命中。

要读到这段缓存,需要同时满足三个条件:

  • 共享前缀达到最低缓存长度。
  • 断点可以复用。
  • 还在 TTL(缓存有效期)内。

满足时,后面的任务可以读到这一段;实际有没有命中,仍然要看 usage。每个 workspace 的第一条 context message 仍然是新的尾部。不能把“共享 system 前缀”夸大成“整个输入都共享”。

值得注意的是,这个决定当时不是为 eval 做的。第 11 章只知道,在 CLI 的一次会话里 cwd 不会变。按那个场景,把 cwd 留在缓存块里完全说得通。真正的理由是:system.ts 不知道自己会被谁调用,而本章就是那个“别人”。

如果当时按 CLI 的情况把 cwd 留在了缓存块,这里不会报错。它只会让每个 attempt 都重写一次缓存,然后在成本表上留下一个谁也解释不清的数字。

代价是:缓存冷热变成了成本上一个看不见的变量。满足缓存条件时:

  1. 第一个 attempt 可能要付写缓存的费用。
  2. 后面的 attempt 可能读缓存。
  3. 缓存过期后,又要重新写入。

于是有两条要求:

  • 执行顺序不能固定。第 22 章会按 block 打乱顺序。
  • 报告不能把 cache_read 和 cache_creation 合成一个 input 总数。

否则,同样的能力换个顺序跑,成本就不一样,却没人看得出原因。

还有一条路径要顺便确认。临时副本通常不是 Git 仓库。readContextSnapshot 去读 Git 分支和未提交改动时,会得到一段固定的“不可用”文本。这意味着两件事:

  • 这是它第一次在非仓库目录下真正运行。
  • eval 里的 agent 比真实使用时少看到一块环境信息。

这两点都要在验收时确认,不要等它在某个 attempt 里抛出 infra_error 才发现。

直接驱动 runAgent 换到了什么、放弃了什么

绕过交互壳,得到了三样东西:

  • 可以替换的 callModel。
  • 可以注入的时钟。
  • 一条不需要伪造 TTY 的执行路径。

放弃的是参数解析、renderer 降级和打包后的入口。这些不归 eval 管,本章不覆盖。第 23 章的容器 smoke(在容器里做的冒烟测试,只确认主路径能跑通)会直接安装 tarball,再运行同一个 runAgent,由它来覆盖。两章合起来,才覆盖了从命令行到 loop 的完整路径。

状态分为七种:

状态含义
passrun 到达可判分状态,全部 oracle 通过
failagent 停止原因或确定性 oracle 不满足
timeoutper-task timer 触发 Abort
budget_exceeded已结算 usage 越过 token 或美元上限,或下一次调用前发现已到上限
infra_errorprovider、文件系统或 harness 自身故障,不能归因给 agent 能力
invalid_tasktask manifest、fixture 或 oracle 非法,不能进入考卷;非法配置在整轮 preflight 直接拒绝,不生成 attempt
aborted操作者主动取消整轮,不计入能力通过率

美元上限是 soft cap(软上限)。原因是:一次请求开始后,要等它 settle(结算完成)才知道用了多少 usage,所以总额最多可能超出一个正在结算的模型调用。

maxTurns、单请求 maxTokens 和 timeout 一起限制最坏情况。报告必须保留超出之后的实际 usage,不能把最后一次调用从账本里抹掉。

no_progress 保留在 runReason 里,但 attempt 的状态仍然是 fail。它既不冒充 provider 的 infra_error,也不冒充美元的 budget_exceeded。现有的状态映射只把 done + oracle 全通过 算作 pass,所以 harness 不需要再造一个同名的顶层状态。

为此加一个自测:让 fake model 连续重复失败,断言 runReason、消息配对和 meter / usageDelta 都一致。如果工具调用一直成功、任务却不收敛,仍然归为 max_turns。

本章的非交互评测只组装本地工具、Todo 和 Task,不暴露 Plan tools。这张固定的工具表在 A/B/C 三份配置里,只随已有的 Todo 开关变化。规划交互由第 14 章的 host 测试覆盖。工具的自动批准策略,不能顺带把方案也批准了。

完整代码增量

新建 eval/types.ts。manifest 带显式版本号。oracle 只有三种,不接受任意 JavaScript 回调:

import type Anthropic from '@anthropic-ai/sdk'
import type { AgentEvent, RunOutcome } from '../src/agent.js'
import type { ApprovalRecord } from '../src/terminal-approval.js'
import type { Usage } from '../src/usage.js'

export type TaskStratum =
  | 'long-context'
  | 'multi-step'
  | 'general'

export type OracleSpec =
  | {
      type: 'exit_code'
      command: string
      args: string[]
      expected: number
    }
  | {
      type: 'file_state'
      path: string
      equals?: string
      contains?: string
      sha256?: string
    }
  | {
      type: 'transcript'
      assertion:
        | 'tool_called'
        | 'assistant_contains'
        | 'tool_result_contains'
      name?: string
      contains?: string
    }

export type TaskManifest = {
  schemaVersion: 1
  id: string
  taskVersion: string
  stratum: TaskStratum
  fixture: string
  prompt: string
  oracles: OracleSpec[]
}

export type EvalFeatures = {
  compaction: boolean
  todo: boolean
}

export type EvalConfig = {
  schemaVersion: 1
  name: string
  model: string
  maxTurns: number
  maxTokensPerRequest: number
  temperature: number
  timeoutMs: number
  maxSettledTokens: number
  maxUsd: number
  approvalPolicy: 'allow_all_recorded' | 'deny_all'
  features: EvalFeatures
  pricingSnapshot: string
}

export type RecordedEvent = ReturnType<typeof recordAgentEvent>

export type StructuredTranscript = {
  prompt: string
  messages: Anthropic.MessageParam[]
  events: RecordedEvent[]
  approvals: ApprovalRecord[]
}

export type OracleResult = {
  spec: OracleSpec
  passed: boolean
  actual: string
}

export type AttemptStatus =
  | 'pass'
  | 'fail'
  | 'timeout'
  | 'budget_exceeded'
  | 'infra_error'
  | 'invalid_task'
  | 'aborted'

export type AttemptRecord = {
  schemaVersion: 1
  attemptId: string
  taskId: string
  taskVersion: string
  taskManifestSha256: string
  fixtureSha256: string
  configName: string
  configSha256: string
  status: AttemptStatus
  runReason?: RunOutcome['reason']
  usageDelta: Usage
  estimatedCostUsd: number
  startedAt: string
  finishedAt: string
  metadata: {
    gitSha: string
    model: string
    temperature: number
    anthropicSdkVersion: string
    node: string
    os: string
    arch: string
    pricingSnapshot: string
    pricingSnapshotSha256: string
  }
  oracleResults: OracleResult[]
  error?: string
}

export function recordAgentEvent(event: AgentEvent) {
  switch (event.type) {
    case 'text_delta':
      return { type: event.type, text: event.text }
    case 'tool_start':
      return {
        type: event.type,
        id: event.id,
        name: event.name,
        input: event.input,
      }
    case 'tool_end':
      return {
        type: event.type,
        id: event.id,
        name: event.name,
        content: event.result.content,
        isError: event.result.isError === true,
      }
    case 'model_retry':
      return {
        type: event.type,
        attempt: event.attempt,
        delayMs: event.delayMs,
      }
    case 'context_usage':
      return {
        type: event.type,
        nextEstimatedInputTokens: event.nextEstimatedInputTokens,
        lastObservedInputTokens: event.lastObservedInputTokens,
      }
    case 'compaction_start':
      return { type: event.type, beforeTokens: event.beforeTokens }
    case 'compaction_end':
      return {
        type: event.type,
        beforeTokens: event.beforeTokens,
        afterTokens: event.afterTokens,
        cutIndex: event.cutIndex,
      }
    case 'run_end':
      return {
        type: event.type,
        reason: event.reason,
        usageDelta: event.usageDelta,
        context: event.context,
        error: event.error,
      }
  }
}

新建 eval/manifest.ts。hash 覆盖 manifest 原文和 fixture 文件树。fixture 只允许放在 practice/ 或 eval/fixtures/ 下,并且拒绝 symlink,避免测试偷偷读到受控目录以外的文件:

import { createHash } from 'node:crypto'
import {
  lstat,
  readFile,
  readdir,
  realpath,
} from 'node:fs/promises'
import path from 'node:path'
import type {
  EvalConfig,
  OracleSpec,
  TaskManifest,
} from './types.js'

export function sha256(value: string | Buffer): string {
  return createHash('sha256').update(value).digest('hex')
}

export class InvalidTaskError extends Error {}

function invalidTask(message: string): never {
  throw new InvalidTaskError(message)
}

function isRecord(value: unknown): value is Record<string, unknown> {
  return value !== null && typeof value === 'object' && !Array.isArray(value)
}

function isOracle(value: unknown): value is OracleSpec {
  if (!isRecord(value) || typeof value.type !== 'string') return false
  if (value.type === 'exit_code') {
    return typeof value.command === 'string' &&
      Array.isArray(value.args) &&
      value.args.every((arg) => typeof arg === 'string') &&
      Number.isInteger(value.expected)
  }
  if (value.type === 'file_state') {
    const assertions = [value.equals, value.contains, value.sha256]
      .filter((item) => typeof item === 'string')
    return typeof value.path === 'string' && assertions.length === 1
  }
  if (value.type === 'transcript') {
    if (value.assertion === 'tool_called') {
      return typeof value.name === 'string' && value.name !== ''
    }
    if (value.assertion === 'assistant_contains') {
      return typeof value.contains === 'string' && value.contains !== ''
    }
    if (value.assertion === 'tool_result_contains') {
      return typeof value.contains === 'string' && value.contains !== '' &&
        (value.name === undefined || typeof value.name === 'string')
    }
    return false
  }
  return false
}

export function parseTaskManifest(value: unknown): TaskManifest {
  if (
    !isRecord(value) ||
    value.schemaVersion !== 1 ||
    typeof value.id !== 'string' ||
    !/^[a-z0-9][a-z0-9_-]*$/.test(value.id) ||
    typeof value.taskVersion !== 'string' ||
    !['long-context', 'multi-step', 'general'].includes(String(value.stratum)) ||
    typeof value.fixture !== 'string' ||
    typeof value.prompt !== 'string' ||
    value.prompt.trim() === '' ||
    !Array.isArray(value.oracles) ||
    value.oracles.length === 0 ||
    !value.oracles.every(isOracle)
  ) {
    invalidTask('Invalid task manifest')
  }
  return value as TaskManifest
}

export function parseEvalConfig(value: unknown): EvalConfig {
  if (
    !isRecord(value) ||
    value.schemaVersion !== 1 ||
    typeof value.name !== 'string' ||
    !/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(value.name) ||
    typeof value.model !== 'string' ||
    !Number.isSafeInteger(value.maxTurns) || Number(value.maxTurns) <= 0 ||
    !Number.isSafeInteger(value.maxTokensPerRequest) || Number(value.maxTokensPerRequest) <= 0 ||
    !Number.isSafeInteger(value.timeoutMs) || Number(value.timeoutMs) <= 0 ||
    !Number.isSafeInteger(value.maxSettledTokens) || Number(value.maxSettledTokens) <= 0 ||
    typeof value.maxUsd !== 'number' || value.maxUsd <= 0 ||
    !['allow_all_recorded', 'deny_all'].includes(String(value.approvalPolicy)) ||
    !isRecord(value.features) ||
    typeof value.features.compaction !== 'boolean' ||
    typeof value.features.todo !== 'boolean' ||
    typeof value.pricingSnapshot !== 'string' ||
    !/^eval\/pricing\/[A-Za-z0-9._-]+\.json$/.test(value.pricingSnapshot)
  ) {
    invalidTask('Invalid eval config')
  }
  return value as EvalConfig
}

async function hashTree(directory: string): Promise<string> {
  const hash = createHash('sha256')

  async function visit(current: string): Promise<void> {
    const names = (await readdir(current)).sort()
    for (const name of names) {
      const absolute = path.join(current, name)
      const relative = path.relative(directory, absolute).split(path.sep).join('/')
      const stat = await lstat(absolute)
      if (stat.isSymbolicLink()) {
        invalidTask(`Fixture symlink is not allowed: ${relative}`)
      }
      if (stat.isDirectory()) {
        hash.update(`D\0${relative}\0`)
        await visit(absolute)
      } else if (stat.isFile()) {
        hash.update(`F\0${relative}\0`)
        hash.update(await readFile(absolute))
        hash.update('\0')
      }
    }
  }

  await visit(directory)
  return hash.digest('hex')
}

export async function loadTask(options: {
  manifestPath: string
  controlledRoots: string[]
}) {
  let raw: string
  let manifest: TaskManifest
  let fixture: string
  try {
    raw = await readFile(options.manifestPath, 'utf8')
    manifest = parseTaskManifest(JSON.parse(raw))
    fixture = await realpath(
      path.resolve(path.dirname(options.manifestPath), manifest.fixture),
    )
  } catch (error) {
    if (error instanceof InvalidTaskError) throw error
    invalidTask(
      error instanceof Error ? error.message : String(error),
    )
  }
  const roots = (
    await Promise.all(
      options.controlledRoots.map((root) =>
        realpath(root).catch(() => undefined),
      ),
    )
  ).filter((root): root is string => root !== undefined)
  const inside = roots.some((root) => {
    const relative = path.relative(root, fixture)
    return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative))
  })
  if (!inside) invalidTask('Fixture is outside controlled roots')

  return {
    manifest,
    fixture,
    manifestSha256: sha256(raw),
    fixtureSha256: await hashTree(fixture),
  }
}

新建 eval/oracles.ts。transcript oracle 只检查结构化的 message / tool event,不读第 20 章渲染出来的终端文本:

import { createHash } from 'node:crypto'
import { readFile } from 'node:fs/promises'
import path from 'node:path'
import { spawn } from 'node:child_process'
import type {
  OracleResult,
  OracleSpec,
  StructuredTranscript,
} from './types.js'

function commandExit(options: {
  command: string
  args: string[]
  cwd: string
  env: NodeJS.ProcessEnv
  signal: AbortSignal
}): Promise<number> {
  return new Promise((resolve, reject) => {
    const child = spawn(options.command, options.args, {
      cwd: options.cwd,
      env: options.env,
      stdio: 'ignore',
      signal: options.signal,
    })
    child.once('error', reject)
    child.once('close', (code) => resolve(code ?? -1))
  })
}

function assistantText(transcript: StructuredTranscript): string {
  return transcript.messages.flatMap((message) => {
    if (message.role !== 'assistant') return []
    if (typeof message.content === 'string') return [message.content]
    return message.content.flatMap((block) =>
      block.type === 'text' ? [block.text] : [],
    )
  }).join('\n')
}

async function runOracle(
  spec: OracleSpec,
  options: {
    cwd: string
    env: NodeJS.ProcessEnv
    signal: AbortSignal
    transcript: StructuredTranscript
  },
): Promise<OracleResult> {
  if (spec.type === 'exit_code') {
    const actual = await commandExit({ ...spec, ...options })
    return {
      spec,
      passed: actual === spec.expected,
      actual: String(actual),
    }
  }

  if (spec.type === 'file_state') {
    const absolute = path.resolve(options.cwd, spec.path)
    const relative = path.relative(options.cwd, absolute)
    if (relative.startsWith('..') || path.isAbsolute(relative)) {
      return { spec, passed: false, actual: 'path escaped workspace' }
    }
    const content = await readFile(absolute, 'utf8').catch(() => undefined)
    if (content === undefined) {
      return { spec, passed: false, actual: 'file missing' }
    }
    if (spec.equals !== undefined) {
      return { spec, passed: content === spec.equals, actual: content }
    }
    if (spec.contains !== undefined) {
      return { spec, passed: content.includes(spec.contains), actual: content }
    }
    const digest = createHash('sha256').update(content).digest('hex')
    return { spec, passed: digest === spec.sha256, actual: digest }
  }

  if (spec.assertion === 'tool_called') {
    const names = options.transcript.events.flatMap((event) =>
      event.type === 'tool_start' ? [event.name] : [],
    )
    return {
      spec,
      passed: spec.name !== undefined && names.includes(spec.name),
      actual: names.join(','),
    }
  }

  if (spec.assertion === 'tool_result_contains') {
    const results = options.transcript.events.flatMap((event) =>
      event.type === 'tool_end' &&
      (spec.name === undefined || event.name === spec.name)
        ? [event.content]
        : [],
    )
    return {
      spec,
      passed: spec.contains !== undefined &&
        results.some((value) => value.includes(spec.contains!)),
      actual: results.join('\n'),
    }
  }

  const text = assistantText(options.transcript)
  return {
    spec,
    passed: spec.contains !== undefined && text.includes(spec.contains),
    actual: text,
  }
}

export async function runOracles(
  specs: OracleSpec[],
  options: Parameters<typeof runOracle>[1],
): Promise<OracleResult[]> {
  const results: OracleResult[] = []
  for (const spec of specs) results.push(await runOracle(spec, options))
  return results
}

给 src/model.ts 加一个构造函数,传入精确的模型和输出上限。它返回的仍是原来的 CallModel,不增加 Provider 层:

export function createAnthropicCallModel(options: {
  client: Anthropic
  model: string
  maxTokens: number
  // 显式冻结采样参数:默认值由 provider 决定,不该由默认值决定实验结论。
  temperature: number
}): CallModel {
  return async (request) => streamAnthropicMessage({
    ...request,
    client: options.client,
    model: options.model,
    maxTokens: options.maxTokens,
    temperature: options.temperature,
  })
}

export function createAnthropicCountInputTokens(options: {
  client: Anthropic
  model: string
}): CountInputTokens {
  return async (request) => {
    const result = await options.client.messages.countTokens({
      model: options.model,
      system: request.system,
      messages: request.messages,
      tools: request.tools,
      cache_control: {
        type: 'ephemeral',
        ttl: '5m',
      },
    }, { signal: request.signal })
    return result.input_tokens
  }
}

把 nodeEnv 从对象字面量改成普通的构造函数,可以指定 cwd 和子进程环境。所有相对路径都先解析到 attempt workspace 下,Bash 也用这个 cwd:

export function createNodeEnv(options: {
  cwd: string
  processEnv: NodeJS.ProcessEnv
}): ExecutionEnv {
  const resolvePath = (file: string) =>
    path.resolve(options.cwd, file)

  return {
    readFile: (file, signal) =>
      readFile(resolvePath(file), { encoding: 'utf8', signal }),
    writeFile: (file, content, signal) =>
      writeFile(resolvePath(file), content, { signal }),
    listFiles: async (directory) => {
      // 保持原有 readdir + DirectoryEntry 映射,只把路径换成 resolvePath(directory)。
      return await listDirectory(resolvePath(directory))
    },
    exec: (command, signal) =>
      execShell(command, {
        cwd: options.cwd,
        env: options.processEnv,
        signal,
      }),
    execFile: (file, args, signal) =>
      execProgram(file, args, {
        cwd: options.cwd,
        env: options.processEnv,
        signal,
      }),
  }
}

export const nodeEnv = createNodeEnv({
  cwd: process.cwd(),
  processEnv: process.env,
})

这里的 listDirectory、execShell、execProgram,是把第 09 章已有的对象字段原样提成同一文件里的函数。进程组、Abort 和截断的行为都不变。没列出来的实现也不改。

新建 eval/pricing.ts。eval 的成本只按本次 run 读到的价格快照计算,不再调用第 10 章那个把模型价格写死的 estimateCostUsd:

import { readFile } from 'node:fs/promises'
import type { Usage } from '../src/usage.js'
import { sha256 } from './manifest.js'

export type PricingSnapshot = {
  schemaVersion: 1
  effectiveDate: string
  currency: 'USD'
  model: string
  source: string
  usdPerMillionTokens: {
    input: number
    output: number
    cacheRead: number
    cacheCreation5m: number
    cacheCreation1h: number
  }
}

function positive(value: unknown): value is number {
  return typeof value === 'number' && Number.isFinite(value) && value >= 0
}

export async function loadPricingSnapshot(
  file: string,
  expectedModel: string,
): Promise<{
  snapshot: PricingSnapshot
  raw: string
  sha256: string
}> {
  const raw = await readFile(file, 'utf8')
  const value = JSON.parse(raw) as Partial<PricingSnapshot>
  const rates = value.usdPerMillionTokens
  if (
    value.schemaVersion !== 1 ||
    value.currency !== 'USD' ||
    value.model !== expectedModel ||
    typeof value.effectiveDate !== 'string' ||
    typeof value.source !== 'string' ||
    rates === undefined ||
    !positive(rates.input) ||
    !positive(rates.output) ||
    !positive(rates.cacheRead) ||
    !positive(rates.cacheCreation5m) ||
    !positive(rates.cacheCreation1h)
  ) {
    throw new Error('Invalid or mismatched pricing snapshot')
  }
  return {
    snapshot: value as PricingSnapshot,
    raw,
    sha256: sha256(raw),
  }
}

export function estimateEvalCostUsd(
  usage: Usage,
  snapshot: PricingSnapshot,
): number {
  const rates = snapshot.usdPerMillionTokens
  const knownCreation =
    usage.cacheCreation5mInputTokens +
    usage.cacheCreation1hInputTokens
  const unclassifiedCreation = Math.max(
    0,
    usage.cacheCreationInputTokens - knownCreation,
  )
  return (
    usage.inputTokens * rates.input +
    usage.outputTokens * rates.output +
    usage.cacheReadInputTokens * rates.cacheRead +
    usage.cacheCreation5mInputTokens * rates.cacheCreation5m +
    usage.cacheCreation1hInputTokens * rates.cacheCreation1h +
    unclassifiedCreation * rates.cacheCreation5m
  ) / 1_000_000
}

当前教学模型的 dated ID(带日期的精确模型 ID)和各 cache bucket 的价格,已在 2026-08-25 对照过 Anthropic 官方的模型 ID 文档和prompt caching 价格表。核对结果要保存成数据,而不是只写在正文里:

{
  "schemaVersion": 1,
  "effectiveDate": "2026-08-25",
  "currency": "USD",
  "model": "claude-haiku-4-5-20251001",
  "source": "https://platform.claude.com/docs/en/build-with-claude/prompt-caching",
  "usdPerMillionTokens": {
    "input": 1,
    "output": 5,
    "cacheRead": 0.1,
    "cacheCreation5m": 1.25,
    "cacheCreation1h": 2
  }
}

新建 eval/run-attempt.ts。它接收正常 runtime 已有的工具组装函数,方便测试时替换 callModel。这不是第二套 runtime,真正执行的仍然只有 runAgent:

import type Anthropic from '@anthropic-ai/sdk'
import assert from 'node:assert/strict'
import { execFile } from 'node:child_process'
import { promisify } from 'node:util'
import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import os from 'node:os'
import path from 'node:path'
import {
  runAgent,
  type BeforeToolCall,
  type BeforeToolCallResult,
  type ToolCallContext,
} from '../src/agent.js'
import type { CompactionConfig } from '../src/compaction.js'
import { truncateToolCallResult } from '../src/context.js'
import { createNodeEnv } from '../src/env.js'
import {
  createAnthropicCallModel,
  type CallModel,
  type ModelRequest,
  type ModelResponse,
} from '../src/model.js'
import { approvalKey } from '../src/permission.js'
import {
  buildSystemPrompt,
  contextUpdateBlocks,
  readContextSnapshot,
} from '../src/system.js'
import type { ApprovalRecord } from '../src/terminal-approval.js'
import type { Tool } from '../src/tools.js'
import {
  addModelUsage,
  emptyUsage,
  type Usage,
} from '../src/usage.js'
import {
  InvalidTaskError,
  loadTask,
  sha256,
} from './manifest.js'
import { runOracles } from './oracles.js'
import {
  estimateEvalCostUsd,
  loadPricingSnapshot,
  type PricingSnapshot,
} from './pricing.js'
import {
  recordAgentEvent,
  type AttemptRecord,
  type EvalConfig,
  type StructuredTranscript,
} from './types.js'

const execFileAsync = promisify(execFile)

const DEFAULT_EVAL_COMPACTION: CompactionConfig = {
  contextWindow: 200_000,
  reserveTokens: 24_000,
  keepRecentTokens: 16_000,
}

type AttemptDependencies = {
  client: Anthropic
  countInputTokens: Parameters<typeof runAgent>[0]['countInputTokens']
  createTools(options: {
    cwd: string
    features: EvalConfig['features']
    callModel: CallModel
    signal: AbortSignal
  }): Promise<{ tools: Tool[]; close(): Promise<void> }>
  callModel?: CallModel
  metadata?: { gitSha: string; sdkVersion: string }
  now?: () => Date
}

function settledTokens(usage: Usage): number {
  return usage.inputTokens +
    usage.outputTokens +
    usage.cacheReadInputTokens +
    usage.cacheCreationInputTokens
}

function safeEnvironment(workspace: string): NodeJS.ProcessEnv {
  const copy = (name: string) =>
    process.env[name] === undefined ? {} : { [name]: process.env[name] }
  return {
    ...copy('PATH'),
    ...copy('LANG'),
    ...copy('LC_ALL'),
    ...copy('TZ'),
    HOME: path.join(workspace, '.home'),
    npm_config_cache: path.join(workspace, '.npm-cache'),
    CI: '1',
  }
}

async function applyRecordedApproval(
  context: ToolCallContext,
  signal: AbortSignal,
  options: {
    env: ReturnType<typeof createNodeEnv>
    policy: EvalConfig['approvalPolicy']
    records: ApprovalRecord[]
    now: () => Date
  },
): Promise<BeforeToolCallResult> {
  signal.throwIfAborted()
  const request = context.approval
  if (!request) {
    return { action: 'continue' }
  }
  const decision = options.policy === 'allow_all_recorded'
    ? 'once' as const
    : 'deny' as const
  options.records.push({
    key: approvalKey(request.scope, options.env),
    description: request.description,
    decision,
    source: 'non_interactive',
    at: options.now().toISOString(),
  })
  return decision === 'deny'
    ? {
        action: 'block',
        reason: `Permission denied by eval policy for ${request.description}.`,
      }
    : { action: 'continue' }
}

function failedAttemptRecord(
  options: {
    attemptId: string
    manifestPath: string
    config: EvalConfig
    configRaw: string
  },
  startedAt: string,
  finishedAt: string,
  error: unknown,
  context: {
    usageDelta: Usage
    pricing?: Awaited<ReturnType<typeof loadPricingSnapshot>>
    task?: Awaited<ReturnType<typeof loadTask>>
    gitSha?: string
    sdkVersion?: string
    timedOut: boolean
    operatorAborted: boolean
  },
): AttemptRecord {
  const message = error instanceof Error ? error.message : String(error)
  const cost = context.pricing
    ? estimateEvalCostUsd(context.usageDelta, context.pricing.snapshot)
    : 0
  return {
    schemaVersion: 1,
    attemptId: options.attemptId,
    taskId: context.task?.manifest.id ?? path.basename(options.manifestPath, '.json'),
    taskVersion: context.task?.manifest.taskVersion ?? 'unavailable',
    taskManifestSha256: context.task?.manifestSha256 ?? 'unavailable',
    fixtureSha256: context.task?.fixtureSha256 ?? 'unavailable',
    configName: options.config.name,
    configSha256: sha256(options.configRaw),
    status: context.timedOut
      ? 'timeout'
      : context.operatorAborted
        ? 'aborted'
        : error instanceof InvalidTaskError
          ? 'invalid_task'
          : 'infra_error',
    usageDelta: context.usageDelta,
    estimatedCostUsd: cost,
    startedAt,
    finishedAt,
    metadata: {
      gitSha: context.gitSha ?? 'unavailable',
      model: options.config.model,
      temperature: options.config.temperature,
      anthropicSdkVersion: context.sdkVersion ?? 'unavailable',
      node: process.version,
      os: `${os.platform()} ${os.release()}`,
      arch: os.arch(),
      pricingSnapshot: options.config.pricingSnapshot,
      pricingSnapshotSha256: context.pricing?.sha256 ?? 'unavailable',
    },
    oracleResults: [],
    error: message,
  }
}

async function callModelWithBudget(
  base: CallModel,
  request: ModelRequest,
  config: EvalConfig,
  pricing: PricingSnapshot,
  meter: { usageDelta: Usage; providerError?: string },
): Promise<ModelResponse> {
  if (
    settledTokens(meter.usageDelta) >= config.maxSettledTokens ||
    estimateEvalCostUsd(meter.usageDelta, pricing) >= config.maxUsd
  ) {
    throw new Error('EVAL_BUDGET_GATE')
  }
  try {
    const response = await base(request)
    addModelUsage(meter.usageDelta, response.usage)
    return response
  } catch (error) {
    if (!(error instanceof Error && error.message === 'EVAL_BUDGET_GATE')) {
      meter.providerError = error instanceof Error
        ? error.message
        : String(error)
    }
    throw error
  }
}

async function packageVersion(
  projectRoot: string,
  packageName: string,
): Promise<string> {
  const file = path.join(
    projectRoot,
    'node_modules',
    ...packageName.split('/'),
    'package.json',
  )
  const value = JSON.parse(await readFile(file, 'utf8')) as { version?: unknown }
  if (typeof value.version !== 'string') throw new Error(`No version for ${packageName}`)
  return value.version
}

export async function runAttempt(options: {
  projectRoot: string
  manifestPath: string
  config: EvalConfig
  configRaw: string
  attemptId: string
  outputDirectory: string
  signal: AbortSignal
  dependencies: AttemptDependencies
}): Promise<AttemptRecord> {
  const now = options.dependencies.now ?? (() => new Date())
  const startedAt = now().toISOString()
  const attemptDirectory = path.join(options.outputDirectory, options.attemptId)
  await mkdir(attemptDirectory, { recursive: false })

  let temporaryRoot: string | undefined
  let task: Awaited<ReturnType<typeof loadTask>> | undefined
  let pricing: Awaited<ReturnType<typeof loadPricingSnapshot>> | undefined
  let gitSha: string | undefined
  let sdkVersion: string | undefined
  const meter = {
    usageDelta: emptyUsage(),
    providerError: undefined as string | undefined,
  }
  let ownedTools: Awaited<ReturnType<AttemptDependencies['createTools']>> | undefined
  let timedOut = false
  const timeoutController = new AbortController()
  const timer = setTimeout(() => {
    timedOut = true
    timeoutController.abort(new Error('Eval attempt timed out'))
  }, options.config.timeoutMs)
  timer.unref()
  const signal = AbortSignal.any([
    options.signal,
    timeoutController.signal,
  ])

  const closeOwnedTools = async () => {
    const current = ownedTools
    ownedTools = undefined
    if (current) await current.close()
  }

  try {
    signal.throwIfAborted()
    task = await loadTask({
      manifestPath: options.manifestPath,
      controlledRoots: [
        path.join(options.projectRoot, 'practice'),
        path.join(options.projectRoot, 'eval', 'fixtures'),
      ],
    })
    temporaryRoot = await mkdtemp(path.join(os.tmpdir(), 'byoaa-eval-'))
    const workspace = path.join(temporaryRoot, 'workspace')
    await cp(task.fixture, workspace, { recursive: true, verbatimSymlinks: true })
    const processEnv = safeEnvironment(workspace)
    await mkdir(processEnv.HOME!, { recursive: true })
    await mkdir(processEnv.npm_config_cache!, { recursive: true })

    const metadata = options.dependencies.metadata
    const [loadedGitSha, loadedSdkVersion, loadedPricing] = await Promise.all([
      metadata
        ? Promise.resolve(metadata.gitSha)
        : execFileAsync('git', ['rev-parse', 'HEAD'], {
            cwd: options.projectRoot,
          }).then((result) => result.stdout.trim()),
      metadata
        ? Promise.resolve(metadata.sdkVersion)
        : packageVersion(options.projectRoot, '@anthropic-ai/sdk'),
      loadPricingSnapshot(
        path.resolve(options.projectRoot, options.config.pricingSnapshot),
        options.config.model,
      ),
    ])
    gitSha = loadedGitSha
    sdkVersion = loadedSdkVersion
    pricing = loadedPricing

    const env = createNodeEnv({ cwd: workspace, processEnv })
    const approvals: ApprovalRecord[] = []
    const recordedApproval = {
      env,
      policy: options.config.approvalPolicy,
      records: approvals,
      now,
    }
    const beforeToolCall: BeforeToolCall = (context, currentSignal) =>
      applyRecordedApproval(
        context,
        currentSignal,
        recordedApproval,
      )
    const runtime = {
      cwd: workspace,
      platform: process.platform,
      shell: processEnv.SHELL ?? '(not inherited)',
      localDate: startedAt.slice(0, 10),
      timeZone: 'UTC',
    }
    // system 不含 workspace 路径,attempt 之间共享同一条缓存条目。
    const system = buildSystemPrompt()
    const contextSnapshot = await readContextSnapshot(
      env, runtime, signal, [],
    )
    const contextMessage = {
      role: 'user' as const,
      content: contextUpdateBlocks(undefined, contextSnapshot),
    }
    const baseCallModel = options.dependencies.callModel ??
      createAnthropicCallModel({
        client: options.dependencies.client,
        model: options.config.model,
        maxTokens: options.config.maxTokensPerRequest,
        temperature: options.config.temperature,
      })
    async function trackedCallModel(
      request: ModelRequest,
    ): Promise<ModelResponse> {
      return await callModelWithBudget(
        baseCallModel,
        request,
        options.config,
        pricing.snapshot,
        meter,
      )
    }
    ownedTools = await options.dependencies.createTools({
      cwd: workspace,
      features: options.config.features,
      callModel: trackedCallModel,
      signal,
    })
    const events: StructuredTranscript['events'] = []
    const run = await runAgent({
      messages: [
        contextMessage,
        { role: 'user', content: task.manifest.prompt },
      ],
      rootTask: task.manifest.prompt,
      system,
      callModel: trackedCallModel,
      countInputTokens: options.dependencies.countInputTokens,
      tools: ownedTools.tools,
      env,
      signal,
      maxTurns: options.config.maxTurns,
      beforeToolCall,
      afterToolCall: truncateToolCallResult,
      onEvent: (event) => events.push(recordAgentEvent(event)),
      ...(options.config.features.compaction
        ? {
            compaction: DEFAULT_EVAL_COMPACTION,
            pinned: [contextMessage],
          }
        : {}),
    })

    // Task Tool 必须使用 createTools 收到的 trackedCallModel;因此 parent、
    // compaction 与 child 的每次模型调用都经过同一个 meter。
    assert.deepEqual(meter.usageDelta, run.usageDelta)
    await closeOwnedTools()

    const transcript: StructuredTranscript = {
      prompt: task.manifest.prompt,
      messages: run.messages,
      events,
      approvals,
    }
    // run 的取消信号已经 abort 后不能再交给 exit-code oracle;否则一个真正的
    // timeout 会在写 transcript 前再次抛错,只留下 attempt.json。已取消的 run
    // 不判 oracle;正常 run 则用独立的短超时收口 oracle 自身。
    const runWasAborted = timedOut || options.signal.aborted || run.reason === 'aborted'
    const oracleResults = runWasAborted
      ? []
      : await runOracles(task.manifest.oracles, {
          cwd: workspace,
          env: processEnv,
          signal: AbortSignal.timeout(Math.min(30_000, options.config.timeoutMs)),
          transcript,
        })
    const overBudget =
      settledTokens(run.usageDelta) > options.config.maxSettledTokens ||
      estimateEvalCostUsd(run.usageDelta, pricing.snapshot) > options.config.maxUsd ||
      (
        run.reason === 'failed' &&
        run.error.message === 'EVAL_BUDGET_GATE'
      )
    const status = timedOut
      ? 'timeout'
      : options.signal.aborted || run.reason === 'aborted'
        ? 'aborted'
        : meter.providerError
          ? 'infra_error'
          : overBudget
            ? 'budget_exceeded'
            : run.reason === 'done' && oracleResults.every((item) => item.passed)
              ? 'pass'
              : 'fail'

    const record: AttemptRecord = {
      schemaVersion: 1,
      attemptId: options.attemptId,
      taskId: task.manifest.id,
      taskVersion: task.manifest.taskVersion,
      taskManifestSha256: task.manifestSha256,
      fixtureSha256: task.fixtureSha256,
      configName: options.config.name,
      configSha256: sha256(options.configRaw),
      status,
      runReason: run.reason,
      usageDelta: run.usageDelta,
      estimatedCostUsd: estimateEvalCostUsd(run.usageDelta, pricing.snapshot),
      startedAt,
      finishedAt: now().toISOString(),
      metadata: {
        gitSha: gitSha!,
        model: options.config.model,
        temperature: options.config.temperature,
        anthropicSdkVersion: sdkVersion!,
        node: process.version,
        os: `${os.platform()} ${os.release()}`,
        arch: os.arch(),
        pricingSnapshot: options.config.pricingSnapshot,
        pricingSnapshotSha256: pricing.sha256,
      },
      oracleResults,
      ...(run.reason === 'failed'
        ? { error: `${run.error.code}: ${run.error.message}` }
        : {}),
    }
    await Promise.all([
      writeFile(path.join(attemptDirectory, 'attempt.json'), `${JSON.stringify(record, null, 2)}\n`),
      writeFile(path.join(attemptDirectory, 'transcript.json'), `${JSON.stringify(transcript, null, 2)}\n`),
      writeFile(path.join(attemptDirectory, 'oracle.json'), `${JSON.stringify(oracleResults, null, 2)}\n`),
    ])
    return record
  } catch (error) {
    let finalError = error
    try {
      await closeOwnedTools()
    } catch (closeError) {
      finalError = new AggregateError(
        [error, closeError],
        'Attempt and tool cleanup both failed',
      )
    }
    const record = failedAttemptRecord(
      options,
      startedAt,
      now().toISOString(),
      finalError,
      {
        // 若 harness 在 run 外层失败,meter 仍覆盖所有已经结算的
        // parent / compaction / child 调用。
        usageDelta: meter.usageDelta,
        pricing,
        task,
        gitSha,
        sdkVersion,
        timedOut,
        operatorAborted: options.signal.aborted && !timedOut,
      },
    )
    await writeFile(
      path.join(attemptDirectory, 'attempt.json'),
      `${JSON.stringify(record, null, 2)}\n`,
    )
    return record
  } finally {
    clearTimeout(timer)
    await closeOwnedTools().catch(() => {})
    if (temporaryRoot) await rm(temporaryRoot, { recursive: true, force: true })
  }
}

preflight(正式运行前的检查)失败时,还拿不到 task / fixture hash、git 或 SDK 元数据。所以失败记录要把这些字段明确写成 unavailable,不能编一个值。正常进入 run 的 attempt,这些字段必须全部记录。

失败分两类:

  • manifest / controlled fixture 校验失败:invalid_task。
  • 其他准备或持久化故障:infra_error。

callModel 的 meter 和 RunResult.usageDelta 是两份记账,可能慢慢对不上。为此补一个断言:每个正常 settle 的 attempt 里,两者逐桶相等。

budget gate 的处理顺序是:

  1. 只在下一次调用开始前检查,超了就抛出。
  2. 刚完成的那次调用,先由 runAgent 入账。
  3. attempt 结束时,按实际 usage 标成 budget_exceeded。

所以 soft cap 不会漏账,最多只会超出一个调用。

一个最小的 task manifest:

{
  "schemaVersion": 1,
  "id": "cart-fix",
  "taskVersion": "1.0.0",
  "stratum": "general",
  "fixture": "../../practice/cart",
  "prompt": "修复购物车总价错误,运行测试,并只在有证据后报告完成。",
  "oracles": [
    {
      "type": "exit_code",
      "command": "node",
      "args": ["--test"],
      "expected": 0
    },
    {
      "type": "transcript",
      "assertion": "tool_called",
      "name": "bash"
    }
  ]
}

配置必须把审批和所有上限都完整写出来:

{
  "schemaVersion": 1,
  "name": "smoke",
  "model": "claude-haiku-4-5-20251001",
  "maxTurns": 12,
  "maxTokensPerRequest": 2048,
  "temperature": 0,
  "timeoutMs": 180000,
  "maxSettledTokens": 120000,
  "maxUsd": 0.75,
  "approvalPolicy": "allow_all_recorded",
  "features": {
    "compaction": true,
    "todo": true
  },
  "pricingSnapshot": "eval/pricing/2026-08-25.json"
}

pricing 文件保存日期、币种和每个 usage bucket 的单价。旧的 run 永远用自己记录的 snapshot hash 计算,不会被以后的常量重新计算。

新建 eval/cli.ts。它做这几件事:

  1. 读取并校验一份 config。
  2. 先创建 runs/<UTC>-<git-short>-<config>/。目录已经存在就失败,不覆盖。
  3. 按 task id 的 ASCII 顺序,逐个调用 runAttempt。
  4. 在根目录的 run.json 里保存 task manifest 列表、开始 / 结束时间,以及所有 attempt 的相对路径。

npm 脚本只暴露这一个入口:

import Anthropic from '@anthropic-ai/sdk'
import { execFile } from 'node:child_process'
import { promisify } from 'node:util'
import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises'
import path from 'node:path'
import {
  createAnthropicCountInputTokens,
} from '../src/model.js'
import { createSessionDraft, createSessionState } from '../src/session.js'
import { truncateToolCallResult } from '../src/context.js'
import {
  createReadOnlyTools,
  createTaskTool,
} from '../src/task-tool.js'
import {
  createTodoWriteTool,
  tools as localTools,
} from '../src/tools.js'
import { parseEvalConfig } from './manifest.js'
import { runAttempt } from './run-attempt.js'
import type { AttemptRecord } from './types.js'

const execFileAsync = promisify(execFile)
const projectRoot = process.cwd()

function argument(name: string): string {
  const index = process.argv.indexOf(name)
  const value = process.argv[index + 1]
  if (index < 0 || value === undefined) {
    throw new Error(`Missing ${name}`)
  }
  return value
}

function ascii(left: string, right: string): number {
  return left < right ? -1 : left > right ? 1 : 0
}

const configPath = path.resolve(projectRoot, argument('--config'))
const configRaw = await readFile(configPath, 'utf8')
const config = parseEvalConfig(JSON.parse(configRaw))
if (!process.env.ANTHROPIC_API_KEY) {
  throw new Error('ANTHROPIC_API_KEY is required for eval')
}

const client = new Anthropic({
  apiKey: process.env.ANTHROPIC_API_KEY,
  maxRetries: 0,
})
const countInputTokens = createAnthropicCountInputTokens({
  client,
  model: config.model,
})
const taskDirectory = path.join(projectRoot, 'eval', 'tasks')
const manifests = (await readdir(taskDirectory))
  .filter((name) => name.endsWith('.json'))
  .sort(ascii)
  .map((name) => path.join(taskDirectory, name))
if (manifests.length === 0) throw new Error('No eval task manifests found')
const manifestRecords = manifests.map((file) => path.relative(projectRoot, file))

const { stdout } = await execFileAsync('git', ['rev-parse', '--short=12', 'HEAD'], {
  cwd: projectRoot,
})
const stamp = new Date().toISOString().replace(/[-:.]/g, '')
const runId = `${stamp}-${stdout.trim()}-${config.name}`
const outputDirectory = path.join(projectRoot, 'eval', 'runs', runId)
await mkdir(outputDirectory, { recursive: false })

const outer = new AbortController()
process.once('SIGINT', () => outer.abort(new Error('Eval cancelled')))
const records: AttemptRecord[] = []
await writeFile(
  path.join(outputDirectory, 'run.json'),
  `${JSON.stringify({ schemaVersion: 1, runId, status: 'running', manifests: manifestRecords }, null, 2)}\n`,
)

let runError: unknown
try {
  for (const [index, manifestPath] of manifests.entries()) {
    const record = await runAttempt({
      projectRoot,
      manifestPath,
      config,
      configRaw,
      attemptId: `${path.basename(manifestPath, '.json')}--${String(index + 1).padStart(3, '0')}`,
      outputDirectory,
      signal: outer.signal,
      dependencies: {
        client,
        countInputTokens,
        async createTools(options) {
          const draft = createSessionDraft(createSessionState())
          const readOnlyTools = createReadOnlyTools(localTools)
          const taskTool = createTaskTool({
            callModel: options.callModel,
            countInputTokens,
            readOnlyTools,
            afterToolCall: truncateToolCallResult,
            maxTurns: 6,
            maxTasks: 2,
          })
          return {
            tools: [
              ...localTools,
              ...(options.features.todo
                ? [createTodoWriteTool(draft)]
                : []),
              taskTool,
            ],
            async close() {},
          }
        },
      },
    })
    records.push(record)
    if (outer.signal.aborted) break
  }
} catch (error) {
  runError = error
}

await writeFile(
  path.join(outputDirectory, 'run.json'),
  `${JSON.stringify({
    schemaVersion: 1,
    runId,
    status: runError
      ? 'infra_error'
      : outer.signal.aborted
        ? 'aborted'
        : 'complete',
    config,
    manifests: manifestRecords,
    attempts: records.map((record) => ({
      attemptId: record.attemptId,
      status: record.status,
    })),
    ...(runError ? {
      error: runError instanceof Error ? runError.stack ?? runError.message : String(runError),
    } : {}),
  }, null, 2)}\n`,
)
if (runError) throw runError

标准任务集不加载用户机器上的 .byoaa-mcp.json,因为外部 server 和凭据会让结果没法复现。Task Tool 仍然保留,而且 child 用的是 factory 收到的同一个带预算的 callModel。

Part 5 的 MCP 实证用仓库里固定的 server fixture,在第 22 章作为单独的 evidence run 重跑。它不混进通用 coding task 的 A / B / C 通过率。

{
  "scripts": {
    "eval": "tsx eval/cli.ts"
  }
}
npm run eval -- --config eval/configs/smoke.json

每个 run 的最小目录结构如下:

eval/runs/2026-08-25T083000Z-a1b2c3d-smoke/
  run.json
  cart-fix--001/
    attempt.json
    transcript.json
    oracle.json

运行结果保存在本地的 eval/runs/。报告引用通过率或成本时,应写清任务、模型、配置和样本数。

自动化测试与真实验收

新建 eval/harness.test.ts。它测的是 harness 本身,不是再测一遍 agent:

import Anthropic from '@anthropic-ai/sdk'
import assert from 'node:assert/strict'
import test from 'node:test'
import {
  mkdir,
  mkdtemp,
  readFile,
  writeFile,
} from 'node:fs/promises'
import os from 'node:os'
import path from 'node:path'
import type { CallModel, ModelUsage } from '../src/model.js'
import { runAttempt } from './run-attempt.js'
import type { EvalConfig } from './types.js'

const MODEL = 'claude-haiku-4-5-20251001'

function usage(input = 10, output = 5): ModelUsage {
  return {
    input_tokens: input,
    output_tokens: output,
    cache_read_input_tokens: 0,
    cache_creation_input_tokens: 0,
    cache_creation: {
      ephemeral_5m_input_tokens: 0,
      ephemeral_1h_input_tokens: 0,
    },
  }
}

function config(overrides: Partial<EvalConfig> = {}): EvalConfig {
  return {
    schemaVersion: 1,
    name: 'test',
    model: MODEL,
    maxTurns: 2,
    maxTokensPerRequest: 32,
    timeoutMs: 5_000,
    maxSettledTokens: 10_000,
    maxUsd: 1,
    approvalPolicy: 'allow_all_recorded',
    features: { compaction: false, todo: false },
    pricingSnapshot: 'eval/pricing/test.json',
    ...overrides,
  }
}

async function makeProject(manifest?: unknown) {
  const root = await mkdtemp(path.join(os.tmpdir(), 'byoaa-harness-test-'))
  const fixture = path.join(root, 'practice', 'fixture')
  const tasks = path.join(root, 'eval', 'tasks')
  const pricing = path.join(root, 'eval', 'pricing')
  const output = path.join(root, 'eval', 'runs', 'test-run')
  await Promise.all([
    mkdir(fixture, { recursive: true }),
    mkdir(tasks, { recursive: true }),
    mkdir(pricing, { recursive: true }),
    mkdir(output, { recursive: true }),
  ])
  await writeFile(path.join(fixture, 'state.txt'), 'original')
  await writeFile(
    path.join(tasks, 'fixture.json'),
    `${JSON.stringify(manifest ?? {
      schemaVersion: 1,
      id: 'fixture',
      taskVersion: '1.0.0',
      stratum: 'general',
      fixture: '../../practice/fixture',
      prompt: 'finish the fixture',
      oracles: [{
        type: 'file_state',
        path: 'state.txt',
        equals: 'mutated',
      }],
    })}\n`,
  )
  await writeFile(path.join(pricing, 'test.json'), `${JSON.stringify({
    schemaVersion: 1,
    effectiveDate: '2026-08-25',
    currency: 'USD',
    model: MODEL,
    source: 'test fixture',
    usdPerMillionTokens: {
      input: 1,
      output: 5,
      cacheRead: 0.1,
      cacheCreation5m: 1.25,
      cacheCreation1h: 2,
    },
  })}\n`)
  return {
    root,
    fixture,
    manifestPath: path.join(tasks, 'fixture.json'),
    output,
  }
}

function finalResponse(modelUsage: ModelUsage): CallModel {
  return async () => ({
    content: [{ type: 'text', text: 'done' }],
    stop_reason: 'end_turn',
    usage: modelUsage,
  })
}

async function attempt(options: {
  project: Awaited<ReturnType<typeof makeProject>>
  attemptId: string
  seen?: string[]
  evalConfig?: EvalConfig
  callModel?: CallModel
  signal?: AbortSignal
}) {
  const evalConfig = options.evalConfig ?? config()
  return await runAttempt({
    projectRoot: options.project.root,
    manifestPath: options.project.manifestPath,
    config: evalConfig,
    configRaw: JSON.stringify(evalConfig),
    attemptId: options.attemptId,
    outputDirectory: options.project.output,
    signal: options.signal ?? new AbortController().signal,
    dependencies: {
      client: {} as Anthropic,
      metadata: { gitSha: 'test-sha', sdkVersion: 'test-sdk' },
      countInputTokens: async () => 1,
      callModel: options.callModel ?? finalResponse(usage()),
      async createTools({ cwd }) {
        const file = path.join(cwd, 'state.txt')
        options.seen?.push(await readFile(file, 'utf8'))
        await writeFile(file, 'mutated')
        return { tools: [], async close() {} }
      },
    },
  })
}

test('each attempt starts from a fresh copy', async () => {
  const project = await makeProject()
  const seen: string[] = []
  await attempt({ project, attemptId: '001', seen })
  await attempt({ project, attemptId: '002', seen })
  assert.deepEqual(seen, ['original', 'original'])
  assert.equal(
    await readFile(path.join(project.fixture, 'state.txt'), 'utf8'),
    'original',
  )
})

test('soft budget keeps the settled call in usage', async () => {
  const project = await makeProject()
  const record = await attempt({
    project,
    attemptId: 'budget',
    evalConfig: config({ maxSettledTokens: 100 }),
    callModel: finalResponse(usage(90, 20)),
  })

  assert.equal(record.status, 'budget_exceeded')
  assert.equal(record.usageDelta.inputTokens, 90)
  assert.equal(record.usageDelta.outputTokens, 20)
})

test('invalid transcript oracle is invalid_task and never calls the model', async () => {
  const project = await makeProject({
    schemaVersion: 1,
    id: 'bad-oracle',
    taskVersion: '1.0.0',
    stratum: 'general',
    fixture: '../../practice/fixture',
    prompt: 'do not run',
    oracles: [{ type: 'transcript', assertion: 'tool_called' }],
  })
  let calls = 0
  const record = await attempt({
    project,
    attemptId: 'invalid',
    callModel: async () => {
      calls += 1
      return await finalResponse(usage())({} as never)
    },
  })
  assert.equal(record.status, 'invalid_task')
  assert.equal(calls, 0)
})

test('timeout and operator abort are different statuses', async () => {
  const timeoutProject = await makeProject()
  const waitsForAbort: CallModel = async (request) => {
    await new Promise<void>((_resolve, reject) => {
      request.signal.addEventListener('abort', () => {
        reject(request.signal.reason)
      }, { once: true })
    })
    throw new Error('unreachable')
  }
  const timeout = await attempt({
    project: timeoutProject,
    attemptId: 'timeout',
    evalConfig: config({ timeoutMs: 5 }),
    callModel: waitsForAbort,
  })
  assert.equal(timeout.status, 'timeout')

  const abortProject = await makeProject()
  const controller = new AbortController()
  controller.abort(new Error('operator cancelled'))
  const aborted = await attempt({
    project: abortProject,
    attemptId: 'aborted',
    signal: controller.signal,
  })
  assert.equal(aborted.status, 'aborted')
})

同一个文件还必须覆盖下面这些情况:

  • manifest 越出 controlled root、字段非法、fixture 含 symlink → invalid_task,callModel 一次都没被调用。
  • timeout 触发的是同一个 AbortSignal,子进程退出,状态为 timeout。
  • provider 注入错误时,状态为 infra_error,不算普通的 fail。
  • allow_all_recorded 下,每次 approval 都有 key、description、decision、timestamp;deny_all 下,危险工具不执行。
  • 白名单下的工具进程,看不到测试进程临时注入的 SECRET_SHOULD_NOT_LEAK。但测试里要写明:这不是能阻止主动读取磁盘的 sandbox。
  • transcript oracle 对 RecordedEvent 判分。把 renderer 的文本换成任何语言,判分结果都不变。
  • attempt 目录已经存在时,拒绝覆盖;中途失败时,至少留下 attempt.json。
  • metadata 包含 git SHA、精确 model、temperature、SDK / Node / OS、config hash、fixture hash 和 pricing hash。缺任何一项,这条记录就算不合格。

运行:

npm test
npm run typecheck
npm run eval -- --config eval/configs/smoke.json

真实验收的步骤:

  1. 先用一份配置跑完整个任务集。检查 run 目录,不要只看汇总数字。
  2. 随机抽两个 attempt。从 fixture hash 恢复原始副本,逐条对照结构化 tool call、审批记录、文件结果和 usage。
  3. 故意把一个任务的 timeout 调到 1ms,把美元 cap 调到不够一次请求。确认 timeout 和 budget_exceeded 没有被混成 agent 的 fail。

本章允许结果是红的,不要因为红就去改考题或改 agent。

单次任务的记录齐全后,就能重复运行,并比较不同功能开关的效果。

章末修正:共享缓存前缀不等于共享完整输入

每个 attempt 的 tools 和 constant system 可以相同。但每个临时 workspace 的项目指令和 runtime 快照一定不同,所以它们作为第一条 context message,仍然要写进新的尾部。

评估报告必须把 cache read 和 creation 分桶记录。这样才能区分两种情况:“共享了基础前缀”,和“误以为整个请求都命中了”。