/** * bug-search snapshot|verify|prefix: the bench runner's commands. Each is * wiring over modules with their own laws; the commands' integration run is * `tests/oracle/cli.oracle.property.test.ts`. */ import { readdirSync, statSync } from 'node:fs' import { join, relative, resolve } from 'node:path' import { parseArgs } from 'node:util' import { JUDGE_ATTEMPTS, JUDGE_BATCH, JUDGE_TIMEOUT_SEC, REPRO_TIMEOUT_SEC, cacheDir, defaultBench, keysDir, knobsFromEnv, } from './config.ts' import { revParse } from './git.ts' import { CacheOnlyJudge, ClaudeJudge } from './judge.ts' import { keyCommits } from './key.ts' import { prefixScore } from './prefix/command.ts' import { assertQuietAllowed, reportLines } from './prefix/score.ts' import { loadBench, repoByName } from './repos.ts' import { nodeReproRunner } from './repro.ts' import { snapshotRepo } from './snapshot.ts' import { TreeCache } from './trees.ts' import { verifyKey } from './verify.ts' import type { Judge } from './judge.ts' export const HELP = `usage: bug-search [options] commands snapshot NAME... [--force] clone the manifest url, archive the cutoff into snap/, run the setup, seal it; --force rebuilds a snapshot that exists verify NAME... check a repo's key: each repro reports its bug on the snapshot and on fix^, not on fix prefix NAME --oracle DIR [--seed N] [--judge claude|cache-only|none] [--placebo] [--quiet] [--timeout-s S] which of NAME's known bugs the @tanstack/oracles files under DIR catch options --bench DIR manifests (default: this package's bench/) --cache DIR runtime state (also BUG_SEARCH_CACHE; default $XDG_CACHE_HOME/bug-search or ~/.cache/bug-search) --keys DIR the private answer keys (also BUG_SEARCH_KEYS; default ~/.local/share/bug-search/keys) ` const common = { bench: { type: `string` }, cache: { type: `string` }, keys: { type: `string` }, help: { type: `boolean`, short: `h` }, } as const // Each command's options: any other is an unknown option. const options = { snapshot: { ...common, force: { type: `boolean` } }, verify: common, prefix: { ...common, oracle: { type: `string` }, seed: { type: `string` }, judge: { type: `string` }, placebo: { type: `boolean` }, quiet: { type: `boolean` }, 'timeout-s': { type: `string` }, }, } as const type Values = Partial< Record< `bench` | `cache` | `keys` | `oracle` | `seed` | `judge` | `timeout-s`, string > > & Partial> /** The oracle files under a folder, by path relative to it. */ function oracleFilesIn(root: string): Array { const out: Array = [] const walk = (dir: string) => { for (const name of readdirSync(dir)) { const p = join(dir, name) if (name === `node_modules`) continue if (statSync(p).isDirectory()) walk(p) else if (/\.oracle\.property\.test\.[cm]?[jt]s$/.test(name)) out.push(relative(root, p)) } } walk(root) return out.sort() } function judgeOf(name: string | undefined): Judge | undefined { if (name === undefined || name === `claude`) return new ClaudeJudge({ timeoutSec: JUDGE_TIMEOUT_SEC }) if (name === `cache-only`) return new CacheOnlyJudge() if (name === `none`) return undefined throw new Error(`--judge must be claude, cache-only or none, got ${name}`) } /** A campaign seed: a safe integer, as the framework reads ORACLE_SEED. */ const seedOf = (s: string | undefined) => { if (s === undefined) return 1 const n = Number(s) if (s.trim() === `` || !Number.isSafeInteger(n)) throw new Error(`--seed must be a safe integer, got ${s}`) return n } const number = (s: string | undefined, flag: string, fallback: number) => { if (s === undefined) return fallback const n = Number(s) if (!Number.isFinite(n) || n <= 0) throw new Error(`${flag} must be a positive number, got ${s}`) return n } /** Runs one command line; `print` takes the report, `log` the progress and warnings. Returns the exit code. */ export async function main( argv: ReadonlyArray, io: { print: (line: string) => void; log: (line: string) => void }, ): Promise { const [cmd, ...rest] = argv if (!cmd || cmd === `help` || cmd === `--help` || cmd === `-h`) { io.print(HELP) return cmd ? 0 : 2 } if (!Object.hasOwn(options, cmd)) { io.log(`unknown command "${cmd}"\n\n${HELP}`) return 2 } const parsed = parseArgs({ args: [...rest], options: options[cmd as keyof typeof options], allowPositionals: true, }) const v = parsed.values as Values const { positionals } = parsed if (v.help) { io.print(HELP) return 0 } if (!positionals.length) throw new Error(`${cmd} takes repo names`) const cache = cacheDir(v.cache) const bench = loadBench({ benchDir: resolve(v.bench ?? defaultBench()), keysDir: keysDir(v.keys), cache, }) // Only the named repos must load: one broken manifest does not stop the others. const repos = positionals.map((n) => { const failed = bench.failed.find((f) => f.name === n) if (failed) throw new Error(`${n}: ${failed.error}`) return repoByName(bench, n) }) const trees = new TreeCache({ root: join(cache, `trees`), log: io.log }) if (cmd === `snapshot`) { for (const r of repos) io.print( `${r.name}: ${await snapshotRepo(r, { cache, force: Boolean(v.force), log: io.log })} (${r.snap})`, ) return 0 } if (cmd === `verify`) { let bad = 0 for (const r of repos) { if (repos.length > 1) io.print(`# ${r.name}`) bad += ( await verifyKey(r, { trees, runRepro: nodeReproRunner( REPRO_TIMEOUT_SEC, `node`, join(cache, `tmp`, `repro`), ), print: io.print, }) ).bad } return bad ? 1 : 0 } if (repos.length !== 1 || !v.oracle) throw new Error(`prefix takes one repo name and --oracle DIR`) const repo = repos[0]! // Every refusal comes before any tree, oracle run or judge call. assertQuietAllowed({ quiet: Boolean(v.quiet), split: repo.split }) const seed = seedOf(v.seed) const timeoutSec = number(v[`timeout-s`], `--timeout-s`, 60) const oracleRoot = resolve(v.oracle) const oracleFiles = oracleFilesIn(oracleRoot) if (!oracleFiles.length) throw new Error(`no *.oracle.property.test.* file under ${oracleRoot}`) const r = await prefixScore({ repo, oracleRoot, oracleFiles, trees, commits: keyCommits, revParse, judge: judgeOf(v.judge), judgeOptions: { batchSize: JUDGE_BATCH, parallel: knobsFromEnv().judgeParallel, attempts: JUDGE_ATTEMPTS, }, placebo: Boolean(v.placebo), seed, timeoutSec, cacheRoot: join(cache, `prefix`), }) for (const l of reportLines(r.score, { quiet: Boolean(v.quiet), split: repo.split, keyLines: r.keyLines, })) io.print(l) for (const u of r.unusable) io.print(`unusable ${u.id}: ${u.reason}`) return 0 } /** * The command line's entry: runs `main` with standard output and error, and * exits with its code; a thrown error is printed as `bug-search: ` * and exits 1. `src/bin.ts` calls it with the process. */ export async function run( argv: ReadonlyArray, sys: { stdout: { write: (s: string) => unknown } stderr: { write: (s: string) => unknown } exit: (code: number) => void }, ): Promise { const io = { print: (l: string) => sys.stdout.write(`${l}\n`), log: (l: string) => sys.stderr.write(`${l}\n`), } let code: number try { code = await main(argv, io) } catch (e) { // Every error the commands throw is an Error. io.log(`bug-search: ${(e as Error).message}`) code = 1 } sys.exit(code) }