import { 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 { const lines = content.split(/\r?\n/) const checkpoints = new Map() 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 { 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 { 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 { 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 { 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 { 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), }, ] }