diff --git a/packages/oracles/oracle-gaps/args.mjs b/packages/oracles/oracle-gaps/args.mjs index 010c8c5..4166030 100644 --- a/packages/oracles/oracle-gaps/args.mjs +++ b/packages/oracles/oracle-gaps/args.mjs @@ -9,7 +9,13 @@ import { stateDirOf } from './evidence.mjs' import { posix, realPathOf } from './paths.mjs' import { Refusal } from './ending.mjs' -const flags = new Set([`daemon`, `stop-daemon`, `ordinary`, `help`]) +const flags = new Set([ + `daemon`, + `stop-daemon`, + `ordinary`, + `typecheck`, + `help`, +]) // The options that take a positive whole number. const counts = [ `contexts`, @@ -33,19 +39,21 @@ const valued = new Set([ `diff-base`, `pool`, `config`, + `tsconfig`, ]) // The usage text `--help` prints (index.mjs). export const usage = `Usage: oracle-gaps --package --source - [--env-prefix ] [--daemon] [--ordinary] [--seed ] [--mutants ] - [--out ] [--only ] [--diff-base ] [--test-timeout ] - [--sample ] [--contexts ] [--pool threads|forks] [--config ] + [--env-prefix ] [--daemon] [--ordinary] [--typecheck] + [--tsconfig ] [--seed ] [--mutants ] [--out ] + [--only ] [--diff-base ] [--test-timeout ] [--sample ] + [--contexts ] [--pool threads|forks] [--config ] [--first-limit ] [--hang-limit ] [--mutant-limit ] oracle-gaps --stop-daemon --package oracle-gaps --help -The paths in --source and --config are relative to --package. Without ---config, the run loads the Vitest config that Vitest discovers for the -package: in its directory, or else in the nearest parent directory that +The paths in --source, --config, and --tsconfig are relative to --package. +Without --config, the run loads the Vitest config that Vitest discovers for +the package: in its directory, or else in the nearest parent directory that has one. Run the CLI from any directory. Every line the CLI writes for a check starts with \`oracle-gaps: \` and its kind (config, note, baseline, blocked, progress, gap, busy, done), on @@ -176,6 +184,18 @@ function optionsOf(args, cwd) { `--config ${args.config} is not a file of the package`, `Pass --config the package's Vitest config file, relative to --package.`, ) + // The TypeScript config used to check oracle files (`--tsconfig`); by + // default tsconfig.json in the package when present (typecheck.mjs). + const tsconfig = + args.tsconfig === undefined ? undefined : packagePath(pkg, args.tsconfig) + if ( + tsconfig !== undefined && + !statSync(join(pkg, tsconfig), { throwIfNoEntry: false })?.isFile() + ) + throw new Refusal( + `--tsconfig ${args.tsconfig} is not a file of the package`, + `Pass --tsconfig the package's TypeScript config file, relative to --package.`, + ) const mutants = args.mutants && resolve(cwd, args.mutants) if (mutants && !statSync(mutants, { throwIfNoEntry: false })?.isDirectory()) throw new Refusal( @@ -203,6 +223,9 @@ function optionsOf(args, cwd) { // Ordinary (non-oracle) test files run only when asked: they never close // a gap, and only report whether they would have caught a survivor. ordinary: args.ordinary === true, + // Refuse the run when TypeScript oracle files are excluded from tsconfig + // or have TypeScript errors (typecheck.mjs). + typecheck: args.typecheck === true, // Each warm context runs one mutant at a time with one worker. Measured on // offline-transactions' FIFO executor (163 mutants, 18 cores): 8 contexts // 124 s, 16 contexts 91 s, with identical classes. @@ -240,6 +263,7 @@ function optionsOf(args, cwd) { // A directory of authored mutants (see loadAuthored). mutants, config, + tsconfig, } } diff --git a/packages/oracles/oracle-gaps/check.mjs b/packages/oracles/oracle-gaps/check.mjs index be801ba..b8c00ce 100644 --- a/packages/oracles/oracle-gaps/check.mjs +++ b/packages/oracles/oracle-gaps/check.mjs @@ -64,6 +64,7 @@ import { } from './stream.mjs' import { analyze, isRunnerCopy } from './analysis.mjs' import { Refusal } from './ending.mjs' +import { typecheckOracleFiles, typecheckRefusal } from './typecheck.mjs' import { baseOf, isWithin, @@ -158,6 +159,7 @@ const ownFiles = [ `evidence.mjs`, `daemon.mjs`, `ending.mjs`, + `typecheck.mjs`, `../src/oracle-property.ts`, ].map((file) => join(here, file)) @@ -1635,6 +1637,24 @@ export default async (env) => { ) endPhase(`static analysis`, { mutants: mutants.length }) + // TypeScript coverage and semantic check for TypeScript oracle files + // (typecheck.mjs). Without --typecheck, issues surface as notes; with + // --typecheck, any uncovered oracle file, incompatible tsconfig, or + // TypeScript error refuses the run before baseline tests execute. + const typecheck = typecheckOracleFiles(ts, pkg, [...declarations.keys()], { + config: options.tsconfig, + }) + for (const line of typecheck.notes) log(line) + if (options.typecheck) { + const refusal = typecheckRefusal(ts, typecheck) + if (refusal) throw refusal + } + endPhase(`typecheck`, { + checked: typecheck.checked.length, + uncovered: typecheck.uncovered.length, + diagnostics: typecheck.diagnostics.length, + }) + // The global inputs of every unit. const lockfile = lockfileOf(pkg) const globalKey = sha1( @@ -2643,6 +2663,17 @@ export default async (env) => { })), excluded, nondeterministic: [...nondeterministic], + ...(typecheck.found + ? { + typecheck: { + config: typecheck.config, + checked: typecheck.checked, + uncovered: typecheck.uncovered, + skipped: typecheck.skipped, + diagnostics: typecheck.diagnostics, + }, + } + : {}), mutantSeconds, // How the result was produced: units reused from the evidence // store and units run in this check, runs cut off at their time @@ -2663,6 +2694,7 @@ export default async (env) => { excluded: excluded.map(relative), baseline: baselineFiles, config: options.config, + typecheck, }), ) if (existsSync(testOutput) && statSync(testOutput).size > 0) @@ -2679,6 +2711,7 @@ export default async (env) => { pkg, baseline: baselineFiles, config: options.config, + typecheck, paths: { report: escapeControls(posix(join(options.out, `summary.md`))), results: join(options.out, `results.json`), diff --git a/packages/oracles/oracle-gaps/index.mjs b/packages/oracles/oracle-gaps/index.mjs index 9284d98..bc40593 100755 --- a/packages/oracles/oracle-gaps/index.mjs +++ b/packages/oracles/oracle-gaps/index.mjs @@ -82,6 +82,10 @@ // [--env-prefix ] (the framework's variable prefix; default ORACLE) // [--daemon] (check through the package's daemon) // [--ordinary] (also run ordinary test files, for information) +// [--typecheck] (refuse if TypeScript oracle files are excluded +// from tsconfig or have TypeScript errors) +// [--tsconfig ] (the TypeScript config, relative to ; +// default tsconfig.json when present) // [--seed ] [--mutants ] [--out ] [--only ] // [--diff-base ] // [--first-limit ] (a copy's first budget; default 2000) diff --git a/packages/oracles/oracle-gaps/report.mjs b/packages/oracles/oracle-gaps/report.mjs index 17e746c..4deba1b 100644 --- a/packages/oracles/oracle-gaps/report.mjs +++ b/packages/oracles/oracle-gaps/report.mjs @@ -277,6 +277,7 @@ export function renderReport({ excluded, baseline = [], config, + typecheck, }) { const gaps = gapsOf(results) const guards = results.filter((r) => r.probeGuard) @@ -327,6 +328,22 @@ export function renderReport({ fence, ``, ) + if (typecheck?.notes?.length > 0) { + lines.push(`## Typecheck notes`, ``) + for (const item of typecheck.skipped ?? []) + lines.push( + `- Skipped ${codeSpan(item.config)}: ${escapeControls(item.reason)}`, + ) + for (const file of typecheck.uncovered ?? []) + lines.push( + `- ${codeSpan(file)} is not included in ${codeSpan(typecheck.config)}; \`tsc\` will not typecheck it.`, + ) + for (const diag of typecheck.diagnostics ?? []) + lines.push( + `- ${codeSpan(`${diag.file}:${diag.line}:${diag.column}`)} TS${diag.code}: ${escapeControls(diag.message)}`, + ) + lines.push(``) + } lines.push( `## How to use this report`, ``, @@ -414,6 +431,7 @@ export function renderStdout({ paths, baseline = [], config, + typecheck, }) { const gaps = gapsOf(results) const unowned = results.filter( @@ -468,6 +486,7 @@ export function renderStdout({ `left out, failing with no mutant active: ${excluded.join(`, `)}`, ), ) + for (const note of typecheck?.notes ?? []) lines.push(note) lines.push( streamLine(`note`, `results ${escapeControls(posix(paths.results))}`), ) diff --git a/packages/oracles/oracle-gaps/typecheck.mjs b/packages/oracles/oracle-gaps/typecheck.mjs new file mode 100644 index 0000000..a571195 --- /dev/null +++ b/packages/oracles/oracle-gaps/typecheck.mjs @@ -0,0 +1,405 @@ +// TypeScript coverage and semantic checking for TypeScript oracle files +// (check.mjs). Vitest strips types without checking them, so an oracle file +// with type errors — or one excluded from tsconfig.json — would otherwise +// pass silently. +// +// This module uses the CLI's bundled TypeScript 5 (`ts`), never the package's +// own `typescript`, so packages without TypeScript or on TypeScript 7 keep +// working. When a package has no tsconfig.json (for example a JavaScript repo +// or a synthetic fixture), default runs do nothing; `--typecheck` refuses. +// When a tsconfig.json exists, default runs emit `oracle-gaps: note +// typecheck: ...` lines for uncovered `.ts` oracle files, incompatible +// tsconfig options (such as TypeScript 7's `contentMappers`), and TypeScript +// errors in covered oracle files, while `--typecheck` refuses on any of them. +import { existsSync, statSync } from 'node:fs' +import { dirname, join, resolve } from 'node:path' +import { Refusal } from './ending.mjs' +import { posix, realPathOf, relativeWithin } from './paths.mjs' +import { escapeControls, streamLine } from './stream.mjs' + +// Maximum diagnostic note lines printed per run so a file with many errors +// does not flood the stream; results.json keeps every diagnostic. +const MAX_DIAGNOSTIC_NOTES = 20 +// Maximum uncovered oracle file note lines printed per run. +const MAX_UNCOVERED_NOTES = 20 + +// Compiler options forced when typechecking in-memory: never write build +// outputs or .tsbuildinfo files, and never fail on third-party .d.ts files. +const CHECK_OVERRIDES = { + noEmit: true, + incremental: false, + composite: false, + emitDeclarationOnly: false, + skipLibCheck: true, +} + +// TypeScript error codes that only report an empty input list (common in +// solution-style tsconfigs or configs whose `include` has no files yet), not +// an incompatible or broken tsconfig. +const EMPTY_INPUT_CODES = new Set([18002, 18003]) + +/** Whether a file is a TypeScript oracle source file (not a declaration). */ +export const isTypeScriptOracle = (file) => + /\.[cm]?tsx?$/i.test(file) && !/\.d\.[cm]?ts$/i.test(file) + +const counted = (n, thing) => `${n} ${thing}${n === 1 ? `` : `s`}` + +// Single-line, control-escaped text for any TypeScript diagnostic message. +function formatDiagnosticText(ts, diagnostic) { + return escapeControls( + ts + .flattenDiagnosticMessageText(diagnostic.messageText, ` `) + .replace(/\s+/g, ` `) + .trim(), + ) +} + +// One compiler-file cache per bundled TypeScript copy, caching only files +// under `/node_modules/` keyed by language options and stat stamp so daemon +// checks stay fast without ever returning stale project or dependency files. +const nodeModulesCache = new WeakMap() +function typecheckHostFor(ts, options) { + const base = ts.createCompilerHost(options) + if (!nodeModulesCache.has(ts)) nodeModulesCache.set(ts, new Map()) + const cache = nodeModulesCache.get(ts) + return { + ...base, + getSourceFile(fileName, languageVersionOrOptions, onError, fresh) { + const normalized = posix(fileName) + if (fresh || !normalized.includes(`/node_modules/`)) + return base.getSourceFile( + fileName, + languageVersionOrOptions, + onError, + fresh, + ) + const stat = statSync(fileName, { throwIfNoEntry: false }) + if (!stat?.isFile()) + return base.getSourceFile( + fileName, + languageVersionOrOptions, + onError, + fresh, + ) + const languageKey = + typeof languageVersionOrOptions === `object` && + languageVersionOrOptions !== null + ? `${languageVersionOrOptions.languageVersion ?? ``}:${languageVersionOrOptions.impliedNodeFormat ?? ``}:${languageVersionOrOptions.jsDocParsingMode ?? ``}` + : String(languageVersionOrOptions) + const key = `${languageKey}\0${normalized}` + const stamp = `${stat.size}:${stat.mtimeMs}` + const cached = cache.get(key) + if (cached?.stamp === stamp) return cached.sourceFile + const sourceFile = base.getSourceFile( + fileName, + languageVersionOrOptions, + onError, + fresh, + ) + if (sourceFile) cache.set(key, { stamp, sourceFile }) + return sourceFile + }, + } +} + +/** + * Checks whether each TypeScript oracle file is covered by the package's + * TypeScript config (following `projectReferences`) and, for every covering + * config compatible with bundled TypeScript 5, collects syntactic and + * semantic TypeScript error diagnostics on the oracle files. + */ +export function typecheckOracleFiles( + ts, + pkg, + oracleFiles, + { config = `tsconfig.json` } = {}, +) { + const pkgRoot = existsSync(pkg) ? realPathOf(pkg) : posix(resolve(pkg)) + const relative = (file) => + relativeWithin(pkgRoot, existsSync(file) ? realPathOf(file) : file) ?? + posix(file) + const canonical = (file) => { + const resolved = existsSync(file) ? realPathOf(file) : posix(resolve(file)) + return ts.sys.useCaseSensitiveFileNames ? resolved : resolved.toLowerCase() + } + const rootPath = join(pkg, config) + if (!existsSync(rootPath)) { + return { + found: false, + config, + checked: [], + uncovered: [], + skipped: [], + diagnostics: [], + notes: [], + } + } + const tsOracleFiles = [...new Set(oracleFiles)] + .filter(isTypeScriptOracle) + .sort((a, b) => { + const ra = relative(a) + const rb = relative(b) + return ra < rb ? -1 : ra > rb ? 1 : 0 + }) + if (tsOracleFiles.length === 0) { + return { + found: true, + config, + checked: [], + uncovered: [], + skipped: [], + diagnostics: [], + notes: [], + } + } + + // BFS over rootPath and any existing projectReferences (guarding cycles). + const loaded = [] + const visited = new Set() + const queue = [rootPath] + while (queue.length > 0) { + const current = queue.shift() + const key = canonical(current) + if (visited.has(key)) continue + visited.add(key) + const posixPath = posix(current) + const relativeConfig = relative(current) + const read = ts.readConfigFile(posixPath, ts.sys.readFile) + if (read.error) { + loaded.push({ + configPath: current, + relativeConfig, + readError: formatDiagnosticText(ts, read.error), + fileNames: [], + fileByCanonical: new Map(), + options: undefined, + configErrors: [], + }) + continue + } + const parsed = ts.parseJsonConfigFileContent( + read.config, + ts.sys, + posix(dirname(current)), + CHECK_OVERRIDES, + posixPath, + ) + const fileByCanonical = new Map() + for (const fileName of parsed.fileNames) { + const c = canonical(fileName) + if (!fileByCanonical.has(c)) fileByCanonical.set(c, fileName) + } + const configErrors = parsed.errors.filter( + (diagnostic) => !EMPTY_INPUT_CODES.has(diagnostic.code), + ) + loaded.push({ + configPath: current, + relativeConfig, + readError: undefined, + fileNames: parsed.fileNames, + fileByCanonical, + options: parsed.options, + configErrors, + }) + for (const ref of parsed.projectReferences ?? []) { + const stat = statSync(ref.path, { throwIfNoEntry: false }) + const target = stat?.isDirectory() + ? join(ref.path, `tsconfig.json`) + : ref.path + if (existsSync(target) && !visited.has(canonical(target))) + queue.push(target) + } + } + + const checked = [] + const uncovered = [] + const skipped = [] + const diagnostics = [] + + const root = loaded[0] + if (root?.readError) { + skipped.push({ config: root.relativeConfig, reason: root.readError }) + } else { + const coveredByConfig = new Map() + for (const file of tsOracleFiles) { + const key = canonical(file) + const owner = loaded.find((cfg) => cfg.fileByCanonical.has(key)) + if (!owner) { + uncovered.push(relative(file)) + continue + } + if (!coveredByConfig.has(owner)) coveredByConfig.set(owner, []) + coveredByConfig.get(owner).push({ + relativeFile: relative(file), + programFileName: owner.fileByCanonical.get(key), + }) + } + // If any oracle file is uncovered and a loaded config failed to read or + // parse, surface that config error (once per config) so the cause is visible. + const skippedConfigs = new Set() + const recordSkipped = (cfg, reason) => { + if (skippedConfigs.has(cfg.relativeConfig)) return + skippedConfigs.add(cfg.relativeConfig) + skipped.push({ config: cfg.relativeConfig, reason }) + } + if (uncovered.length > 0) { + for (const cfg of loaded) { + if (cfg.readError) recordSkipped(cfg, cfg.readError) + else if (cfg.configErrors.length > 0) + recordSkipped(cfg, formatDiagnosticText(ts, cfg.configErrors[0])) + } + } + for (const [cfg, entries] of coveredByConfig) { + if (cfg.configErrors.length > 0) { + recordSkipped(cfg, formatDiagnosticText(ts, cfg.configErrors[0])) + continue + } + const program = ts.createProgram({ + rootNames: cfg.fileNames, + options: cfg.options, + host: typecheckHostFor(ts, cfg.options), + }) + for (const { relativeFile, programFileName } of entries) { + checked.push(relativeFile) + const sourceFile = program.getSourceFile(programFileName) + if (!sourceFile) continue + const fileDiagnostics = [ + ...program.getSyntacticDiagnostics(sourceFile), + ...program.getSemanticDiagnostics(sourceFile), + ].filter((d) => d.category === ts.DiagnosticCategory.Error) + for (const diag of fileDiagnostics) { + const position = + diag.start !== undefined + ? sourceFile.getLineAndCharacterOfPosition(diag.start) + : { line: 0, character: 0 } + diagnostics.push({ + file: relativeFile, + line: position.line + 1, + column: position.character + 1, + code: diag.code, + message: formatDiagnosticText(ts, diag), + }) + } + } + } + diagnostics.sort( + (a, b) => + (a.file < b.file ? -1 : a.file > b.file ? 1 : 0) || + a.line - b.line || + a.column - b.column || + a.code - b.code || + (a.message < b.message ? -1 : a.message > b.message ? 1 : 0), + ) + } + + const result = { + found: true, + config, + checked, + uncovered, + skipped, + diagnostics, + } + return { ...result, notes: formatTypecheckNotes(result) } +} + +/** + * Formats typecheck findings as greppable single-line `oracle-gaps: note` + * stream lines (stream.mjs, law 15). + */ +export function formatTypecheckNotes({ + config, + uncovered, + skipped, + diagnostics, +}) { + const notes = [] + for (const item of skipped) + notes.push( + streamLine( + `note`, + `typecheck: skipped ${escapeControls(item.config)} (${escapeControls(item.reason)})`, + ), + ) + for (const file of uncovered.slice(0, MAX_UNCOVERED_NOTES)) + notes.push( + streamLine( + `note`, + `typecheck: ${escapeControls(file)} is not included in ${escapeControls(config)}; tsc will not typecheck it`, + ), + ) + if (uncovered.length > MAX_UNCOVERED_NOTES) + notes.push( + streamLine( + `note`, + `typecheck: ${counted(uncovered.length - MAX_UNCOVERED_NOTES, `more oracle file`)} not included in ${escapeControls(config)}`, + ), + ) + for (const diag of diagnostics.slice(0, MAX_DIAGNOSTIC_NOTES)) + notes.push( + streamLine( + `note`, + `typecheck: ${escapeControls(diag.file)}:${diag.line}:${diag.column} TS${diag.code}: ${escapeControls(diag.message)}`, + ), + ) + if (diagnostics.length > MAX_DIAGNOSTIC_NOTES) + notes.push( + streamLine( + `note`, + `typecheck: ${counted(diagnostics.length - MAX_DIAGNOSTIC_NOTES, `more TypeScript error`)} in oracle files`, + ), + ) + if (diagnostics.length > 0) { + const files = new Set(diagnostics.map((d) => d.file)) + notes.push( + streamLine( + `note`, + `typecheck: ${counted(diagnostics.length, `TypeScript error`)} in ${counted(files.size, `oracle file`)}`, + ), + ) + } + return notes +} + +/** + * The Refusal for `--typecheck` when a package lacks a compatible tsconfig, + * leaves a TypeScript oracle file out of it, or has TypeScript errors in an + * oracle file. Undefined when every TypeScript oracle file passes cleanly. + */ +export function typecheckRefusal(ts, result) { + if (!result.found) + return new Refusal( + `--typecheck requires ${escapeControls(result.config)} in the package`, + `Add ${escapeControls(result.config)} to the package, or pass --tsconfig naming a TypeScript config inside the package.`, + ) + if (result.skipped.length > 0) { + const first = result.skipped[0] + return new Refusal( + `${escapeControls(first.config)} cannot be typechecked with bundled TypeScript ${ts.version}: ${escapeControls(first.reason)}`, + `Fix ${escapeControls(first.config)}, or run the project's own TypeScript compiler instead of --typecheck.`, + ) + } + if (result.uncovered.length > 0) { + const shown = result.uncovered.slice(0, 3).map(escapeControls).join(`, `) + const listed = + result.uncovered.length === 1 + ? shown + : `${counted(result.uncovered.length, `oracle file`)} (${shown}${result.uncovered.length > 3 ? `, ...` : ``})` + return new Refusal( + `${escapeControls(result.config)} does not include ${listed}`, + `Include the oracle files in ${escapeControls(result.config)}, or pass --tsconfig naming a TypeScript config that includes them.`, + ) + } + if (result.diagnostics.length > 0) { + const first = result.diagnostics[0] + const more = + result.diagnostics.length > 1 + ? ` (+${result.diagnostics.length - 1} more TypeScript ${result.diagnostics.length === 2 ? `error` : `errors`} in oracle files)` + : `` + return new Refusal( + `${escapeControls(first.file)}:${first.line}:${first.column}: TS${first.code}: ${escapeControls(first.message)}${more}`, + `Fix the TypeScript errors in the oracle files, then run the check again.`, + ) + } + return undefined +} diff --git a/packages/oracles/tests/oracle-gaps-typecheck.test.ts b/packages/oracles/tests/oracle-gaps-typecheck.test.ts new file mode 100644 index 0000000..ee20a1c --- /dev/null +++ b/packages/oracles/tests/oracle-gaps-typecheck.test.ts @@ -0,0 +1,538 @@ +import { spawnSync } from 'node:child_process' +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + realpathSync, + rmSync, + writeFileSync, +} from 'node:fs' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { describe, expect, test } from 'vitest' +import ts from 'typescript-for-tanstack-oracles' +import { parseArgs } from '../oracle-gaps/args.mjs' +import { + typecheckOracleFiles, + typecheckRefusal, +} from '../oracle-gaps/typecheck.mjs' + +const here = dirname(fileURLToPath(import.meta.url)) +const cliPath = join(here, `../oracle-gaps/index.mjs`) +const scratchRoot = join(here, `../oracle-gaps`) + +function makeScratch(prefix: string): string { + return realpathSync.native( + mkdtempSync(join(scratchRoot, `.scratch-${prefix}-`)), + ) +} + +function writeFiles(dir: string, files: Record): void { + for (const [rel, content] of Object.entries(files)) { + const full = join(dir, rel) + mkdirSync(dirname(full), { recursive: true }) + writeFileSync(full, content) + } +} + +const cleanEnv = () => + Object.fromEntries( + Object.entries(process.env).filter( + ([name]) => + !name.startsWith(`VITEST`) && + !name.startsWith(`ORACLE_`) && + name !== `NODE_ENV` && + name !== `TEST`, + ), + ) + +function runCli(pkg: string, args: Array) { + return spawnSync(process.execPath, [cliPath, ...args], { + cwd: pkg, + encoding: `utf8`, + env: cleanEnv(), + timeout: 120_000, + }) +} + +const minimalSource = `export function add(a: number, b: number): number { + return a + b +} +` + +const minimalOracle = (body: string) => `import { expect, test } from 'vitest' +import { add } from '../src/math' + +declare function oracleProperty(spec: { owns: Array }): void +if (false) oracleProperty({ owns: ['src/math.ts#add'] }) + +test('adds numbers', () => { +${body} +}) +` + +describe(`oracle-gaps typecheck`, () => { + test(`does nothing when the package has no tsconfig.json, and refuses with --typecheck`, () => { + const pkg = makeScratch(`no-tsconfig`) + try { + writeFiles(pkg, { + 'package.json': JSON.stringify({ name: `no-tsconfig`, private: true }), + 'src/math.ts': minimalSource, + 'tests/math.oracle.test.ts': `const x: number = 'not a number'\nexport { x }\n`, + }) + const oracle = join(pkg, `tests/math.oracle.test.ts`) + const result = typecheckOracleFiles(ts, pkg, [oracle]) + expect(result.found).toBe(false) + expect(result.notes).toEqual([]) + expect(result.diagnostics).toEqual([]) + expect(result.uncovered).toEqual([]) + + const refusal = typecheckRefusal(ts, result) + expect(refusal).toBeDefined() + expect(refusal?.message).toContain(`tsconfig.json`) + expect(refusal?.fix).not.toMatch(/\b(ignore|equivalent|skip)/i) + } finally { + rmSync(pkg, { recursive: true, force: true }) + } + }) + + test(`checks covered TypeScript oracle files and ignores unrelated files' type errors`, () => { + const pkg = makeScratch(`covered-errors`) + try { + writeFiles(pkg, { + 'package.json': JSON.stringify({ + name: `covered-errors`, + private: true, + }), + 'tsconfig.json': JSON.stringify({ + compilerOptions: { + target: `ES2022`, + module: `ESNext`, + moduleResolution: `Bundler`, + strict: true, + types: [], + }, + include: [`src`, `tests`], + }), + 'src/math.ts': minimalSource, + 'src/unrelated.ts': `export const broken: number = 'unrelated error'\n`, + 'tests/math.oracle.test.ts': `import { add } from '../src/math'\nexport const result: number = add('bad', 2)\n`, + }) + const oracle = join(pkg, `tests/math.oracle.test.ts`) + const result = typecheckOracleFiles(ts, pkg, [oracle]) + expect(result.found).toBe(true) + expect(result.checked).toEqual([`tests/math.oracle.test.ts`]) + expect(result.uncovered).toEqual([]) + expect(result.skipped).toEqual([]) + expect(result.diagnostics).toHaveLength(1) + expect(result.diagnostics[0]).toMatchObject({ + file: `tests/math.oracle.test.ts`, + line: 2, + code: 2345, + }) + expect( + result.notes.some((line) => + line.startsWith( + `oracle-gaps: note typecheck: tests/math.oracle.test.ts:2:`, + ), + ), + ).toBe(true) + expect(result.notes.some((line) => line.includes(`TS2345:`))).toBe(true) + + const refusal = typecheckRefusal(ts, result) + expect(refusal).toBeDefined() + expect(refusal?.message).toContain(`tests/math.oracle.test.ts:2:`) + expect(refusal?.message).toContain(`TS2345`) + expect(refusal?.fix).not.toMatch(/\b(ignore|equivalent|skip)/i) + } finally { + rmSync(pkg, { recursive: true, force: true }) + } + }) + + test(`reports uncovered TypeScript oracle files when excluded from tsconfig.json`, () => { + const pkg = makeScratch(`uncovered`) + try { + writeFiles(pkg, { + 'package.json': JSON.stringify({ name: `uncovered`, private: true }), + 'tsconfig.json': JSON.stringify({ + compilerOptions: { + target: `ES2022`, + module: `ESNext`, + moduleResolution: `Bundler`, + strict: true, + types: [], + }, + include: [`src`], + }), + 'tsconfig.test.json': JSON.stringify({ + extends: `./tsconfig.json`, + include: [`src`, `tests`], + }), + 'src/math.ts': minimalSource, + 'tests/math.oracle.test.ts': `import { add } from '../src/math'\nexport const ok: number = add(1, 2)\n`, + }) + const oracle = join(pkg, `tests/math.oracle.test.ts`) + const uncoveredResult = typecheckOracleFiles(ts, pkg, [oracle]) + expect(uncoveredResult.found).toBe(true) + expect(uncoveredResult.uncovered).toEqual([`tests/math.oracle.test.ts`]) + expect(uncoveredResult.checked).toEqual([]) + expect(uncoveredResult.notes).toEqual([ + `oracle-gaps: note typecheck: tests/math.oracle.test.ts is not included in tsconfig.json; tsc will not typecheck it`, + ]) + const refusal = typecheckRefusal(ts, uncoveredResult) + expect(refusal?.message).toContain(`tests/math.oracle.test.ts`) + expect(refusal?.fix).not.toMatch(/\b(ignore|equivalent|skip)/i) + + // Passing --tsconfig tsconfig.test.json covers and checks the file cleanly. + const coveredResult = typecheckOracleFiles(ts, pkg, [oracle], { + config: `tsconfig.test.json`, + }) + expect(coveredResult.found).toBe(true) + expect(coveredResult.uncovered).toEqual([]) + expect(coveredResult.checked).toEqual([`tests/math.oracle.test.ts`]) + expect(coveredResult.diagnostics).toEqual([]) + expect(coveredResult.notes).toEqual([]) + expect(typecheckRefusal(ts, coveredResult)).toBeUndefined() + } finally { + rmSync(pkg, { recursive: true, force: true }) + } + }) + + test(`follows solution-style project references (including directory references and cycles)`, () => { + const pkg = makeScratch(`solution-refs`) + try { + writeFiles(pkg, { + 'package.json': JSON.stringify({ + name: `solution-refs`, + private: true, + }), + 'tsconfig.json': JSON.stringify({ + files: [], + references: [{ path: `./tsconfig.app.json` }, { path: `./sub` }], + }), + 'tsconfig.app.json': JSON.stringify({ + compilerOptions: { + target: `ES2022`, + module: `ESNext`, + moduleResolution: `Bundler`, + strict: true, + types: [], + }, + include: [`src`], + references: [{ path: `./tsconfig.json` }], + }), + 'sub/tsconfig.json': JSON.stringify({ + compilerOptions: { + target: `ES2022`, + module: `ESNext`, + moduleResolution: `Bundler`, + strict: true, + types: [], + }, + include: [`../src`, `../tests`], + }), + 'src/math.ts': minimalSource, + 'tests/ok.oracle.test.ts': `import { add } from '../src/math'\nexport const ok: number = add(1, 2)\n`, + 'tests/bad.oracle.test.ts': `import { add } from '../src/math'\nexport const bad: number = add(1, 'two')\n`, + }) + const okFile = join(pkg, `tests/ok.oracle.test.ts`) + const badFile = join(pkg, `tests/bad.oracle.test.ts`) + + const clean = typecheckOracleFiles(ts, pkg, [okFile]) + expect(clean.uncovered).toEqual([]) + expect(clean.skipped).toEqual([]) + expect(clean.checked).toEqual([`tests/ok.oracle.test.ts`]) + expect(clean.diagnostics).toEqual([]) + expect(clean.notes).toEqual([]) + + const errored = typecheckOracleFiles(ts, pkg, [okFile, badFile]) + expect(errored.uncovered).toEqual([]) + expect(errored.diagnostics).toHaveLength(1) + expect(errored.diagnostics[0]?.file).toBe(`tests/bad.oracle.test.ts`) + expect(errored.diagnostics[0]?.code).toBe(2345) + } finally { + rmSync(pkg, { recursive: true, force: true }) + } + }) + + test(`gracefully skips TS 7-only tsconfig options while still checking coverage`, () => { + const pkg = makeScratch(`ts7-config`) + try { + writeFiles(pkg, { + 'package.json': JSON.stringify({ name: `ts7-config`, private: true }), + 'tsconfig.json': JSON.stringify({ + compilerOptions: { + target: `ES2022`, + module: `ESNext`, + moduleResolution: `Bundler`, + strict: true, + contentMappers: [`./mapper.mjs`], + }, + include: [`src`, `tests/covered.oracle.test.ts`], + }), + 'src/math.ts': minimalSource, + 'tests/covered.oracle.test.ts': `import { add } from '../src/math'\nexport const x: number = add('bad', 2)\n`, + 'tests/uncovered.oracle.test.ts': `export const y = 1\n`, + }) + const covered = join(pkg, `tests/covered.oracle.test.ts`) + const uncovered = join(pkg, `tests/uncovered.oracle.test.ts`) + const result = typecheckOracleFiles(ts, pkg, [covered, uncovered]) + expect(result.found).toBe(true) + expect(result.uncovered).toEqual([`tests/uncovered.oracle.test.ts`]) + expect(result.skipped).toHaveLength(1) + expect(result.skipped[0]?.config).toBe(`tsconfig.json`) + expect(result.skipped[0]?.reason).toContain(`contentMappers`) + expect(result.diagnostics).toEqual([]) + expect(result.notes).toEqual([ + expect.stringContaining( + `oracle-gaps: note typecheck: skipped tsconfig.json`, + ), + `oracle-gaps: note typecheck: tests/uncovered.oracle.test.ts is not included in tsconfig.json; tsc will not typecheck it`, + ]) + + const refusal = typecheckRefusal(ts, result) + expect(refusal?.message).toContain(`contentMappers`) + expect(refusal?.fix).not.toMatch(/\b(ignore|equivalent|skip)/i) + } finally { + rmSync(pkg, { recursive: true, force: true }) + } + }) + + test(`ignores non-TypeScript oracle files and handles invalid tsconfig JSON without crashing`, () => { + const pkg = makeScratch(`js-and-invalid`) + try { + writeFiles(pkg, { + 'package.json': JSON.stringify({ + name: `js-and-invalid`, + private: true, + }), + 'tsconfig.json': `{ invalid json`, + 'src/math.ts': minimalSource, + 'tests/math.oracle.test.mjs': `export const ok = 1\n`, + 'tests/math.oracle.test.ts': `export const ok = 1\n`, + }) + const jsOnly = typecheckOracleFiles(ts, pkg, [ + join(pkg, `tests/math.oracle.test.mjs`), + ]) + expect(jsOnly.found).toBe(true) + expect(jsOnly.notes).toEqual([]) + expect(typecheckRefusal(ts, jsOnly)).toBeUndefined() + + const badJson = typecheckOracleFiles(ts, pkg, [ + join(pkg, `tests/math.oracle.test.ts`), + ]) + expect(badJson.found).toBe(true) + expect(badJson.uncovered).toEqual([]) + expect(badJson.skipped).toHaveLength(1) + expect(badJson.notes).toHaveLength(1) + expect(badJson.notes[0]).toMatch( + /^oracle-gaps: note typecheck: skipped tsconfig\.json/, + ) + } finally { + rmSync(pkg, { recursive: true, force: true }) + } + }) + + test(`parseArgs validates --typecheck and --tsconfig`, () => { + const pkg = makeScratch(`args`) + try { + writeFiles(pkg, { + 'package.json': JSON.stringify({ name: `args`, private: true }), + 'src/math.ts': minimalSource, + 'tsconfig.test.json': `{}\n`, + }) + const parsed = parseArgs( + [ + `--package`, + pkg, + `--source`, + `src/math.ts`, + `--typecheck`, + `--tsconfig`, + `tsconfig.test.json`, + ], + pkg, + ) + expect(parsed.typecheck).toBe(true) + expect(parsed.tsconfig).toBe(`tsconfig.test.json`) + + expect(() => + parseArgs( + [ + `--package`, + pkg, + `--source`, + `src/math.ts`, + `--tsconfig`, + `missing.json`, + ], + pkg, + ), + ).toThrow(/--tsconfig missing\.json is not a file of the package/) + expect(() => + parseArgs( + [ + `--package`, + pkg, + `--source`, + `src/math.ts`, + `--tsconfig`, + `../outside.json`, + ], + pkg, + ), + ).toThrow(/outside the package/) + } finally { + rmSync(pkg, { recursive: true, force: true }) + } + }) + + test(`CLI surfaces type errors by default, refuses with --typecheck, and stays consistent under --daemon`, () => { + const pkg = makeScratch(`cli-e2e`) + try { + writeFiles(pkg, { + 'package.json': JSON.stringify({ + name: `cli-e2e`, + private: true, + type: `module`, + }), + 'vitest.config.mjs': `export default { test: { include: ['tests/**/*.test.ts'] } }\n`, + 'tsconfig.json': JSON.stringify({ + compilerOptions: { + target: `ES2022`, + module: `ESNext`, + moduleResolution: `Bundler`, + strict: true, + noEmit: true, + skipLibCheck: true, + }, + include: [`src`, `tests`], + }), + 'src/math.ts': minimalSource, + // Vitest strips types so this passes at runtime, while tsc rejects it. + 'tests/math.oracle.test.ts': minimalOracle( + ` const wrong: string = add(1, 2)\n expect(wrong).toBe(3)`, + ), + }) + + // 1. Default run completes (exit 0) and emits greppable typecheck notes + // on stderr, stream.log, stdout, summary.md, and results.json. + const outDefault = join(pkg, `out-default`) + const defaultRun = runCli(pkg, [ + `--package`, + pkg, + `--source`, + `src/math.ts`, + `--contexts`, + `1`, + `--out`, + outDefault, + ]) + expect(defaultRun.status, defaultRun.stderr).toBe(0) + expect(defaultRun.stderr).toContain( + `oracle-gaps: note typecheck: tests/math.oracle.test.ts:`, + ) + expect(defaultRun.stderr).toContain(`TS2322:`) + expect(defaultRun.stdout).toContain( + `oracle-gaps: note typecheck: tests/math.oracle.test.ts:`, + ) + expect(readFileSync(join(outDefault, `stream.log`), `utf8`)).toBe( + defaultRun.stderr, + ) + expect(readFileSync(join(outDefault, `summary.md`), `utf8`)).toContain( + `## Typecheck notes`, + ) + const defaultResults = JSON.parse( + readFileSync(join(outDefault, `results.json`), `utf8`), + ) as { + typecheck?: { + config: string + diagnostics: Array<{ file: string; code: number }> + } + } + expect(defaultResults.typecheck?.config).toBe(`tsconfig.json`) + expect(defaultResults.typecheck?.diagnostics).toEqual([ + expect.objectContaining({ + file: `tests/math.oracle.test.ts`, + code: 2322, + }), + ]) + + // 2. With --typecheck, the same package refuses (exit 2) before baseline runs. + const outStrict = join(pkg, `out-strict`) + const strictRun = runCli(pkg, [ + `--package`, + pkg, + `--source`, + `src/math.ts`, + `--typecheck`, + `--contexts`, + `1`, + `--out`, + outStrict, + ]) + expect(strictRun.status, strictRun.stderr).toBe(2) + expect(strictRun.stderr).toContain( + `oracle-gaps: note typecheck: tests/math.oracle.test.ts:`, + ) + expect(strictRun.stderr).toContain(`refused: tests/math.oracle.test.ts:`) + expect(strictRun.stderr).toContain(`TS2322`) + expect(strictRun.stderr).toContain(`fix: `) + expect(strictRun.stderr).toContain(`oracle-gaps: done refused, report `) + expect(strictRun.stdout).toContain(`oracle-gaps: done refused, report `) + expect(readFileSync(join(outStrict, `stream.log`), `utf8`)).toBe( + strictRun.stderr, + ) + const strictResults = JSON.parse( + readFileSync(join(outStrict, `results.json`), `utf8`), + ) as { status: string; cause: string } + expect(strictResults.status).toBe(`refused`) + expect(strictResults.cause).toContain(`TS2322`) + + // 3. Through --daemon: refuses while broken, then passes once fixed. + const outDaemonBroken = join(pkg, `out-daemon-broken`) + const daemonBroken = runCli(pkg, [ + `--package`, + pkg, + `--source`, + `src/math.ts`, + `--typecheck`, + `--daemon`, + `--contexts`, + `1`, + `--out`, + outDaemonBroken, + ]) + expect(daemonBroken.status, daemonBroken.stderr).toBe(2) + expect(daemonBroken.stderr).toContain(`TS2322`) + + // Fix the type error and verify daemon sees the fresh file and passes. + writeFiles(pkg, { + 'tests/math.oracle.test.ts': minimalOracle( + ` const right: number = add(1, 2)\n expect(right).toBe(3)`, + ), + }) + const outDaemonFixed = join(pkg, `out-daemon-fixed`) + const daemonFixed = runCli(pkg, [ + `--package`, + pkg, + `--source`, + `src/math.ts`, + `--typecheck`, + `--daemon`, + `--contexts`, + `1`, + `--out`, + outDaemonFixed, + ]) + expect(daemonFixed.status, daemonFixed.stderr).toBe(0) + expect(daemonFixed.stderr).not.toContain(`oracle-gaps: note typecheck:`) + expect(daemonFixed.stdout).not.toContain(`oracle-gaps: note typecheck:`) + expect(existsSync(join(outDaemonFixed, `results.json`))).toBe(true) + } finally { + runCli(pkg, [`--stop-daemon`, `--package`, pkg]) + rmSync(pkg, { recursive: true, force: true }) + } + }, 120_000) +})