Datasets:
Add professional benchmark suite
Browse filesFiles changed (16)
- README.mdAdded+41
- cli.tsAdded+163
- config/defaults.tsAdded+40
- fixtures/headless-offline.stream.jsonlAdded+4
- fixtures/headless-offline.txtAdded+1
- harness/process.tsAdded+66
- harness/runner.tsAdded+75
- observability/adapters.tsAdded+68
- reporting/report.tsAdded+167
- scenarios/correctnessTools.tsAdded+168
- scenarios/headless.tsAdded+201
- scenarios/restoration.tsAdded+48
- scenarios/startupCommand.tsAdded+199
- types.tsAdded+126
- utils/files.tsAdded+17
- utils/stats.tsAdded+30
1234567891011121314151617181920212223242526272829303132333435363738394041# Benchmark Suite / 基准测试套件
Professional benchmark harness for this restored Claude Code repository.
面向本还原版 Claude Code 仓库的专业级 Benchmark 框架。
## Commands / 命令
- `bun run bench:smoke` - quick hybrid pass for local validation
快速混合模式验证(本地冒烟)
- `bun run bench:full` - full hybrid suite
完整混合模式基准
- `bun run bench:offline` - deterministic offline-only run
仅离线可复现模式
- `bun run bench:online-sample` - online-only sampled run (requires credentials)
仅在线抽样模式(需要凭据)
- `bun run bench:compare --baseline=<path> --current=<path>` - compare two JSON reports
对比两份 JSON 报告
## Scenario Mapping / 场景映射
- `B01` version fast path / 版本快路径
- `B02` startup phase profiling / 启动分段剖析
- `B03` bare-mode delta / bare 模式差分
- `B04` command catalog load / 命令目录加载
- `B05` headless single round (offline fixture + online sample) / 无头单轮(离线夹具 + 在线抽检)
- `B06` headless streaming format and timing checks / 无头流式格式与时延检查
- `B07` slash/queue batching correctness / 斜杠命令与队列批处理正确性
- `B08` tool orchestration pipeline behavior / 工具编排流水线行为
- `B09` restoration health gate via `dev-entry` / 通过 `dev-entry` 的恢复健康门禁
## Outputs / 输出
Reports are written to `benchmark/results/`.
报告会写入 `benchmark/results/` 目录:
- `benchmark-<run>-<timestamp>.json`
- `latest.json`
- `latest-summary.md`
- `comparison.md` (when running compare / 运行 compare 时生成)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163import { mkdir } from 'node:fs/promises'
import { basename, isAbsolute, join, resolve } from 'node:path'
import { createConfig } from './config/defaults.js'
import { runScenarios } from './harness/runner.js'
import {
collectBootstrapObservability,
collectProcessObservability,
} from './observability/adapters.js'
import {
buildBenchmarkReport,
buildComparisonText,
} from './reporting/report.js'
import { createCorrectnessAndToolScenarios } from './scenarios/correctnessTools.js'
import { createHeadlessScenarios } from './scenarios/headless.js'
import { createRestorationScenario } from './scenarios/restoration.js'
import { createStartupAndCommandScenarios } from './scenarios/startupCommand.js'
import type { BenchmarkMode, BenchmarkReport, BenchmarkRunKind } from './types.js'
import { readJsonFile, writeJsonFile, writeTextFile } from './utils/files.js'
function parseArg(name: string): string | undefined {
const hit = process.argv.find(value => value.startsWith(`${name}=`))
if (!hit) return undefined
return hit.slice(name.length + 1)
}
function resolveMode(): BenchmarkMode {
const raw = parseArg('--mode')
if (raw === 'online' || raw === 'offline' || raw === 'hybrid') return raw
return 'hybrid'
}
function resolveRunKind(): BenchmarkRunKind {
const raw = parseArg('--run')
if (raw === 'smoke' || raw === 'full') return raw
return 'smoke'
}
function resolveOutputDir(rootDir: string): string {
const input = parseArg('--out')
if (!input) return join(rootDir, 'benchmark', 'results')
return isAbsolute(input) ? input : resolve(rootDir, input)
}
async function runBench(): Promise<void> {
const rootDir = process.cwd()
const nowIso = new Date().toISOString()
const mode = resolveMode()
const runKind = resolveRunKind()
const config = createConfig(mode, runKind)
const outputDir = resolveOutputDir(rootDir)
await mkdir(outputDir, { recursive: true })
const context = {
rootDir,
mode,
runKind,
nowIso,
outputDir,
}
const scenarios = [
...createStartupAndCommandScenarios(config),
...createHeadlessScenarios(config),
...createCorrectnessAndToolScenarios(config),
createRestorationScenario(config),
]
const summaries = await runScenarios({
scenarios,
context,
config,
})
const report = buildBenchmarkReport({
rootDir,
generatedAt: nowIso,
config,
scenarios: summaries,
observability: {
bootstrapState: collectBootstrapObservability(),
process: collectProcessObservability(),
},
})
const reportPath = join(
outputDir,
`benchmark-${runKind}-${nowIso.replace(/[:.]/gu, '-')}.json`,
)
await writeJsonFile(reportPath, report)
const latestPath = join(outputDir, 'latest.json')
await writeJsonFile(latestPath, report)
await writeTextFile(
join(outputDir, 'latest-summary.md'),
renderSummaryMarkdown(report, basename(reportPath)),
)
process.stdout.write(`Benchmark report written: ${reportPath}\n`)
process.stdout.write(
`Quality gate: ${report.qualityGate.passed ? 'PASS' : 'FAIL'}\n`,
)
if (!report.qualityGate.passed) {
for (const reason of report.qualityGate.reasons) {
process.stdout.write(`- ${reason}\n`)
}
process.exitCode = 1
}
}
function renderSummaryMarkdown(
report: BenchmarkReport,
fileName: string,
): string {
const lines: string[] = []
lines.push('# Benchmark Summary')
lines.push('')
lines.push(`- Report: ${fileName}`)
lines.push(`- Mode: ${report.mode}`)
lines.push(`- Run: ${report.runKind}`)
lines.push(
`- Overall score: ${report.aggregate.score.total.toFixed(2)} (latency ${report.aggregate.score.latency.toFixed(2)}, stability ${report.aggregate.score.stability.toFixed(2)}, quality ${report.aggregate.score.quality.toFixed(2)}, cost ${report.aggregate.score.cost.toFixed(2)})`,
)
lines.push(`- Success rate: ${report.aggregate.successRate.toFixed(2)}%`)
lines.push('')
lines.push('## Scenario Results')
for (const scenario of report.scenarios) {
const p95 = scenario.durationMs?.p95 ?? 0
lines.push(
`- ${scenario.id} ${scenario.name}: success ${scenario.successRate.toFixed(2)}%, p95 ${p95.toFixed(2)}ms`,
)
}
lines.push('')
lines.push(
`- Quality gate: ${report.qualityGate.passed ? 'PASS' : 'FAIL'} (${report.qualityGate.reasons.length} issue(s))`,
)
if (!report.qualityGate.passed) {
for (const reason of report.qualityGate.reasons) {
lines.push(` - ${reason}`)
}
}
lines.push('')
return `${lines.join('\n')}\n`
}
async function runCompare(): Promise<void> {
const rootDir = process.cwd()
const outputDir = resolveOutputDir(rootDir)
const baselinePath = parseArg('--baseline')
const currentPath = parseArg('--current')
if (!baselinePath || !currentPath) {
throw new Error('--baseline and --current are required for compare mode')
}
const baseline = await readJsonFile<BenchmarkReport>(
isAbsolute(baselinePath) ? baselinePath : resolve(rootDir, baselinePath),
)
const current = await readJsonFile<BenchmarkReport>(
isAbsolute(currentPath) ? currentPath : resolve(rootDir, currentPath),
)
const text = buildComparisonText(baseline, current)
const outPath = join(outputDir, 'comparison.md')
await writeTextFile(outPath, text)
process.stdout.write(`Comparison written: ${outPath}\n`)
}
const command = parseArg('--command') ?? 'run'
if (command === 'compare') {
await runCompare()
} else {
await runBench()
}12345678910111213141516171819202122232425262728293031323334353637383940import type { BenchmarkConfig, BenchmarkMode, BenchmarkRunKind } from '../types.js'
export function createConfig(
mode: BenchmarkMode,
runKind: BenchmarkRunKind,
): BenchmarkConfig {
const isSmoke = runKind === 'smoke'
return {
mode,
runKind,
iterations: {
startup: isSmoke ? 2 : 8,
commandLoad: isSmoke ? 3 : 16,
queueCorrectness: isSmoke ? 4 : 24,
toolPipeline: isSmoke ? 3 : 20,
},
timeoutsMs: {
command: isSmoke ? 20_000 : 60_000,
onlineHeadless: isSmoke ? 30_000 : 120_000,
},
weights: {
latency: 0.3,
stability: 0.3,
quality: 0.25,
cost: 0.15,
},
thresholds: {
minimumSuccessRatePct: isSmoke ? 85 : 95,
maximumP95MsByCategory: {
startup: isSmoke ? 20_000 : 8_000,
commands: isSmoke ? 15_000 : 5_000,
headless: isSmoke ? 60_000 : 25_000,
correctness: isSmoke ? 5_000 : 2_000,
tools: isSmoke ? 5_000 : 2_000,
restoration: isSmoke ? 20_000 : 10_000,
},
maximumMissingImports: 0,
},
}
}1234{"type":"session.start","session_id":"offline-bench"}
{"type":"assistant.delta","text":"Hello"}
{"type":"assistant.delta","text":" world"}
{"type":"assistant.final","text":"Hello world","usage":{"input_tokens":8,"output_tokens":3}}1Hello world123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566import { spawn } from 'node:child_process'
export type CommandResult = {
code: number | null
signal: NodeJS.Signals | null
stdout: string
stderr: string
durationMs: number
timedOut: boolean
}
export function runCommand(
command: string,
args: string[],
options: {
cwd: string
env?: Record<string, string | undefined>
timeoutMs: number
stdinText?: string
},
): Promise<CommandResult> {
return new Promise(resolve => {
const startedAt = performance.now()
const child = spawn(command, args, {
cwd: options.cwd,
env: {
...process.env,
...options.env,
},
stdio: 'pipe',
windowsHide: true,
})
let stdout = ''
let stderr = ''
let timedOut = false
child.stdout.on('data', chunk => {
stdout += String(chunk)
})
child.stderr.on('data', chunk => {
stderr += String(chunk)
})
if (options.stdinText !== undefined) {
child.stdin.write(options.stdinText)
}
child.stdin.end()
const timer = setTimeout(() => {
timedOut = true
child.kill()
}, options.timeoutMs)
child.on('close', (code, signal) => {
clearTimeout(timer)
resolve({
code,
signal,
stdout,
stderr,
durationMs: performance.now() - startedAt,
timedOut,
})
})
})
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475import { buildDistribution } from '../utils/stats.js'
import type {
BenchmarkConfig,
RunContext,
Scenario,
ScenarioSummary,
SingleExecution,
} from '../types.js'
function normalizeError(error: unknown): string {
if (error instanceof Error) return `${error.name}: ${error.message}`
return String(error)
}
function summarize(
scenario: Scenario,
executions: SingleExecution[],
): ScenarioSummary {
const successRuns = executions.filter(item => item.ok && !item.skipped).length
const failedRuns = executions.filter(item => !item.ok && !item.skipped).length
const skippedRuns = executions.filter(item => item.skipped).length
const measured = executions.filter(item => !item.skipped).map(item => item.durationMs)
return {
id: scenario.id,
name: scenario.name,
category: scenario.category,
description: scenario.description,
tags: scenario.tags,
totalRuns: executions.length,
skippedRuns,
successRuns,
failedRuns,
successRate:
executions.length === 0
? 0
: (successRuns / Math.max(1, successRuns + failedRuns)) * 100,
durationMs: buildDistribution(measured),
examples: executions
.map(item => item.details)
.filter(Boolean)
.slice(0, 3) as Array<Record<string, unknown>>,
errors: executions
.map(item => item.error)
.filter((value): value is string => Boolean(value))
.slice(0, 8),
}
}
export async function runScenarios({
scenarios,
context,
}: {
scenarios: Scenario[]
context: RunContext
config: BenchmarkConfig
}): Promise<ScenarioSummary[]> {
const results: ScenarioSummary[] = []
for (const scenario of scenarios) {
try {
const executions = await scenario.run(context)
results.push(summarize(scenario, executions))
} catch (error) {
results.push(
summarize(scenario, [
{
ok: false,
durationMs: 0,
error: normalizeError(error),
},
]),
)
}
}
return results
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768import {
getModelUsage,
getTotalAPIDuration,
getTotalAPIDurationWithoutRetries,
getTotalCacheCreationInputTokens,
getTotalCacheReadInputTokens,
getTotalCost,
getTotalDuration,
getTotalInputTokens,
getTotalLinesAdded,
getTotalLinesRemoved,
getTotalOutputTokens,
getTotalWebSearchRequests,
} from '../../src/cost-tracker.js'
import {
getTotalToolDuration,
getTurnClassifierCount,
getTurnClassifierDurationMs,
getTurnHookCount,
getTurnHookDurationMs,
getTurnToolCount,
getTurnToolDurationMs,
} from '../../src/bootstrap/state.js'
export function collectBootstrapObservability(): Record<string, unknown> {
return {
session: {
totalWallDurationMs: getTotalDuration(),
totalApiDurationMs: getTotalAPIDuration(),
totalApiDurationWithoutRetriesMs: getTotalAPIDurationWithoutRetries(),
totalToolDurationMs: getTotalToolDuration(),
totalCostUsd: getTotalCost(),
},
tokens: {
input: getTotalInputTokens(),
output: getTotalOutputTokens(),
cacheReadInput: getTotalCacheReadInputTokens(),
cacheCreationInput: getTotalCacheCreationInputTokens(),
webSearchRequests: getTotalWebSearchRequests(),
},
edits: {
linesAdded: getTotalLinesAdded(),
linesRemoved: getTotalLinesRemoved(),
},
perTurn: {
hookDurationMs: getTurnHookDurationMs(),
hookCount: getTurnHookCount(),
toolDurationMs: getTurnToolDurationMs(),
toolCount: getTurnToolCount(),
classifierDurationMs: getTurnClassifierDurationMs(),
classifierCount: getTurnClassifierCount(),
},
modelUsage: getModelUsage(),
}
}
export function collectProcessObservability(): Record<string, unknown> {
const memory = process.memoryUsage()
const cpu = process.cpuUsage()
return {
pid: process.pid,
platform: process.platform,
node: process.version,
memory,
cpu,
uptimeSec: process.uptime(),
}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167import type {
BenchmarkConfig,
BenchmarkReport,
QualityGateResult,
ScenarioSummary,
} from '../types.js'
import { clamp } from '../utils/stats.js'
function average(values: number[]): number {
if (values.length === 0) return 0
return values.reduce((sum, value) => sum + value, 0) / values.length
}
function computeScore(
summaries: ScenarioSummary[],
config: BenchmarkConfig,
): BenchmarkReport['aggregate']['score'] {
const p95s = summaries
.map(summary => summary.durationMs?.p95)
.filter((value): value is number => typeof value === 'number' && value > 0)
const avgP95 = average(p95s)
const latency = clamp(100 - avgP95 / 20, 0, 100)
const stability = clamp(
average(summaries.map(summary => summary.successRate)),
0,
100,
)
const qualityFailures = summaries.filter(summary =>
summary.tags.includes('correctness'),
).reduce((sum, item) => sum + item.failedRuns, 0)
const quality = clamp(100 - qualityFailures * 10, 0, 100)
const costProxy = clamp(100 - avgP95 / 40, 0, 100)
const total =
latency * config.weights.latency +
stability * config.weights.stability +
quality * config.weights.quality +
costProxy * config.weights.cost
return {
latency,
stability,
quality,
cost: costProxy,
total,
}
}
export function evaluateQualityGate(
summaries: ScenarioSummary[],
config: BenchmarkConfig,
): QualityGateResult {
const reasons: string[] = []
for (const summary of summaries) {
if (summary.successRate < config.thresholds.minimumSuccessRatePct) {
reasons.push(
`${summary.id} successRate ${summary.successRate.toFixed(2)}% < ${config.thresholds.minimumSuccessRatePct}%`,
)
}
const maxP95 = config.thresholds.maximumP95MsByCategory[summary.category]
if (
maxP95 !== undefined &&
summary.durationMs &&
summary.durationMs.p95 > maxP95
) {
reasons.push(
`${summary.id} p95 ${summary.durationMs.p95.toFixed(2)}ms > ${maxP95}ms`,
)
}
if (summary.id === 'B09') {
const missing =
summary.examples[0]?.missingRelativeImports as number | undefined
if (
typeof missing === 'number' &&
missing > config.thresholds.maximumMissingImports
) {
reasons.push(
`B09 missing_relative_imports=${missing} exceeds ${config.thresholds.maximumMissingImports}`,
)
}
}
}
return {
passed: reasons.length === 0,
reasons,
}
}
export function buildBenchmarkReport({
rootDir,
generatedAt,
config,
scenarios,
observability,
}: {
rootDir: string
generatedAt: string
config: BenchmarkConfig
scenarios: ScenarioSummary[]
observability: {
bootstrapState?: Record<string, unknown>
process?: Record<string, unknown>
}
}): BenchmarkReport {
const totalRuns = scenarios.reduce((sum, item) => sum + item.totalRuns, 0)
const failedScenarios = scenarios.filter(item => item.failedRuns > 0).length
const skippedScenarios = scenarios.filter(
item => item.skippedRuns === item.totalRuns,
).length
const successRate =
scenarios.length === 0
? 0
: average(scenarios.map(item => item.successRate))
const score = computeScore(scenarios, config)
const qualityGate = evaluateQualityGate(scenarios, config)
return {
version: 1,
generatedAt,
rootDir,
mode: config.mode,
runKind: config.runKind,
config,
scenarios,
aggregate: {
totalScenarios: scenarios.length,
failedScenarios,
skippedScenarios,
totalRuns,
successRate,
score,
},
observability,
qualityGate,
}
}
export function buildComparisonText(
baseline: BenchmarkReport,
current: BenchmarkReport,
): string {
const lines: string[] = []
lines.push('# Benchmark Comparison')
lines.push('')
lines.push(`- Baseline: ${baseline.generatedAt}`)
lines.push(`- Current: ${current.generatedAt}`)
lines.push(
`- Total score: ${baseline.aggregate.score.total.toFixed(2)} -> ${current.aggregate.score.total.toFixed(2)}`,
)
lines.push(
`- Success rate: ${baseline.aggregate.successRate.toFixed(2)}% -> ${current.aggregate.successRate.toFixed(2)}%`,
)
lines.push('')
lines.push('## Scenario deltas')
const baselineMap = new Map(baseline.scenarios.map(item => [item.id, item]))
for (const scenario of current.scenarios) {
const older = baselineMap.get(scenario.id)
if (!older) {
lines.push(`- ${scenario.id}: new scenario`)
continue
}
const oldP95 = older.durationMs?.p95 ?? 0
const newP95 = scenario.durationMs?.p95 ?? 0
const delta = newP95 - oldP95
lines.push(
`- ${scenario.id}: p95 ${oldP95.toFixed(2)}ms -> ${newP95.toFixed(2)}ms (delta ${delta.toFixed(2)}ms), success ${older.successRate.toFixed(2)}% -> ${scenario.successRate.toFixed(2)}%`,
)
}
return `${lines.join('\n')}\n`
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168import type { ToolUseBlock } from '@anthropic-ai/sdk/resources/index.mjs'
import { getDefaultAppState } from '../../src/state/AppStateStore.js'
import { runTools } from '../../src/services/tools/toolOrchestration.js'
import type { CanUseToolFn } from '../../src/hooks/useCanUseTool.js'
import { enqueue, resetCommandQueue } from '../../src/utils/messageQueueManager.js'
import { processQueueIfReady } from '../../src/utils/queueProcessor.js'
import { createAssistantMessage } from '../../src/utils/messages.js'
import type { ToolUseContext } from '../../src/Tool.js'
import type { BenchmarkConfig, RunContext, Scenario, SingleExecution } from '../types.js'
async function runQueueCorrectness(
_context: RunContext,
config: BenchmarkConfig,
): Promise<SingleExecution[]> {
const runs: SingleExecution[] = []
for (let i = 0; i < config.iterations.queueCorrectness; i++) {
resetCommandQueue()
const executedBatches: string[][] = []
enqueue({ value: '/help', mode: 'prompt', priority: 'next' })
enqueue({ value: 'first normal', mode: 'prompt', priority: 'next' })
enqueue({ value: 'second normal', mode: 'prompt', priority: 'next' })
enqueue({ value: 'echo hi', mode: 'bash', priority: 'next' })
const startedAt = performance.now()
while (
processQueueIfReady({
executeInput: async commands => {
executedBatches.push(commands.map(command => String(command.value)))
},
}).processed
) {
// keep draining
}
const durationMs = performance.now() - startedAt
const slashBatch = executedBatches[0] ?? []
const normalBatch = executedBatches[1] ?? []
const bashBatch = executedBatches[2] ?? []
const ok =
slashBatch.length === 1 &&
slashBatch[0] === '/help' &&
normalBatch.length === 2 &&
bashBatch.length === 1
runs.push({
ok,
durationMs,
details: {
executedBatches,
},
error: ok ? undefined : 'queue processor did not preserve expected batching semantics',
})
}
resetCommandQueue()
return runs
}
function createMinimalToolUseContext(): ToolUseContext {
let appState = getDefaultAppState()
let inProgress = new Set<string>()
return {
options: {
commands: [],
debug: false,
mainLoopModel: 'claude-sonnet-4-5',
tools: [],
verbose: false,
thinkingConfig: {
type: 'disabled',
},
mcpClients: [],
mcpResources: {},
isNonInteractiveSession: true,
agentDefinitions: { activeAgents: [], allAgents: [] },
},
abortController: new AbortController(),
readFileState: {} as ToolUseContext['readFileState'],
getAppState: () => appState,
setAppState: updater => {
appState = updater(appState)
},
setInProgressToolUseIDs: updater => {
inProgress = updater(inProgress)
},
setResponseLength: _updater => {},
updateFileHistoryState: _updater => {},
updateAttributionState: _updater => {},
messages: [],
}
}
async function runToolPipeline(
_context: RunContext,
config: BenchmarkConfig,
): Promise<SingleExecution[]> {
const runs: SingleExecution[] = []
for (let i = 0; i < config.iterations.toolPipeline; i++) {
const toolUseContext = createMinimalToolUseContext()
const canUseTool: CanUseToolFn = async (_tool, input) => ({
behavior: 'allow',
updatedInput: input,
})
const toolUseMessages: ToolUseBlock[] = [
{
id: `tool-use-${i}-1`,
name: 'NonExistentToolA',
input: {},
type: 'tool_use',
},
{
id: `tool-use-${i}-2`,
name: 'NonExistentToolB',
input: {},
type: 'tool_use',
},
]
const assistantMessages = toolUseMessages.map(toolUse =>
createAssistantMessage({
content: [toolUse],
}),
)
const startedAt = performance.now()
let yieldedMessages = 0
for await (const update of runTools(
toolUseMessages,
assistantMessages,
canUseTool,
toolUseContext,
)) {
if (update.message) {
yieldedMessages++
}
}
const durationMs = performance.now() - startedAt
const ok = yieldedMessages >= toolUseMessages.length
runs.push({
ok,
durationMs,
details: {
yieldedMessages,
},
error: ok ? undefined : 'tool orchestration produced fewer messages than expected',
})
}
return runs
}
export function createCorrectnessAndToolScenarios(
config: BenchmarkConfig,
): Scenario[] {
return [
{
id: 'B07',
name: 'Slash and Queue Correctness',
category: 'correctness',
description:
'Validate slash command isolation, normal prompt batching, and bash single-item behavior.',
tags: ['queue', 'slash', 'correctness'],
run: context => runQueueCorrectness(context, config),
},
{
id: 'B08',
name: 'Tool Pipeline Execution',
category: 'tools',
description:
'Measure runTools orchestration overhead and ensure deterministic tool-result plumbing.',
tags: ['tools', 'orchestration', 'pipeline'],
run: context => runToolPipeline(context, config),
},
]
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
import type { BenchmarkConfig, RunContext, Scenario, SingleExecution } from '../types.js'
import { runCommand } from '../harness/process.js'
function hasOnlineCredential(): boolean {
return Boolean(
process.env.ANTHROPIC_API_KEY ||
process.env.AWS_ACCESS_KEY_ID ||
process.env.AZURE_OPENAI_API_KEY,
)
}
async function offlineSingleRound(context: RunContext): Promise<SingleExecution[]> {
const startedAt = performance.now()
const output = await readFile(
join(context.rootDir, 'benchmark', 'fixtures', 'headless-offline.txt'),
'utf8',
)
const ok = output.trim().length > 0
return [
{
ok,
durationMs: performance.now() - startedAt,
details: {
outputLength: output.trim().length,
},
error: ok ? undefined : 'offline fixture output is empty',
},
]
}
async function offlineStreaming(context: RunContext): Promise<SingleExecution[]> {
const startedAt = performance.now()
const raw = await readFile(
join(context.rootDir, 'benchmark', 'fixtures', 'headless-offline.stream.jsonl'),
'utf8',
)
const lines = raw
.split(/\r?\n/)
.map(line => line.trim())
.filter(Boolean)
const parsed = lines.map(line => JSON.parse(line) as Record<string, unknown>)
const valid = parsed.every(item => typeof item.type === 'string')
const firstEventDelayMs = lines.length > 0 ? 0 : -1
return [
{
ok: valid && lines.length > 0,
durationMs: performance.now() - startedAt,
details: {
eventCount: lines.length,
firstEventDelayMs,
},
error: valid ? undefined : 'stream-json fixture contains invalid events',
},
]
}
async function onlineSingleRound(
context: RunContext,
config: BenchmarkConfig,
): Promise<SingleExecution[]> {
if (!hasOnlineCredential()) {
return [
{
ok: true,
durationMs: 0,
skipped: true,
skipReason: 'no online credentials found',
},
]
}
const result = await runCommand(
'bun',
['run', './src/bootstrap-entry.ts', '-p', 'Reply with exactly: benchmark_ok'],
{
cwd: context.rootDir,
timeoutMs: config.timeoutsMs.onlineHeadless,
},
)
const text = result.stdout.trim()
const ok = result.code === 0 && /benchmark_ok/iu.test(text)
return [
{
ok,
durationMs: result.durationMs,
details: {
exitCode: result.code,
outputPreview: text.slice(0, 120),
},
error: ok ? undefined : `online -p failed (${String(result.code)})`,
},
]
}
async function onlineStreaming(
context: RunContext,
config: BenchmarkConfig,
): Promise<SingleExecution[]> {
if (!hasOnlineCredential()) {
return [
{
ok: true,
durationMs: 0,
skipped: true,
skipReason: 'no online credentials found',
},
]
}
const stdinText =
'{"type":"user","text":"Reply in one short sentence."}\n{"type":"input_end"}\n'
const result = await runCommand(
'bun',
[
'run',
'./src/bootstrap-entry.ts',
'-p',
'--input-format=stream-json',
'--output-format=stream-json',
],
{
cwd: context.rootDir,
timeoutMs: config.timeoutsMs.onlineHeadless,
stdinText,
},
)
const lines = result.stdout
.split(/\r?\n/)
.map(line => line.trim())
.filter(Boolean)
let parsedCount = 0
for (const line of lines) {
try {
JSON.parse(line)
parsedCount++
} catch {
return [
{
ok: false,
durationMs: result.durationMs,
details: {
exitCode: result.code,
parsedCount,
line,
},
error: 'stream-json output contains invalid JSON line',
},
]
}
}
return [
{
ok: result.code === 0 && parsedCount > 0,
durationMs: result.durationMs,
details: {
exitCode: result.code,
eventCount: parsedCount,
},
error: result.code === 0 ? undefined : `online stream-json failed (${String(result.code)})`,
},
]
}
export function createHeadlessScenarios(config: BenchmarkConfig): Scenario[] {
return [
{
id: 'B05',
name: 'Headless Single Round',
category: 'headless',
description:
'Measure non-interactive single-round behavior with offline fixture and optional online sampling.',
tags: ['headless', 'print', 'quality'],
run: async context =>
context.mode === 'online'
? onlineSingleRound(context, config)
: context.mode === 'offline'
? offlineSingleRound(context)
: [
...(await offlineSingleRound(context)),
...(await onlineSingleRound(context, config)),
],
},
{
id: 'B06',
name: 'Headless Streaming',
category: 'headless',
description:
'Validate stream-json event format and first-event responsiveness with offline fixture and optional online sampling.',
tags: ['headless', 'stream-json', 'stability'],
run: async context =>
context.mode === 'online'
? onlineStreaming(context, config)
: context.mode === 'offline'
? offlineStreaming(context)
: [
...(await offlineStreaming(context)),
...(await onlineStreaming(context, config)),
],
},
]
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748import type { BenchmarkConfig, RunContext, Scenario, SingleExecution } from '../types.js'
import { runCommand } from '../harness/process.js'
function extractMissingImports(output: string): number | null {
const match = /missing_relative_imports=(\d+)/u.exec(output)
if (!match) return null
return Number(match[1])
}
async function runRestorationGate(
context: RunContext,
config: BenchmarkConfig,
): Promise<SingleExecution[]> {
const result = await runCommand('bun', ['run', './src/dev-entry.ts', '--version'], {
cwd: context.rootDir,
timeoutMs: config.timeoutsMs.command,
})
const combined = `${result.stdout}\n${result.stderr}`
const missing = extractMissingImports(combined)
const ok =
result.code === 0 &&
(missing === null || missing <= config.thresholds.maximumMissingImports)
return [
{
ok,
durationMs: result.durationMs,
details: {
exitCode: result.code,
missingRelativeImports: missing,
},
error: ok
? undefined
: `restoration gate failed (missing_relative_imports=${String(missing)})`,
},
]
}
export function createRestorationScenario(config: BenchmarkConfig): Scenario {
return {
id: 'B09',
name: 'Restoration Health Gate',
category: 'restoration',
description:
'Run restored dev entry check and enforce missing-relative-imports gate.',
tags: ['restoration', 'health', 'gate'],
run: context => runRestorationGate(context, config),
}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199import { readdir, readFile } from 'node:fs/promises'
import { join } from 'node:path'
import { clearCommandsCache, getCommands } from '../../src/commands.js'
import { getClaudeConfigHomeDir } from '../../src/utils/envUtils.js'
import type { BenchmarkConfig, RunContext, Scenario, SingleExecution } from '../types.js'
import { runCommand } from '../harness/process.js'
function parseStartupReport(content: string): Record<string, number> {
const lines = content.split(/\r?\n/)
const checkpoints = new Map<string, number>()
const pattern = /^\[\+\s*([0-9.]+)ms\]\s+\(\+\s*([0-9.]+)ms\)\s+(.+)$/u
for (const line of lines) {
const match = pattern.exec(line.trim())
if (!match) continue
checkpoints.set(match[3]!, Number(match[1]))
}
const resolve = (start: string, end: string): number | undefined => {
const s = checkpoints.get(start)
const e = checkpoints.get(end)
if (s === undefined || e === undefined) return undefined
return Math.max(0, e - s)
}
return {
importTimeMs: resolve('cli_entry', 'main_tsx_imports_loaded') ?? -1,
initTimeMs: resolve('init_function_start', 'init_function_end') ?? -1,
settingsTimeMs: resolve('eagerLoadSettings_start', 'eagerLoadSettings_end') ?? -1,
totalTimeMs: resolve('cli_entry', 'main_after_run') ?? -1,
}
}
async function readLatestStartupReport(rootDir: string): Promise<string | null> {
const dir = join(getClaudeConfigHomeDir(), 'startup-perf')
const entries = await readdir(dir, { withFileTypes: true }).catch(() => [])
const txtFiles = entries.filter(entry => entry.isFile() && entry.name.endsWith('.txt'))
if (txtFiles.length === 0) return null
const sorted = txtFiles.sort((a, b) => b.name.localeCompare(a.name))
const first = sorted[0]
if (!first) return null
return readFile(join(dir, first.name), 'utf8').catch(() => null)
}
async function runVersionBenchmark(
context: RunContext,
config: BenchmarkConfig,
): Promise<SingleExecution[]> {
const runs: SingleExecution[] = []
for (let i = 0; i < config.iterations.startup; i++) {
const result = await runCommand(
'bun',
['run', './src/bootstrap-entry.ts', '--version'],
{
cwd: context.rootDir,
timeoutMs: config.timeoutsMs.command,
},
)
runs.push({
ok: result.code === 0 && !result.timedOut,
durationMs: result.durationMs,
details: {
exitCode: result.code,
hasVersion: /^\d+/u.test(result.stdout.trim()),
},
error:
result.code === 0
? undefined
: `version command failed (code=${String(result.code)}): ${result.stderr.trim()}`,
})
}
return runs
}
async function runStartupProfiling(
context: RunContext,
config: BenchmarkConfig,
): Promise<SingleExecution[]> {
const result = await runCommand('bun', ['run', './src/bootstrap-entry.ts', '--help'], {
cwd: context.rootDir,
timeoutMs: config.timeoutsMs.command,
env: {
CLAUDE_CODE_PROFILE_STARTUP: '1',
},
})
const report = await readLatestStartupReport(context.rootDir)
const parsed = report ? parseStartupReport(report) : {}
return [
{
ok: result.code === 0 && !result.timedOut && Boolean(report),
durationMs: result.durationMs,
details: {
exitCode: result.code,
...parsed,
},
error:
report || result.code === 0
? undefined
: `startup profile run failed (code=${String(result.code)})`,
},
]
}
async function runBareComparison(
context: RunContext,
config: BenchmarkConfig,
): Promise<SingleExecution[]> {
const normal = await runCommand('bun', ['run', './src/bootstrap-entry.ts', '--help'], {
cwd: context.rootDir,
timeoutMs: config.timeoutsMs.command,
})
const bare = await runCommand(
'bun',
['run', './src/bootstrap-entry.ts', '--help', '--bare'],
{
cwd: context.rootDir,
timeoutMs: config.timeoutsMs.command,
},
)
return [
{
ok: normal.code === 0 && bare.code === 0,
durationMs: normal.durationMs + bare.durationMs,
details: {
normalMs: normal.durationMs,
bareMs: bare.durationMs,
deltaMs: normal.durationMs - bare.durationMs,
},
error:
normal.code === 0 && bare.code === 0
? undefined
: `--bare comparison failed (normal=${String(normal.code)}, bare=${String(bare.code)})`,
},
]
}
async function runCommandsLoad(
context: RunContext,
config: BenchmarkConfig,
): Promise<SingleExecution[]> {
const runs: SingleExecution[] = []
for (let i = 0; i < config.iterations.commandLoad; i++) {
clearCommandsCache()
const startedAt = performance.now()
const cold = await getCommands(context.rootDir)
const coldMs = performance.now() - startedAt
const warmStart = performance.now()
const warm = await getCommands(context.rootDir)
const warmMs = performance.now() - warmStart
runs.push({
ok: cold.length > 0 && warm.length > 0,
durationMs: coldMs + warmMs,
details: {
coldMs,
warmMs,
coldCount: cold.length,
warmCount: warm.length,
},
error: cold.length > 0 ? undefined : 'commands list is empty',
})
}
return runs
}
export function createStartupAndCommandScenarios(
config: BenchmarkConfig,
): Scenario[] {
return [
{
id: 'B01',
name: 'Version Fast Path',
category: 'startup',
description: 'Measure --version cold-start latency and exit stability.',
tags: ['cli', 'startup', 'version'],
run: context => runVersionBenchmark(context, config),
},
{
id: 'B02',
name: 'Startup Phase Profiling',
category: 'startup',
description: 'Capture startup phase durations from startup profiler checkpoints.',
tags: ['cli', 'startup', 'profiling'],
run: context => runStartupProfiling(context, config),
},
{
id: 'B03',
name: 'Bare Mode Delta',
category: 'startup',
description: 'Compare --help startup latency between normal and --bare.',
tags: ['cli', 'startup', 'bare'],
run: context => runBareComparison(context, config),
},
{
id: 'B04',
name: 'Command Catalog Load',
category: 'commands',
description: 'Measure cold/warm command catalog loading via getCommands(cwd).',
tags: ['commands', 'cache'],
run: context => runCommandsLoad(context, config),
},
]
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126export type BenchmarkMode = 'offline' | 'online' | 'hybrid'
export type BenchmarkRunKind = 'smoke' | 'full'
export type ScenarioCategory =
| 'startup'
| 'commands'
| 'headless'
| 'correctness'
| 'tools'
| 'restoration'
export type RunContext = {
rootDir: string
mode: BenchmarkMode
runKind: BenchmarkRunKind
nowIso: string
outputDir: string
}
export type SingleExecution = {
ok: boolean
durationMs: number
details?: Record<string, unknown>
error?: string
skipped?: boolean
skipReason?: string
}
export type Scenario = {
id: string
name: string
category: ScenarioCategory
description: string
tags: string[]
run: (context: RunContext) => Promise<SingleExecution[]>
}
export type Distribution = {
min: number
max: number
mean: number
p50: number
p95: number
p99: number
}
export type ScenarioSummary = {
id: string
name: string
category: ScenarioCategory
description: string
tags: string[]
totalRuns: number
skippedRuns: number
successRuns: number
failedRuns: number
successRate: number
durationMs: Distribution | null
examples: Array<Record<string, unknown>>
errors: string[]
}
export type BenchmarkWeights = {
latency: number
stability: number
quality: number
cost: number
}
export type BenchmarkThresholds = {
minimumSuccessRatePct: number
maximumP95MsByCategory: Partial<Record<ScenarioCategory, number>>
maximumMissingImports: number
}
export type BenchmarkConfig = {
mode: BenchmarkMode
runKind: BenchmarkRunKind
iterations: {
startup: number
commandLoad: number
queueCorrectness: number
toolPipeline: number
}
timeoutsMs: {
command: number
onlineHeadless: number
}
weights: BenchmarkWeights
thresholds: BenchmarkThresholds
}
export type QualityGateResult = {
passed: boolean
reasons: string[]
}
export type BenchmarkReport = {
version: 1
generatedAt: string
rootDir: string
mode: BenchmarkMode
runKind: BenchmarkRunKind
config: BenchmarkConfig
scenarios: ScenarioSummary[]
aggregate: {
totalScenarios: number
failedScenarios: number
skippedScenarios: number
totalRuns: number
successRate: number
score: {
latency: number
stability: number
quality: number
cost: number
total: number
}
}
observability: {
bootstrapState?: Record<string, unknown>
process?: Record<string, unknown>
}
qualityGate: QualityGateResult
}1234567891011121314151617import { mkdir, readFile, writeFile } from 'node:fs/promises'
import { dirname } from 'node:path'
export async function readJsonFile<T>(path: string): Promise<T> {
const raw = await readFile(path, 'utf8')
return JSON.parse(raw) as T
}
export async function writeJsonFile(path: string, value: unknown): Promise<void> {
await mkdir(dirname(path), { recursive: true })
await writeFile(path, JSON.stringify(value, null, 2), 'utf8')
}
export async function writeTextFile(path: string, value: string): Promise<void> {
await mkdir(dirname(path), { recursive: true })
await writeFile(path, value, 'utf8')
}123456789101112131415161718192021222324252627282930import type { Distribution } from '../types.js'
function quantile(sortedValues: number[], q: number): number {
if (sortedValues.length === 0) return 0
if (sortedValues.length === 1) return sortedValues[0]!
const pos = (sortedValues.length - 1) * q
const lower = Math.floor(pos)
const upper = Math.ceil(pos)
if (lower === upper) return sortedValues[lower]!
const weight = pos - lower
return sortedValues[lower]! * (1 - weight) + sortedValues[upper]! * weight
}
export function buildDistribution(values: number[]): Distribution | null {
if (values.length === 0) return null
const sorted = [...values].sort((a, b) => a - b)
const total = sorted.reduce((sum, value) => sum + value, 0)
return {
min: sorted[0]!,
max: sorted[sorted.length - 1]!,
mean: total / sorted.length,
p50: quantile(sorted, 0.5),
p95: quantile(sorted, 0.95),
p99: quantile(sorted, 0.99),
}
}
export function clamp(value: number, min: number, max: number): number {
return Math.min(max, Math.max(min, value))
}README.mdAdded+41
cli.tsAdded+163
config/defaults.tsAdded+40
fixtures/headless-offline.stream.jsonlAdded+4
fixtures/headless-offline.txtAdded+1
harness/process.tsAdded+66
harness/runner.tsAdded+75
observability/adapters.tsAdded+68
reporting/report.tsAdded+167
scenarios/correctnessTools.tsAdded+168
scenarios/headless.tsAdded+201
scenarios/restoration.tsAdded+48
scenarios/startupCommand.tsAdded+199
types.tsAdded+126
utils/files.tsAdded+17
utils/stats.tsAdded+30