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

22 · 对照实验与证据收口

里程碑 → 对比三组的通过率、token 用量和费用

第 21 章已经能生成可信的单次 attempt。但“一次通过”仍然可能只是模型采样碰巧顺利。

本章先冻结 baseline(作为对照基准、之后不再改动的那次运行),再把同一批任务重复送进三份递增的配置:

  • A:关闭 compaction 和 Todo。
  • B:在 A 的基础上,只增加 compaction。
  • C:在 B 的基础上,再增加 Todo。

每个 task 的每次 repetition(重复)组成一个配对 block。三份配置在 block 内的运行顺序是打乱的。如果实验暴露了真实的 agent bug,修复要先保留 baseline,再用新 commit 另跑一轮。

和上一章相比,本章新增的是实验规则和汇总方式:

  • task 按 long-context、multi-step、general 分层。
  • 通过率报告 Wilson 区间。Wilson 区间是根据“通过几次、一共几次”算出的通过率范围,样本越少,范围越宽。
  • token 和 USD 报中位数和四分位距(IQR,中间一半数据所在的范围)。
  • A→B、B→C 只比较同一个 pair 里的结果。

结果可能是正向、负向,也可能看不出差异。不预设一定会出现哪一种。

能力边界与控制流

prepare-experiment
  → 读取 task manifests / fixtures / A B C configs
  → 校验只有 compaction / Todo 递增,其余字段逐字等价
  → 要求代码 worktree 干净,冻结 git SHA / pricing / task / fixture / config hash
  → 汇总每次尝试的预算;超过整轮上限则拒绝生成计划
  → 写 experiment-plan.json(存在则拒绝覆盖)

experiment-cli
  → 开始时及每个 attempt 前重核 git / dirty state / pricing 与全部 hash
  → task × repetition 组成 paired blocks
  → seed 固定:打乱 block 顺序,并在每个 block 内打乱 A/B/C
  → 每个 attempt 仍走第 21 章 runAttempt
  → 已结算总成本到整轮 soft cap 后不再启动下一 attempt
  → 持续写 experiment.json;旧 run 不覆盖

report
  → 全量 attempts.csv
  → overall + 三个 stratum 的区间 / token / USD
  → A→B、B→C 的 paired win / loss / tie 与成本差
  → infra / invalid / aborted 单列,不从磁盘删除

配置是递增的,但这不等于证明了因果。provider 的负载、模型后端的变化、任务数量,仍然会影响结果。

配对和随机顺序只做两件事:

  • 把能控制的偏差压小。
  • 让比较的单位从“两个总分”回到“同一个 task 的同一次 repetition”。

所以报告保存区间和原始 attempts,不会把 8/10 和 7/10 直接写成谁好谁坏。

修 agent 也不是不允许。如果某个红被归为真实的 agent_defect,按这个顺序处理:

  1. 先保留原来的 run,作为 baseline。
  2. 在新 commit 下生成 successor plan(接替原计划的新计划)。
  3. 新 plan 的 task / fixture / config / pricing hash 必须和 baseline 一致,只有 git SHA 和 plan ID 改变。

旧 plan 绑定的是旧 SHA,本来就不允许在新 commit 上直接重跑。如果是题目本身错了,就增加 task version,另建新 plan。旧结果标成 invalid_task,但继续保留。

缓存、Skills 和 MCP 的端到端探针单独运行。A/B/C 实验观察的是固定任务上功能开关的影响,两个结果回答的问题不同。

完整代码增量

当前的预算预检有一个已经核对过的问题。后面 worstCaseUsd 的实现只是把每个 attempt 的软门限加起来,没有算上末次调用可能超出的费用。所以它目前只是静态的预算估算,达不到“严格最坏费用”的目标。这里先标明待修复,不靠字段名承诺硬上限。

三份 config 除了 name 和 features 以外完全一致。A:无 compaction;B:A + compaction;C:B + Todo。

{
  "schemaVersion": 1,
  "name": "A-no-compaction",
  "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": false, "todo": false },
  "pricingSnapshot": "eval/pricing/2026-08-25.json"
}
{
  "schemaVersion": 1,
  "name": "B-compaction",
  "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": false },
  "pricingSnapshot": "eval/pricing/2026-08-25.json"
}
{
  "schemaVersion": 1,
  "name": "C-compaction-todo",
  "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"
}

新建 eval/experiment.ts。准备阶段读取当前的任务,运行阶段只认冻结后的 hash:

import assert from 'node:assert/strict'
import { execFile } from 'node:child_process'
import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises'
import path from 'node:path'
import { promisify } from 'node:util'
import {
  loadTask,
  parseEvalConfig,
  sha256,
} from './manifest.js'
import type {
  AttemptRecord,
  EvalConfig,
  TaskStratum,
} from './types.js'

export type ConfigKey = 'A' | 'B' | 'C'

const execFileAsync = promisify(execFile)
const CONFIG_KEYS = ['A', 'B', 'C'] as const
const STRATA = ['long-context', 'multi-step', 'general'] as const
const METRICS = [
  'pass_rate_wilson_95',
  'settled_tokens_median_iqr',
  'usd_median_iqr',
  'paired_win_loss_tie',
] as const

export type FrozenExperimentPlan = {
  schemaVersion: 1
  planId: string
  createdAt: string
  repetitions: number
  seed: number
  maxExperimentUsd: number
  worstCaseUsd: number
  repository: {
    gitSha: string
    pricingSnapshotPath: string
    pricingSnapshotSha256: string
  }
  tasks: Array<{
    id: string
    taskVersion: string
    stratum: TaskStratum
    manifestPath: string
    manifestSha256: string
    fixtureSha256: string
  }>
  configs: Array<{
    key: ConfigKey
    path: string
    sha256: string
  }>
  comparisons: Array<{
    left: ConfigKey
    right: ConfigKey
  }>
  metrics: readonly [
    'pass_rate_wilson_95',
    'settled_tokens_median_iqr',
    'usd_median_iqr',
    'paired_win_loss_tie',
  ]
}

export type ScheduledAttempt = {
  pairId: string
  taskId: string
  taskVersion: string
  taskStratum: TaskStratum
  repetition: number
  configKey: ConfigKey
  configPath: string
  attemptId: string
}

export type ExperimentAttempt = ScheduledAttempt & {
  record: AttemptRecord
}

export type ExperimentRecord = {
  schemaVersion: 1
  plan: FrozenExperimentPlan
  planSha256: string
  status: 'running' | 'complete' | 'aborted' | 'budget_exceeded' | 'infra_error'
  attempts: ExperimentAttempt[]
  settledCostUsd: number
  error?: string
}

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

function withoutAblation(config: EvalConfig) {
  return {
    schemaVersion: config.schemaVersion,
    model: config.model,
    maxTurns: config.maxTurns,
    maxTokensPerRequest: config.maxTokensPerRequest,
    timeoutMs: config.timeoutMs,
    maxSettledTokens: config.maxSettledTokens,
    maxUsd: config.maxUsd,
    approvalPolicy: config.approvalPolicy,
    pricingSnapshot: config.pricingSnapshot,
  }
}

export function assertIncrementalAblation(configs: Record<ConfigKey, EvalConfig>): void {
  for (const key of ['B', 'C'] as const) {
    assert.deepStrictEqual(
      withoutAblation(configs[key]),
      withoutAblation(configs.A),
      `${key} changes fields outside the ablation features`,
    )
  }
  const expected = {
    A: { compaction: false, todo: false },
    B: { compaction: true, todo: false },
    C: { compaction: true, todo: true },
  } as const
  for (const key of ['A', 'B', 'C'] as const) {
    assert.deepStrictEqual(configs[key].features, expected[key], `Invalid ${key} feature increment`)
  }
}

function createSeededRandom(seed: number): () => number {
  let value = seed >>> 0
  return () => {
    value += 0x6d2b79f5
    let result = value
    result = Math.imul(result ^ (result >>> 15), result | 1)
    result ^= result + Math.imul(result ^ (result >>> 7), result | 61)
    return ((result ^ (result >>> 14)) >>> 0) / 4_294_967_296
  }
}

function shuffle<T>(values: readonly T[], next: () => number): T[] {
  const result = [...values]
  for (let index = result.length - 1; index > 0; index -= 1) {
    const other = Math.floor(next() * (index + 1))
    ;[result[index], result[other]] = [result[other], result[index]]
  }
  return result
}

export function buildSchedule(plan: FrozenExperimentPlan): ScheduledAttempt[] {
  const next = createSeededRandom(plan.seed)
  const blocks = plan.tasks.flatMap((task) =>
    Array.from({ length: plan.repetitions }, (_, index) => ({
      task,
      repetition: index + 1,
    })),
  )
  return shuffle(blocks, next).flatMap(({ task, repetition }) => {
    const pairId = `${task.id}--r${String(repetition).padStart(2, '0')}`
    return shuffle(plan.configs, next).map((config) => ({
      pairId,
      taskId: task.id,
      taskVersion: task.taskVersion,
      taskStratum: task.stratum,
      repetition,
      configKey: config.key,
      configPath: config.path,
      attemptId: `${pairId}--${config.key}`,
    }))
  })
}

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

function projectPath(projectRoot: string, relative: string): string {
  if (relative === '' || path.isAbsolute(relative)) throw new Error(`Unsafe path: ${relative}`)
  const root = path.resolve(projectRoot)
  const absolute = path.resolve(root, relative)
  if (!absolute.startsWith(`${root}${path.sep}`)) throw new Error(`Path escapes project: ${relative}`)
  return absolute
}

function isSha256(value: unknown): value is string {
  return typeof value === 'string' && /^[a-f0-9]{64}$/.test(value)
}

export function parseFrozenPlan(value: unknown, projectRoot: string): FrozenExperimentPlan {
  if (!isRecord(value) || value.schemaVersion !== 1 ||
    typeof value.planId !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(value.planId) ||
    typeof value.createdAt !== 'string' || !Number.isSafeInteger(value.repetitions) ||
    Number(value.repetitions) < 2 || !Number.isSafeInteger(value.seed) ||
    typeof value.maxExperimentUsd !== 'number' || value.maxExperimentUsd <= 0 ||
    typeof value.worstCaseUsd !== 'number' || value.worstCaseUsd <= 0 ||
    value.worstCaseUsd > value.maxExperimentUsd || !isRecord(value.repository) ||
    typeof value.repository.gitSha !== 'string' || !/^[a-f0-9]{40,64}$/.test(value.repository.gitSha) ||
    typeof value.repository.pricingSnapshotPath !== 'string' ||
    !isSha256(value.repository.pricingSnapshotSha256) ||
    !Array.isArray(value.tasks) || value.tasks.length === 0 ||
    !Array.isArray(value.configs) || value.configs.length !== 3 ||
    !Array.isArray(value.comparisons) || !Array.isArray(value.metrics)) {
    throw new Error('Invalid frozen experiment plan')
  }
  projectPath(projectRoot, value.repository.pricingSnapshotPath)
  const ids = new Set<string>()
  for (const task of value.tasks) {
    if (!isRecord(task) || typeof task.id !== 'string' ||
      !/^[a-z0-9][a-z0-9_-]*$/.test(task.id) || ids.has(task.id) ||
      typeof task.taskVersion !== 'string' ||
      !STRATA.includes(task.stratum as typeof STRATA[number]) ||
      typeof task.manifestPath !== 'string' || !isSha256(task.manifestSha256) ||
      !isSha256(task.fixtureSha256)) throw new Error('Invalid frozen task')
    ids.add(task.id)
    projectPath(projectRoot, task.manifestPath)
  }
  const keys = value.configs.map((config) => isRecord(config) ? config.key : undefined).sort()
  assert.deepStrictEqual(keys, [...CONFIG_KEYS])
  for (const config of value.configs) {
    if (!isRecord(config) || !CONFIG_KEYS.includes(config.key as ConfigKey) ||
      typeof config.path !== 'string' || !isSha256(config.sha256)) {
      throw new Error('Invalid frozen config')
    }
    projectPath(projectRoot, config.path)
  }
  assert.deepStrictEqual(value.comparisons, [
    { left: 'A', right: 'B' },
    { left: 'B', right: 'C' },
  ])
  assert.deepStrictEqual(value.metrics, [...METRICS])
  return value as FrozenExperimentPlan
}

async function gitState(projectRoot: string): Promise<{ sha: string; dirty: string[] }> {
  const [sha, status] = await Promise.all([
    execFileAsync('git', ['rev-parse', 'HEAD'], { cwd: projectRoot }),
    execFileAsync('git', ['status', '--porcelain=v1', '--untracked-files=all'], { cwd: projectRoot }),
  ])
  return {
    sha: sha.stdout.trim(),
    dirty: status.stdout.split('\n').filter(Boolean).map((line) => line.slice(3)),
  }
}

function isWithin(target: string, allowed: string): boolean {
  return target === allowed || target.startsWith(`${allowed}${path.sep}`)
}

async function assertRepositoryState(options: {
  projectRoot: string
  expectedSha?: string
  allowedDirty?: string[]
}): Promise<string> {
  const state = await gitState(options.projectRoot)
  if (options.expectedSha && state.sha !== options.expectedSha) throw new Error('Git SHA changed')
  const allowed = (options.allowedDirty ?? []).map((item) => path.resolve(item))
  const unexpected = state.dirty.filter((relative) => {
    const absolute = path.resolve(options.projectRoot, relative)
    return !allowed.some((entry) => isWithin(absolute, entry))
  })
  if (unexpected.length > 0) throw new Error(`Dirty worktree: ${unexpected.join(', ')}`)
  return state.sha
}

export async function verifyFrozenEnvironment(options: {
  projectRoot: string
  plan: FrozenExperimentPlan
  allowedDirty: string[]
}): Promise<void> {
  await assertRepositoryState({
    projectRoot: options.projectRoot,
    expectedSha: options.plan.repository.gitSha,
    allowedDirty: options.allowedDirty,
  })
  const pricingRaw = await readFile(
    projectPath(options.projectRoot, options.plan.repository.pricingSnapshotPath),
    'utf8',
  )
  if (sha256(pricingRaw) !== options.plan.repository.pricingSnapshotSha256) {
    throw new Error('Pricing snapshot changed')
  }
}

export async function prepareExperiment(options: {
  projectRoot: string
  outputPath: string
  repetitions: number
  seed: number
  maxExperimentUsd: number
  now?: () => Date
}): Promise<FrozenExperimentPlan> {
  if (!Number.isSafeInteger(options.repetitions) || options.repetitions < 2) {
    throw new Error('repetitions must be an integer >= 2')
  }
  if (!Number.isFinite(options.maxExperimentUsd) || options.maxExperimentUsd <= 0) {
    throw new Error('maxExperimentUsd must be positive')
  }
  const gitSha = await assertRepositoryState({ projectRoot: options.projectRoot })
  projectPath(options.projectRoot, path.relative(options.projectRoot, options.outputPath))
  const taskDirectory = path.join(options.projectRoot, 'eval', 'tasks')
  const manifestPaths = (await readdir(taskDirectory))
    .filter((name) => name.endsWith('.json'))
    .sort(ascii)
    .map((name) => path.join(taskDirectory, name))
  const tasks = []
  for (const manifestPath of manifestPaths) {
    const loaded = await loadTask({
      manifestPath,
      controlledRoots: [
        path.join(options.projectRoot, 'practice'),
        path.join(options.projectRoot, 'eval', 'fixtures'),
      ],
    })
    tasks.push({
      id: loaded.manifest.id,
      taskVersion: loaded.manifest.taskVersion,
      stratum: loaded.manifest.stratum,
      manifestPath: path.relative(options.projectRoot, manifestPath),
      manifestSha256: loaded.manifestSha256,
      fixtureSha256: loaded.fixtureSha256,
    })
  }
  if (new Set(tasks.map((task) => task.id)).size !== tasks.length) {
    throw new Error('task ids must be unique')
  }
  if (new Set(tasks.map((task) => task.stratum)).size !== 3) {
    throw new Error('task set must contain long-context, multi-step, and general strata')
  }

  const configPaths: Record<ConfigKey, string> = {
    A: 'eval/configs/A-no-compaction.json',
    B: 'eval/configs/B-compaction.json',
    C: 'eval/configs/C-compaction-todo.json',
  }
  const configs = {} as Record<ConfigKey, EvalConfig>
  const frozenConfigs: FrozenExperimentPlan['configs'] = []
  for (const key of ['A', 'B', 'C'] as const) {
    const raw = await readFile(path.join(options.projectRoot, configPaths[key]), 'utf8')
    configs[key] = parseEvalConfig(JSON.parse(raw))
    frozenConfigs.push({ key, path: configPaths[key], sha256: sha256(raw) })
  }
  assertIncrementalAblation(configs)

  const pricingSnapshotPath = configs.A.pricingSnapshot
  const pricingRaw = await readFile(projectPath(options.projectRoot, pricingSnapshotPath), 'utf8')
  const worstCaseUsd = tasks.length * options.repetitions * CONFIG_KEYS.reduce(
    (sum, key) => sum + configs[key].maxUsd,
    0,
  )
  if (worstCaseUsd > options.maxExperimentUsd) {
    throw new Error(
      `Worst-case $${worstCaseUsd.toFixed(2)} exceeds experiment cap ` +
      `$${options.maxExperimentUsd.toFixed(2)}`,
    )
  }

  const plan: FrozenExperimentPlan = {
    schemaVersion: 1,
    planId: `ablation-v1-${gitSha.slice(0, 12)}-${String(options.seed)}`,
    createdAt: (options.now?.() ?? new Date()).toISOString(),
    repetitions: options.repetitions,
    seed: options.seed,
    maxExperimentUsd: options.maxExperimentUsd,
    worstCaseUsd,
    repository: {
      gitSha,
      pricingSnapshotPath,
      pricingSnapshotSha256: sha256(pricingRaw),
    },
    tasks,
    configs: frozenConfigs,
    comparisons: [
      { left: 'A', right: 'B' },
      { left: 'B', right: 'C' },
    ],
    metrics: [
      'pass_rate_wilson_95',
      'settled_tokens_median_iqr',
      'usd_median_iqr',
      'paired_win_loss_tie',
    ],
  }
  await mkdir(path.dirname(options.outputPath), { recursive: true })
  await writeFile(
    options.outputPath,
    `${JSON.stringify(plan, null, 2)}\n`,
    { flag: 'wx' },
  )
  return plan
}

export async function verifyFrozenPlan(
  projectRoot: string,
  plan: FrozenExperimentPlan,
  allowedDirty: string[],
): Promise<Record<ConfigKey, { config: EvalConfig; raw: string }>> {
  await verifyFrozenEnvironment({ projectRoot, plan, allowedDirty })
  const configs = {} as Record<ConfigKey, { config: EvalConfig; raw: string }>
  for (const frozen of plan.configs) {
    const raw = await readFile(path.join(projectRoot, frozen.path), 'utf8')
    if (sha256(raw) !== frozen.sha256) throw new Error(`Config changed: ${frozen.key}`)
    configs[frozen.key] = { config: parseEvalConfig(JSON.parse(raw)), raw }
  }
  assertIncrementalAblation({
    A: configs.A.config,
    B: configs.B.config,
    C: configs.C.config,
  })
  const expectedWorstCase = plan.tasks.length * plan.repetitions * CONFIG_KEYS.reduce(
    (sum, key) => sum + configs[key].config.maxUsd,
    0,
  )
  if (expectedWorstCase !== plan.worstCaseUsd || expectedWorstCase > plan.maxExperimentUsd) {
    throw new Error('Frozen experiment budget no longer matches configs')
  }
  for (const frozen of plan.tasks) {
    const loaded = await loadTask({
      manifestPath: path.join(projectRoot, frozen.manifestPath),
      controlledRoots: [
        path.join(projectRoot, 'practice'),
        path.join(projectRoot, 'eval', 'fixtures'),
      ],
    })
    if (
      loaded.manifest.id !== frozen.id ||
      loaded.manifest.taskVersion !== frozen.taskVersion ||
      loaded.manifestSha256 !== frozen.manifestSha256 ||
      loaded.fixtureSha256 !== frozen.fixtureSha256
    ) {
      throw new Error(`Task changed after freeze: ${frozen.id}`)
    }
  }
  return configs
}

export function planHash(raw: string): string {
  return sha256(raw)
}

prepareExperiment 的输出用 flag: 'wx' 写入,所以已经存在的 plan 不会被“重新生成”覆盖。它的预算检查分两步:

  1. 准备时,先算 task × repetition × 三配置 maxUsd 的最坏成本。超过 maxExperimentUsd 就拒绝准备。
  2. 运行时,在每个 attempt 开始前,按已结算的成本检查,到了就停。

和单次 attempt 一样,这仍然是 soft cap,最多可能超出一个正在结算的 attempt。

要换任务、oracle、重复次数或指标,必须新建 plan ID。这是防止“看到红之后偷偷改考卷”的最简单办法。

新建 eval/experiment-cli.ts。它复用第 21 章的 runAttempt。createRuntime(config) 只是把第 21 章 eval/cli.ts 里的三样东西原样移到 eval/runtime.ts 并导出:Anthropic client、精确 model 的 token counter、Tool factory。runAgent 不变:

import { mkdir, readFile, writeFile } from 'node:fs/promises'
import path from 'node:path'
import { createRuntime } from './runtime.js'
import {
  buildSchedule,
  parseFrozenPlan,
  planHash,
  verifyFrozenEnvironment,
  verifyFrozenPlan,
  type ExperimentRecord,
} from './experiment.js'
import { runAttempt } from './run-attempt.js'

const projectRoot = process.cwd()
if (!process.argv[2]) throw new Error('Usage: npm run experiment -- <plan.json>')
const planPath = path.resolve(projectRoot, process.argv[2])
if (!planPath.startsWith(`${projectRoot}${path.sep}`)) throw new Error('Plan must be inside project')
const raw = await readFile(planPath, 'utf8')
const plan = parseFrozenPlan(JSON.parse(raw), projectRoot)
const runId = `${plan.planId}-${new Date().toISOString().replace(/[-:.]/g, '')}`
const outputDirectory = path.join(projectRoot, 'eval', 'runs', runId)
const configs = await verifyFrozenPlan(projectRoot, plan, [planPath])
await mkdir(outputDirectory, { recursive: false })
await writeFile(
  path.join(outputDirectory, 'experiment-plan.json'),
  raw,
  { flag: 'wx' },
)

const controller = new AbortController()
process.once('SIGINT', () => controller.abort(new Error('Experiment cancelled')))
const runtimes = {
  A: createRuntime(configs.A.config),
  B: createRuntime(configs.B.config),
  C: createRuntime(configs.C.config),
}
const experiment: ExperimentRecord = {
  schemaVersion: 1,
  plan,
  planSha256: planHash(raw),
  status: 'running',
  attempts: [],
  settledCostUsd: 0,
}
const save = async () => writeFile(
  path.join(outputDirectory, 'experiment.json'),
  `${JSON.stringify(experiment, null, 2)}\n`,
)
await save()

let thrown: unknown
try {
  for (const scheduled of buildSchedule(plan)) {
    if (experiment.settledCostUsd >= plan.maxExperimentUsd) {
      experiment.status = 'budget_exceeded'
      break
    }
    await verifyFrozenEnvironment({
      projectRoot,
      plan,
      allowedDirty: [planPath, outputDirectory],
    })
    const selected = configs[scheduled.configKey]
    const record = await runAttempt({
      projectRoot,
      manifestPath: path.join(
        projectRoot,
        plan.tasks.find((task) => task.id === scheduled.taskId)!.manifestPath,
      ),
      config: selected.config,
      configRaw: selected.raw,
      attemptId: scheduled.attemptId,
      outputDirectory,
      signal: controller.signal,
      dependencies: runtimes[scheduled.configKey].dependencies,
    })
    experiment.attempts.push({ ...scheduled, record })
    experiment.settledCostUsd += record.estimatedCostUsd
    await save()
    if (controller.signal.aborted) break
  }
  if (experiment.status === 'running') {
    experiment.status = controller.signal.aborted
      ? 'aborted'
      : experiment.settledCostUsd > plan.maxExperimentUsd
        ? 'budget_exceeded'
        : 'complete'
  }
  await save()
} catch (error) {
  experiment.status = 'infra_error'
  experiment.error = error instanceof Error ? error.stack ?? error.message : String(error)
  await save()
  thrown = error
}
try {
  await Promise.all(Object.values(runtimes).map((runtime) => runtime.close()))
} catch (error) {
  experiment.status = 'infra_error'
  experiment.error = error instanceof Error ? error.stack ?? error.message : String(error)
  await save()
  thrown ??= error
}
if (thrown) throw thrown

eval/runtime.ts 不读 .byoaa-mcp.json,标准消融实验(逐个打开或关闭功能,看结果怎么变)只比较 compaction / Todo。它完整复用上一章 CLI 里的 Tool 组装。唯一重要的变化是:Task Tool 接收的是 attempt 那个带记录的 callModel:

import Anthropic from '@anthropic-ai/sdk'
import {
  createAnthropicCountInputTokens,
} from '../src/model.js'
import { createSessionState } from '../src/session.js'
import { createReadOnlyTools, createTaskTool } from '../src/task-tool.js'
import { createTodoWriteTool, tools as localTools } from '../src/tools.js'
import type { EvalConfig } from './types.js'

export function createRuntime(config: EvalConfig) {
  const client = new Anthropic({
    apiKey: process.env.ANTHROPIC_API_KEY,
    maxRetries: 0,
  })
  const countInputTokens = createAnthropicCountInputTokens({
    client,
    model: config.model,
  })
  return {
    dependencies: {
      client,
      countInputTokens,
      async createTools(options: {
        features: EvalConfig['features']
        callModel: Parameters<typeof createTaskTool>[0]['callModel']
      }) {
        const state = createSessionState()
        const task = createTaskTool({
          callModel: options.callModel,
          countInputTokens,
          readOnlyTools: createReadOnlyTools(localTools),
          maxTurns: 6,
          maxTasks: 2,
        })
        return {
          tools: [
            ...localTools,
            ...(options.features.todo ? [createTodoWriteTool(state)] : []),
            task,
          ],
          async close() {},
        }
      },
    },
    async close() {},
  }
}

新建 eval/report.ts。状态分两类处理:

  • 进入通过率分母:pass / fail / timeout / budget_exceeded。
  • 单独列出:infra_error / invalid_task / aborted。它们不算 agent 失败,但也不能从全量 CSV 里消失。
import assert from 'node:assert/strict'
import { readFile, writeFile } from 'node:fs/promises'
import path from 'node:path'
import { sha256 } from './manifest.js'
import type {
  ConfigKey,
  ExperimentAttempt,
  ExperimentRecord,
} from './experiment.js'

const CAPABILITY_STATUSES = new Set([
  'pass', 'fail', 'timeout', 'budget_exceeded',
])

function settledTokens(attempt: ExperimentAttempt): number {
  const usage = attempt.record.usage
  return usage.inputTokens + usage.outputTokens +
    usage.cacheReadInputTokens + usage.cacheCreationInputTokens
}

// 合并成一个 input 总数会把「缓存热度」藏起来:同一份能力换个执行顺序
// 成本就不同,而读者看不出差别来自 cache 而不是 agent。
function cacheReadTokens(attempt: ExperimentAttempt): number {
  return attempt.record.usage.cacheReadInputTokens
}

function cacheCreationTokens(attempt: ExperimentAttempt): number {
  return attempt.record.usage.cacheCreationInputTokens
}

function quantile(values: number[], probability: number): number | null {
  if (values.length === 0) return null
  const sorted = [...values].sort((a, b) => a - b)
  const position = (sorted.length - 1) * probability
  const lower = Math.floor(position)
  const upper = Math.ceil(position)
  const fraction = position - lower
  return sorted[lower] + (sorted[upper] - sorted[lower]) * fraction
}

export function wilson95(passes: number, total: number): [number, number] | null {
  if (total === 0) return null
  const z = 1.959963984540054
  const observed = passes / total
  const denominator = 1 + (z * z) / total
  const center = (observed + (z * z) / (2 * total)) / denominator
  const margin = z * Math.sqrt(
    (observed * (1 - observed) / total) +
    (z * z) / (4 * total * total),
  ) / denominator
  return [Math.max(0, center - margin), Math.min(1, center + margin)]
}

function summarize(attempts: ExperimentAttempt[]) {
  const eligible = attempts.filter((attempt) =>
    CAPABILITY_STATUSES.has(attempt.record.status),
  )
  const passes = eligible.filter((attempt) => attempt.record.status === 'pass').length
  const tokens = eligible.map(settledTokens)
  const cacheRead = eligible.map(cacheReadTokens)
  const cacheCreation = eligible.map(cacheCreationTokens)
  const costs = eligible.map((attempt) => attempt.record.estimatedCostUsd)
  return {
    attempts: attempts.length,
    eligible: eligible.length,
    passes,
    passRate: eligible.length === 0 ? null : passes / eligible.length,
    interval95: wilson95(passes, eligible.length),
    tokens: {
      q1: quantile(tokens, 0.25),
      median: quantile(tokens, 0.5),
      q3: quantile(tokens, 0.75),
    },
    cacheReadTokens: { median: quantile(cacheRead, 0.5) },
    cacheCreationTokens: { median: quantile(cacheCreation, 0.5) },
    usd: {
      q1: quantile(costs, 0.25),
      median: quantile(costs, 0.5),
      q3: quantile(costs, 0.75),
    },
    excluded: attempts.length - eligible.length,
  }
}

function paired(
  attempts: ExperimentAttempt[],
  left: ConfigKey,
  right: ConfigKey,
) {
  const byPair = new Map<string, Partial<Record<ConfigKey, ExperimentAttempt>>>()
  for (const attempt of attempts) {
    const entry = byPair.get(attempt.pairId) ?? {}
    if (entry[attempt.configKey]) {
      throw new Error(`Duplicate ${attempt.configKey} in pair ${attempt.pairId}`)
    }
    entry[attempt.configKey] = attempt
    byPair.set(attempt.pairId, entry)
  }
  let wins = 0
  let losses = 0
  let ties = 0
  let eligiblePairs = 0
  let excludedPairs = 0
  const tokenDelta: number[] = []
  const usdDelta: number[] = []
  for (const pair of byPair.values()) {
    const a = pair[left]
    const b = pair[right]
    if (!a || !b ||
      !CAPABILITY_STATUSES.has(a.record.status) ||
      !CAPABILITY_STATUSES.has(b.record.status)) {
      excludedPairs += 1
      continue
    }
    eligiblePairs += 1
    const leftPass = a.record.status === 'pass'
    const rightPass = b.record.status === 'pass'
    if (!leftPass && rightPass) wins += 1
    else if (leftPass && !rightPass) losses += 1
    else ties += 1
    tokenDelta.push(settledTokens(b) - settledTokens(a))
    usdDelta.push(b.record.estimatedCostUsd - a.record.estimatedCostUsd)
  }
  return {
    left, right, wins, losses, ties, eligiblePairs, excludedPairs,
    medianTokenDelta: quantile(tokenDelta, 0.5),
    medianUsdDelta: quantile(usdDelta, 0.5),
  }
}

function csvCell(value: unknown): string {
  return `"${String(value).replaceAll('"', '""')}"`
}

function show(value: number | null, digits = 3): string {
  return value === null ? 'n/a' : value.toFixed(digits)
}

function markdownSummary(
  planId: string,
  status: ExperimentRecord['status'],
  attempts: { completed: number; planned: number },
  groups: Array<ReturnType<typeof summarize> & { configKey: ConfigKey; stratum: string }>,
  comparisons: Array<ReturnType<typeof paired> & { stratum: string }>,
): string {
  const lines = [
    `# Experiment ${planId}`,
    '',
    `Status: ${status}; attempts: ${attempts.completed}/${attempts.planned}.`,
    '',
    '| config | stratum | pass / eligible | 95% interval | token IQR | USD IQR | excluded |',
    '|---|---|---:|---:|---:|---:|---:|',
    ...groups.map((group) => {
      const interval = group.interval95
      return `| ${group.configKey} | ${group.stratum} | ${group.passes}/${group.eligible} | ` +
        `${interval ? `${show(interval[0])}–${show(interval[1])}` : 'n/a'} | ` +
        `${show(group.tokens.q1, 0)}–${show(group.tokens.q3, 0)} | ` +
        `${show(group.usd.q1)}–${show(group.usd.q3)} | ${group.excluded} |`
    }),
    '',
    '| comparison | stratum | win / loss / tie | eligible / excluded | median Δtoken | median ΔUSD |',
    '|---|---|---:|---:|---:|---:|',
    ...comparisons.map((item) =>
      `| ${item.left}→${item.right} | ${item.stratum} | ${item.wins}/${item.losses}/${item.ties} | ` +
      `${item.eligiblePairs}/${item.excludedPairs} | ${show(item.medianTokenDelta, 0)} | ` +
      `${show(item.medianUsdDelta)} |`,
    ),
    '',
    '> 方向不预设;必须结合区间、配对转换和成本分布解释。',
    '',
  ]
  return lines.join('\n')
}

export async function writeReport(experimentPath: string): Promise<void> {
  const raw = await readFile(experimentPath, 'utf8')
  const experiment = JSON.parse(raw) as ExperimentRecord
  if (experiment.status === 'running') throw new Error('Experiment is still running')
  const directory = path.dirname(experimentPath)
  const planRaw = await readFile(path.join(directory, 'experiment-plan.json'), 'utf8')
  assert.equal(sha256(planRaw), experiment.planSha256, 'Frozen plan hash changed')
  assert.deepStrictEqual(JSON.parse(planRaw), experiment.plan)
  const groups = []
  for (const configKey of ['A', 'B', 'C'] as const) {
    const selected = experiment.attempts.filter((item) => item.configKey === configKey)
    groups.push({ configKey, stratum: 'all', ...summarize(selected) })
    for (const stratum of ['long-context', 'multi-step', 'general'] as const) {
      groups.push({
        configKey,
        stratum,
        ...summarize(selected.filter((item) => item.taskStratum === stratum)),
      })
    }
  }
  const comparisons = experiment.plan.comparisons.flatMap(({ left, right }) => [
    { stratum: 'all', ...paired(experiment.attempts, left, right) },
    ...(['long-context', 'multi-step', 'general'] as const).map((stratum) => ({
      stratum,
      ...paired(
        experiment.attempts.filter((item) => item.taskStratum === stratum),
        left,
        right,
      ),
    })),
  ])
  const csv = [
    ['pair_id', 'task', 'stratum', 'repetition', 'config', 'status', 'tokens', 'usd'],
    ...experiment.attempts.map((item) => [
      item.pairId,
      item.taskId,
      item.taskStratum,
      item.repetition,
      item.configKey,
      item.record.status,
      settledTokens(item),
      item.record.estimatedCostUsd,
    ]),
  ].map((row) => row.map(csvCell).join(',')).join('\n') + '\n'
  const summary = {
    planId: experiment.plan.planId,
    status: experiment.status,
    completedAttempts: experiment.attempts.length,
    plannedAttempts:
      experiment.plan.tasks.length * experiment.plan.repetitions * CONFIG_KEYS.length,
    groups,
    comparisons,
    interpretation: 'Outcome direction is not predeclared; inspect intervals, paired transitions, and cost together.',
  }
  await Promise.all([
    writeFile(path.join(directory, 'attempts.csv'), csv),
    writeFile(path.join(directory, 'summary.json'), `${JSON.stringify(summary, null, 2)}\n`),
    writeFile(path.join(directory, 'summary.md'), markdownSummary(
      experiment.plan.planId,
      experiment.status,
      {
        completed: summary.completedAttempts,
        planned: summary.plannedAttempts,
      },
      groups,
      comparisons,
    )),
  ])
}

summary.json 是给机器查的版本。summary.md 由同一个对象渲染出来,不手抄数字。

用 JSON 报告查看缓存读取和写入的分项统计。

表里每一行必须同时有这些内容:

  • pass/eligible
  • 95% 区间
  • token IQR
  • USD IQR
  • cache read / creation 中位数
  • excluded 数

cache 这两列,对应的是第 21 章那条要求。稳定的前缀在 attempt 之间可以命中,命不命中取决于执行顺序和 TTL。如果合成一个 input 总数,缓存冷热就会看起来像能力差异。

读这些区间时,要注意几点:

  • Wilson 区间这里只描述这组固定 task 上 attempt 的通过率。同一个 task 的重复不是严格独立的,更不能把区间推广到没见过的任务。
  • 这些单组区间不是配对差异的检验。不能只看区间重叠还是分开,就判断差异成不成立,更不能据此证明两份配置等价。
  • 分层之后,每一格的样本更少,区间更宽。所以分层表必须和 overall 一起给出。
  • 某个配置通过率更高、但成本翻倍时,报告只陈述这两方面的事实。值不值得,由任务目标来解释,不能自动认定它“更好”。

六项跨 Part 的证据用固定 ID 汇总。新建 eval/evidence.ts,它只负责三件事:

  1. 校验清单的形状。
  2. 确认文件在项目内、真实存在。
  3. 保存两边的 hash。

它不理解每种 artifact 的含义,所以替代不了原章节的验收脚本和人工 review:

import { readFile, writeFile } from 'node:fs/promises'
import path from 'node:path'
import { sha256 } from './manifest.js'

const REQUIRED = [
  'part3-cache-hit',
  'part3-compaction-dual-needle',
  'part3-pricing-real-usage',
  'part5-sdk-v2-typecheck',
  'part5-skills-live-run',
  'part5-mcp-e2e',
] as const

export type EvidenceInput = {
  id: typeof REQUIRED[number]
  sourcePart: 3 | 5
  sourceArtifact: string
  unifiedArtifact: string
}

function artifactPath(projectRoot: string, file: string): string {
  const root = path.resolve(projectRoot)
  const absolute = path.resolve(root, file)
  const relative = path.relative(root, absolute)
  if (relative === '' || relative.startsWith('..') || path.isAbsolute(relative)) {
    throw new Error(`Evidence path escapes project: ${file}`)
  }
  return absolute
}

export async function freezeEvidence(options: {
  projectRoot: string
  inputs: EvidenceInput[]
  outputPath: string
  now?: () => Date
}): Promise<void> {
  if (options.inputs.length !== REQUIRED.length) {
    throw new Error(`Expected exactly ${REQUIRED.length} evidence entries`)
  }
  const byId = new Map(options.inputs.map((item) => [item.id, item]))
  if (byId.size !== REQUIRED.length) throw new Error('Duplicate evidence id')
  const frozen = []
  for (const id of REQUIRED) {
    const input = byId.get(id)
    if (!input) throw new Error(`Missing evidence: ${id}`)
    const expectedPart = id.startsWith('part3-') ? 3 : 5
    if (input.sourcePart !== expectedPart) {
      throw new Error(`Wrong source Part for ${id}`)
    }
    const [source, unified] = await Promise.all([
      readFile(artifactPath(options.projectRoot, input.sourceArtifact)),
      readFile(artifactPath(options.projectRoot, input.unifiedArtifact)),
    ])
    frozen.push({
      ...input,
      sourceSha256: sha256(source),
      unifiedSha256: sha256(unified),
    })
  }
  await writeFile(artifactPath(options.projectRoot, options.outputPath), `${JSON.stringify({
    schemaVersion: 1,
    frozenAt: (options.now?.() ?? new Date()).toISOString(),
    evidence: frozen,
  }, null, 2)}\n`, { flag: 'wx' })
}

这个函数不能把 pending 自动改成 verified。文件存在、hash 稳定,只能证明引用没有变。reviewer 仍然要核对两点:

  • source 是不是通过了原 Part 的验收。
  • unified 是不是真的来自指定的 harness / CI。

审核通过后,才提交 index。不能让“有两个文件”冒充“能力已实测”。SDK typecheck 这类不涉及模型的证据,不混进 A / B / C 的成功率,只在 evidence index 里引用对应的 CI artifact。

最后加入脚本:

{
  "scripts": {
    "experiment:prepare": "tsx eval/prepare-experiment-cli.ts",
    "experiment": "tsx eval/experiment-cli.ts",
    "experiment:report": "tsx eval/report-cli.ts",
    "evidence:freeze": "tsx eval/evidence-cli.ts"
  }
}

两个 wrapper 只负责检查参数,不包含实验逻辑:

import path from 'node:path'
import { prepareExperiment } from './experiment.js'

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

const projectRoot = process.cwd()
const outputPath = path.resolve(projectRoot, flag('--out'))
if (!outputPath.startsWith(`${projectRoot}${path.sep}`)) throw new Error('--out escapes project')
await prepareExperiment({
  projectRoot,
  outputPath,
  repetitions: Number(flag('--repetitions')),
  seed: Number(flag('--seed')),
  maxExperimentUsd: Number(flag('--max-usd')),
})
import path from 'node:path'
import { writeReport } from './report.js'

const projectRoot = process.cwd()
if (!process.argv[2]) throw new Error('Usage: npm run experiment:report -- <experiment.json>')
const experimentPath = path.resolve(projectRoot, process.argv[2])
if (!experimentPath.startsWith(`${projectRoot}${path.sep}`)) {
  throw new Error('Experiment path escapes project')
}
await writeReport(experimentPath)

证据清单也用一个很薄的 wrapper,输入是 EvidenceInput[] 的 JSON。运行时的校验仍然在 freezeEvidence 里做,不能靠 TypeScript cast 就信任外部文件:

import { readFile } from 'node:fs/promises'
import path from 'node:path'
import { freezeEvidence, type EvidenceInput } from './evidence.js'

const projectRoot = process.cwd()
const input = process.argv[2]
const output = process.argv[3]
if (!input || !output) {
  throw new Error('Usage: npm run evidence:freeze -- <inputs.json> <index.json>')
}
const raw = JSON.parse(await readFile(path.resolve(projectRoot, input), 'utf8'))
if (!Array.isArray(raw)) throw new Error('Evidence input must be an array')
await freezeEvidence({
  projectRoot,
  inputs: raw as EvidenceInput[],
  outputPath: output,
})

自动化测试与真实验收

新建 eval/experiment.test.ts:

import assert from 'node:assert/strict'
import test from 'node:test'
import {
  assertIncrementalAblation,
  buildSchedule,
  parseFrozenPlan,
  type FrozenExperimentPlan,
} from './experiment.js'
import { wilson95 } from './report.js'
import type { EvalConfig } from './types.js'

function configs(): Record<'A' | 'B' | 'C', EvalConfig> {
  const base = {
    schemaVersion: 1 as const,
    model: 'fixed-model',
    maxTurns: 12,
    maxTokensPerRequest: 1024,
    timeoutMs: 60_000,
    maxSettledTokens: 100_000,
    maxUsd: 1,
    approvalPolicy: 'allow_all_recorded' as const,
    pricingSnapshot: 'pricing.json',
  }
  return {
    A: { ...base, name: 'A', features: { compaction: false, todo: false } },
    B: { ...base, name: 'B', features: { compaction: true, todo: false } },
    C: { ...base, name: 'C', features: { compaction: true, todo: true } },
  }
}

const plan: FrozenExperimentPlan = {
  schemaVersion: 1,
  planId: 'test',
  createdAt: '2026-08-25T00:00:00.000Z',
  repetitions: 3,
  seed: 42,
  maxExperimentUsd: 9,
  worstCaseUsd: 9,
  repository: {
    gitSha: 'a'.repeat(40),
    pricingSnapshotPath: 'pricing.json',
    pricingSnapshotSha256: 'a'.repeat(64),
  },
  tasks: [
    {
      id: 'long', taskVersion: '1', stratum: 'long-context',
      manifestPath: 'long.json',
      manifestSha256: 'a'.repeat(64), fixtureSha256: 'b'.repeat(64),
    },
  ],
  configs: [
    { key: 'A', path: 'A.json', sha256: 'a'.repeat(64) },
    { key: 'B', path: 'B.json', sha256: 'b'.repeat(64) },
    { key: 'C', path: 'C.json', sha256: 'c'.repeat(64) },
  ],
  comparisons: [{ left: 'A', right: 'B' }, { left: 'B', right: 'C' }],
  metrics: [
    'pass_rate_wilson_95',
    'settled_tokens_median_iqr',
    'usd_median_iqr',
    'paired_win_loss_tie',
  ],
}

test('A B C differ only by incremental features', () => {
  assert.doesNotThrow(() => assertIncrementalAblation(configs()))
  const changed = configs()
  changed.C.maxTurns = 99
  assert.throws(() => assertIncrementalAblation(changed))
})

test('schedule is seeded, paired, and complete', () => {
  const first = buildSchedule(plan)
  const second = buildSchedule(plan)
  assert.deepEqual(first, second)
  assert.equal(first.length, 9)
  for (const repetition of [1, 2, 3]) {
    const block = first.filter((item) => item.repetition === repetition)
    assert.deepEqual(
      block.map((item) => item.configKey).sort(),
      ['A', 'B', 'C'],
    )
  }
})

test('Wilson interval remains bounded and does not collapse at small n', () => {
  const interval = wilson95(8, 10)
  assert.ok(interval)
  const [low, high] = interval
  assert.ok(low > 0 && low < 0.8)
  assert.ok(high > 0.8 && high < 1)
  assert.equal(wilson95(0, 0), null)
})

test('plan parser rejects duplicate task ids and escaping paths', () => {
  assert.doesNotThrow(() => parseFrozenPlan(plan, process.cwd()))
  assert.throws(() => parseFrozenPlan({
    ...plan,
    tasks: [plan.tasks[0], { ...plan.tasks[0], manifestPath: '../outside.json' }],
  }, process.cwd()))
})

另外用临时文件 fixture 覆盖三条失败路径:

  • 冻结后改一个 oracle 字符,verifyFrozenPlan 必须在调用模型之前失败。
  • 已有的 plan / run 目录,拒绝覆盖。
  • writeReport 写出的 CSV 行数,必须等于全部 attempt 数加一行 header,其中包含 infra_error 和 invalid_task。

运行一轮小规模对照

在干净的参考实现 checkout 中,从 code/ 目录生成计划。执行计划会调用真实模型,需要配置 API key。

npm run experiment:prepare -- --repetitions 2 --seed 42 --max-usd 5 --out eval/runs/plan.json
npm run experiment -- eval/runs/plan.json
npm run experiment:report -- eval/runs/<run-id>/experiment.json

把最后一行的 <run-id> 替换为运行输出中的目录名。预算用来决定何时停止启动新尝试,已经发出的模型请求仍可能产生费用。结果包含通过、失败、超时、预算耗尽和基础设施错误等状态,统计时保留这些分类。

一次实测的结果

三项受控任务各重复两次,A、B、C 各运行六次,模型为 Haiku 4.5。A 通过 6 次,B 和 C 各通过 4 次。四次失败都发生在长上下文任务:低阈值触发压缩后,模型反复重读相同的三页文件,最后用完累计 token 预算。按运行时保存的价格估算,18 次尝试合计约 1.06 美元。

这个实验刻意压低了 compaction 的触发线。样本只覆盖三项任务,结果说明了该配置下的重读和成本问题。要判断日常阈值下的影响,需要用相同任务和判分器另跑一轮。