From 2b09651abacf51084cc50b7a8486924123c3b979 Mon Sep 17 00:00:00 2001 From: Samanyu Das Date: Sat, 21 Nov 2026 19:46:55 +1030 Subject: [PATCH 1/3] test(repo-guards): parse only possible importers in the daemon fixture scan The daemon fixture guard parsed all 4,391 source files to build the whole import graph, then walked it from the five seed files. That took about 2.5 s, over the 2.5 s unit budget, and under full-suite load the test crossed its 5 s timeout. The scan now walks the graph from the seeds and parses a file only when it could import a family member: its text names the member, or names the directory for an index, or it sits under a path the request could reach with `.` and `..` steps, or it contains a backslash escape that could spell any request. The scan takes about 1.0 s, and it returns the same violations on the repository with every file seeded with a raw launcher. New cases pin `.` and `..` requests that the resolver maps to a sibling fixture module, and a module named `.ts`. The guard no longer fails on a syntax error in a file outside that candidate set. Such a file cannot import a family member, so the error never affected detection. Lint and typecheck still parse every file. Co-Authored-By: Claude Opus 5.5 --- .../daemon-fixture-launch-guard.test.ts | 20 +++++ scripts/lib/daemon-fixture-launch-guard.ts | 89 +++++++++++++------ 2 files changed, 82 insertions(+), 27 deletions(-) diff --git a/scripts/__tests__/daemon-fixture-launch-guard.test.ts b/scripts/__tests__/daemon-fixture-launch-guard.test.ts index 4e7a6d4a5a..b0761fe368 100644 --- a/scripts/__tests__/daemon-fixture-launch-guard.test.ts +++ b/scripts/__tests__/daemon-fixture-launch-guard.test.ts @@ -105,6 +105,26 @@ for (const specifier of ['..', '.', String.raw`.\u002e`]) { }); } +for (const [fixture, consumer, specifier] of [ + ['src/support.ts', 'src/support/consumer.test.ts', '.'], + ['src/support.ts', 'src/support/nested/consumer.test.ts', '..'], + ['src/support.ts', 'src/support.js/consumer.test.ts', '.'], + ['src/support/.ts', 'src/support/consumer.test.ts', './.ts'], +] as const) { + test(`the repo scan follows '${specifier}' from ${consumer} to ${fixture}`, () => { + const bad = `import { runCmdDetachedMonitored } from '@agent-device/host-kit/command'; const spawn = vi.mocked(runCmdDetachedMonitored); spawn.mockImplementation(() => { throw new Error('raw'); });`; + const violations = scanDaemonFixtureLaunches([ + { + file: fixture, + source: `import { createRegisteredDaemonFixtures } from '@agent-device/test-kit'; export const fixtures = createRegisteredDaemonFixtures({});`, + }, + { file: consumer, source: `import { fixtures } from '${specifier}'; ${bad}` }, + ]); + assert.equal(violations.length, 1); + assert.ok(violations[0]!.includes(consumer)); + }); +} + for (const expression of [ '(spawn as any)', 'spawn!', diff --git a/scripts/lib/daemon-fixture-launch-guard.ts b/scripts/lib/daemon-fixture-launch-guard.ts index b303c60221..68e31e81ec 100644 --- a/scripts/lib/daemon-fixture-launch-guard.ts +++ b/scripts/lib/daemon-fixture-launch-guard.ts @@ -14,24 +14,75 @@ type FixtureSource = Readonly<{ file: string; source: string }>; /** Follows local fixture imports so a renamed helper or a new consumer cannot leave the guard. */ export function scanDaemonFixtureLaunches(files: readonly FixtureSource[]): string[] { const paths = new Set(files.map(({ file }) => file)); - const parsed = new Map(files.map(({ file, source }) => [file, parseFixtureSource(file, source)])); - const importers = new Map(); - for (const [file, { dependencies }] of parsed) { - for (const specifier of dependencies) { - const dependency = resolveLocalImport(file, specifier, paths); - if (dependency) importers.set(dependency, [...(importers.get(dependency) ?? []), file]); + const parsed = new Map(); + const parse = ({ file, source }: FixtureSource): ParsedFixtureSource => { + let entry = parsed.get(file); + if (!entry) parsed.set(file, (entry = parseFixtureSource(file, source))); + return entry; + }; + const resolvedImports = new Map>(); + const importsOf = (entry: FixtureSource): ReadonlySet => { + let imports = resolvedImports.get(entry.file); + if (!imports) { + imports = new Set( + parse(entry).dependencies.flatMap( + (specifier) => resolveLocalImport(entry.file, specifier, paths) ?? [], + ), + ); + resolvedImports.set(entry.file, imports); } - } + return imports; + }; // Only a file that could name the seed needs its tree walked; everything else joins through imports. - const seeds = files - .filter(({ file, source }) => mayNameSeed(source) && namesSeed(parsed.get(file)!.program())) - .map(({ file }) => file); - const family = reachedFrom(seeds, importers); + const family = new Set( + files + .filter((entry) => mayNameSeed(entry.source) && namesSeed(parse(entry).program())) + .map(({ file }) => file), + ); + // Parsing every file to build the whole import graph costs seconds, so only a file that could + // import a family member is parsed. An escape can spell any request, so every file with one is a + // candidate. + const escaped = files.filter(({ source }) => source.includes('\\')); + const unescaped = files.filter(({ source }) => !source.includes('\\')); + const pending = [...family]; + while (pending.length > 0) { + const member = pending.pop()!; + const candidates = [...escaped, ...unescaped.filter(mayImport(member))]; + for (const candidate of candidates) { + if (family.has(candidate.file) || !importsOf(candidate).has(member)) continue; + family.add(candidate.file); + pending.push(candidate.file); + } + } return files .filter(({ file }) => family.has(file)) .flatMap(({ file, source }) => daemonFixtureLaunchViolations(source, file)); } +/** + * A cheap superset of the unescaped files whose relative request resolves to `member`. + * {@link resolveLocalImport} reaches `member` from the member path, its `.js` alias, or its + * extensionless path. Each segment of a resolved path is spelled by the request, unless `.` and `..` + * steps take it from the importer's own path, which puts the importer under that path. A request to + * an index passes through its directory, so the directory stands for every form of an index. + */ +function mayImport(member: string): (entry: FixtureSource) => boolean { + const stem = member.replace(/\.ts$/, ''); + const targets = + lastSegment(stem) === 'index' ? [path.posix.dirname(member)] : [member, `${stem}.js`, stem]; + // Every target's last segment contains this name. A module named `.ts` has an empty one, which + // admits every file. + const name = lastSegment(targets.at(-1)!); + const ancestors = targets.map((target) => `${target}/`); + return ({ file, source }) => + source.includes(name) || ancestors.some((ancestor) => file.startsWith(ancestor)); +} + +/** Unlike `path.basename`, keeps an empty segment empty (`src/fixtures/` gives ``). */ +function lastSegment(target: string): string { + return target.slice(target.lastIndexOf('/') + 1); +} + type ParsedFixtureSource = Readonly<{ program: () => AstNode; dependencies: readonly string[] }>; /** Relative module requests come from the parser's module record, so escaped specifiers resolve too. */ @@ -76,22 +127,6 @@ function namesSeed(program: AstNode): boolean { return found; } -function reachedFrom( - seeds: readonly string[], - importers: ReadonlyMap, -): Set { - const reached = new Set(seeds); - const pending = [...seeds]; - while (pending.length > 0) { - for (const importer of importers.get(pending.pop()!) ?? []) { - if (reached.has(importer)) continue; - reached.add(importer); - pending.push(importer); - } - } - return reached; -} - function resolveLocalImport( file: string, specifier: string, From 0a7c9e3235db93d4ae5acd1614ed4eecfa79cfca Mon Sep 17 00:00:00 2001 From: Samanyu Das Date: Sat, 21 Nov 2026 19:46:55 +1030 Subject: [PATCH 2/3] test(repo-guards): skip modules that cannot name a producer in the emitter scan Four tests in the snapshot producer guard each parsed and walked all 2,013 production modules, about 3.4 s per test. Under full-suite load one of them crossed the 5 s timeout. A module records a producer only through a `producer` key or a `*_PRODUCER` binding, and an escape can spell either. The scan now skips a module whose text has neither name and no backslash. Each repository scan takes about 1.05 s, and every module's scan result is unchanged. Co-Authored-By: Claude Opus 5.5 --- test/repo-guards/snapshot-producer-emitters.test.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/test/repo-guards/snapshot-producer-emitters.test.ts b/test/repo-guards/snapshot-producer-emitters.test.ts index cfccca3470..3991a329e0 100644 --- a/test/repo-guards/snapshot-producer-emitters.test.ts +++ b/test/repo-guards/snapshot-producer-emitters.test.ts @@ -96,6 +96,9 @@ function publishArgument(call: AstNode): AstNode | undefined { } function scanModule(file: string, source: string): ProducerScan { + // Only a `producer` key or a `*_PRODUCER` binding records anything, and an escape can spell either. + // Skipping the other modules unparsed keeps each repo scan well under the test timeout. + if (!/producer|PRODUCER|\\/.test(source)) return { emissions: [], references: [] }; const program = parseSync(file, source).program as unknown as AstNode; const constants = moduleConstants(program); const producerOf = (node: unknown) => { From c181a8469160acb810b3c01b6f6fe380f0a6e416 Mon Sep 17 00:00:00 2001 From: Samanyu Das Date: Sat, 21 Nov 2026 19:46:55 +1030 Subject: [PATCH 3/3] perf(fuzz): load fast-check only for generated runs `run.ts` imported `generate.ts` eagerly, so every harness run loaded fast-check and the arbitraries, about a second, even for a saved case, corpus promotion, self-check, or an options error. The harness tests spawn `run.ts` per case, and the promotion cases ran near the 2.5 s unit budget. A generate run now imports `generate.ts` once, before the first target's timer, so no target's reported duration includes the load. A promotion run drops from about 2.4 s to 1.65 s. Co-Authored-By: Claude Opus 5.5 --- scripts/fuzz/run.ts | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/scripts/fuzz/run.ts b/scripts/fuzz/run.ts index e675d58871..ef46d9021f 100644 --- a/scripts/fuzz/run.ts +++ b/scripts/fuzz/run.ts @@ -14,7 +14,6 @@ import { writeFuzzEnvelope, } from './envelope.ts'; import { runCases } from './execute.ts'; -import { generateAndCheck } from './generate.ts'; import { describeFailure, type FuzzFailure } from './invariant.ts'; import { fallbackFuzzOptions, FUZZ_USAGE, readFuzzOptions, type FuzzOptions } from './options.ts'; import { getFuzzTarget } from './registry.ts'; @@ -34,12 +33,15 @@ function corpusCasesFor(target: FuzzTarget): string[] { .map((entry) => entry.input); } -/** One target's run: generated (fast-check, shrinking) or a replay of the checked-in corpus. */ +type GenerateAndCheck = typeof import('./generate.ts').generateAndCheck; + +/** One target's run: generated (fast-check, shrinking), or without a generator a corpus replay. */ async function runOneTarget( target: FuzzTarget, options: FuzzOptions, + generateAndCheck: GenerateAndCheck | undefined, ): Promise<{ cases: number; failures: FuzzFailure[]; replayHint?: string }> { - if (options.replayCorpus) { + if (generateAndCheck === undefined) { const cases = corpusCasesFor(target); return { cases: cases.length, failures: await runCases(target, cases, options.caseTimeoutMs) }; } @@ -57,9 +59,18 @@ async function runOneTarget( async function fuzzTargets(targets: readonly FuzzTarget[], options: FuzzOptions) { const failures: FuzzFailure[] = []; const targetRuns: FuzzTargetRun[] = []; + // fast-check and the arbitraries take about a second to load, and only generation needs them. + // Loading them before the first timer keeps that cost out of every target's duration. + const generateAndCheck = options.replayCorpus + ? undefined + : (await import('./generate.ts')).generateAndCheck; for (const target of targets) { const started = Date.now(); - const { cases, failures: found, replayHint } = await runOneTarget(target, options); + const { + cases, + failures: found, + replayHint, + } = await runOneTarget(target, options, generateAndCheck); const durationMs = Date.now() - started; targetRuns.push({ target: target.name, cases, failures: found.length, durationMs }); process.stdout.write(