Open History to see the last commit
1/**
2 * Law L4 (lint scope): after an edit, every oracle file whose oracle lint result
3 * can change is linted again, by the edit hook, by `pnpm lint:changed`, and by
4 * the pre-commit hook. An oracle file's result depends on the test modules that
5 * it reaches through relative imports and re-exports: its companions, support
6 * modules, drivers, and other oracle files. The rule does not read production
7 * source, so an edit to production code selects nothing. A change to the
8 * rule's own sources changes every oracle result, so it selects every oracle
9 * file. An oracle file is any file in the working tree whose name contains
10 * `oracle`, in TypeScript or JavaScript, tracked or new and untracked: an
11 * agent's new oracle file is linted like any other.
12 *
13 * Authority: AGENTS.md "Lint feedback while you work" says the hooks and
14 * `pnpm lint:changed` return the oracle reports for the files that were edited,
15 * and that the pre-commit hook lints the staged files. AGENTS.md "Name oracle
16 * files for discovery" defines an oracle file by its name. The rule's header
17 * contract (scripts/eslint-plugin-oracle/rules/no-unit-test.js) states that the
18 * rule follows relative imports of test modules and does not follow production
19 * source. The rule-source case follows from the same reports: the oracle
20 * results are a function of the rule's code.
21 *
22 * Limits. The grammar draws up to three oracle files, two or three support
23 * modules, one driver, and one production module, with relative imports and
24 * re-exports. Half the programs take a re-export chain: the first oracle file
25 * imports the first support module, which re-exports the second. An oracle file
26 * is `.ts` or `.js`, and one can be new and untracked. Support modules and
27 * drivers are `.ts`, and only a tracked `.ts` oracle file is imported by another
28 * oracle file, because the rule resolves only TypeScript test modules. The
29 * `.js` specifier form of an import is drawn for some oracle files. Re-exports
30 * are drawn for support modules only, and star re-exports are the only form.
31 * The driver runs the lint command-line script in temporary git repositories.
32 * The pre-commit leg is covered only by the script's file selection: the glob in
33 * lint-staged.config.js is not evaluated here.
34 *
35 * Structure:
36 * 1. The grammar draws a module graph, the edited and untracked modules, and
37 * the file that an edit hook names.
38 * 2. The model predicts the oracle files to lint for each scope, by a
39 * fixed-point closure over the graph's edges.
40 * 3. The driver writes the base commit and the edited working tree, then runs
41 * the CLI's changed scope, its named scope, and its edit-hook form. A
42 * crashed CLI is a failure, not an empty selection.
43 * 4. The comparison checks that each observed selection equals the prediction.
44 * 5. Reach counts the graph states that the campaign enters, and the
45 * campaigns run the same predicate with a fixed seed and a random seed.
46 */
47import { execFileSync, spawnSync } from 'node:child_process'
48import {
49 cpSync,
50 mkdirSync,
51 mkdtempSync,
52 readFileSync,
53 realpathSync,
54 rmSync,
55 symlinkSync,
56 writeFileSync,
57} from 'node:fs'
58import { tmpdir } from 'node:os'
59import { join } from 'node:path'
60import { setImmediate } from 'node:timers/promises'
61import { fileURLToPath } from 'node:url'
62import fc from 'fast-check'
63import { afterAll, beforeAll, describe, expect, it } from 'vitest'
64import { declareOracle } from '../packages/db/tests/oracle-declaration.js'
65import {
66 oraclePropertyOptions,
67 oracleRuns,
68} from '../packages/db/tests/oracle-config.js'
69import { createOracleReach } from '../packages/db/tests/oracle-reach.js'
70
71const PROPERTY = `scripts.lint-scope`
72const FIXED_SEED = 2234
73const BASE_RUNS = 24
74const PRODUCTION = `src/prod.ts`
75const repoRoot = fileURLToPath(new URL(`../`, import.meta.url))
76const APP = `packages/app`
77const RULE = `scripts/eslint-plugin-oracle/rules/no-unit-test.js`
78
79// -- 1. Grammar ---------------------------------------------------------------
80//
81// Every module is a node. An oracle file imports supports, drivers, other
82// oracle files, and production. A support module imports other supports and
83// production. A driver imports supports. Production imports nothing. Each
84// target is an index taken modulo the modules the kind may reach, so every draw
85// is a legal edge. A star re-export is an import whose names the module passes
86// on. An edit adds a line to a module, so its text differs from the base
87// commit. An untracked oracle file exists only in the working tree, so nothing
88// imports it. The edit hook names one module, or the rule's source.
89
90const moduleEdit = fc.boolean()
91
92// Most modules import one target. A second route to an edited module would
93// hide the effect of a re-export, so single targets are drawn more often.
94const singleOrManyTargets = fc.oneof(
95 {
96 weight: 3,
97 arbitrary: fc.array(fc.nat({ max: 9 }), { minLength: 1, maxLength: 1 }),
98 },
99 {
100 weight: 1,
101 arbitrary: fc.array(fc.nat({ max: 9 }), { minLength: 1, maxLength: 3 }),
102 },
103)
104
105const programArbitrary = fc
106 .record({
107 // Random draws reach three shapes too rarely, so a share of the programs
108 // take each of them. See the shape functions below.
109 shape: fc.oneof(
110 { weight: 2, arbitrary: fc.constant(`free`) },
111 { weight: 2, arbitrary: fc.constant(`re-export chain`) },
112 { weight: 2, arbitrary: fc.constant(`oracle chain`) },
113 { weight: 1, arbitrary: fc.constant(`untracked dependent`) },
114 ),
115 oracles: fc.array(
116 fc.record({
117 edited: moduleEdit,
118 targets: singleOrManyTargets,
119 style: fc.nat({ max: 1 }),
120 extension: fc.oneof(
121 { weight: 2, arbitrary: fc.constant(`ts`) },
122 { weight: 1, arbitrary: fc.constant(`js`) },
123 ),
124 untracked: fc.oneof(
125 { weight: 3, arbitrary: fc.constant(false) },
126 { weight: 1, arbitrary: fc.constant(true) },
127 ),
128 }),
129 { minLength: 1, maxLength: 3 },
130 ),
131 // Two supports or more let a chain form, and a single target keeps a
132 // re-export on the only route to an edited module.
133 supports: fc.array(
134 fc.record({
135 edited: moduleEdit,
136 targets: singleOrManyTargets,
137 reexport: fc.array(
138 fc.oneof(
139 { weight: 3, arbitrary: fc.constant(true) },
140 { weight: 1, arbitrary: fc.constant(false) },
141 ),
142 { minLength: 1, maxLength: 2 },
143 ),
144 }),
145 { minLength: 2, maxLength: 3 },
146 ),
147 driver: fc.record({
148 present: fc.boolean(),
149 edited: moduleEdit,
150 targets: fc.array(fc.nat({ max: 9 }), { maxLength: 2 }),
151 }),
152 production: fc.record({ edited: moduleEdit }),
153 ruleEdited: fc.oneof(
154 { weight: 3, arbitrary: fc.constant(false) },
155 { weight: 1, arbitrary: fc.constant(true) },
156 ),
157 // The edit hook names a module of this kind, or the rule's source.
158 hookKind: fc.oneof(
159 { weight: 2, arbitrary: fc.constant(`oracle`) },
160 { weight: 2, arbitrary: fc.constant(`support`) },
161 { weight: 2, arbitrary: fc.constant(`driver`) },
162 { weight: 1, arbitrary: fc.constant(`production`) },
163 { weight: 2, arbitrary: fc.constant(`rule`) },
164 ),
165 hookIndex: fc.nat({ max: 9 }),
166 })
167 .map(({ shape, ...skeleton }) => {
168 const drawn =
169 skeleton.hookKind === `driver`
170 ? { ...skeleton, driver: { ...skeleton.driver, present: true } }
171 : skeleton
172 return buildProgram(shapes[shape](drawn))
173 })
174
175const shapes = {
176 free: (skeleton) => skeleton,
177 're-export chain': reexportChain,
178 'oracle chain': oracleChain,
179 'untracked dependent': untrackedDependent,
180}
181
182/** The skeleton's first two oracle files, adding a second when there is one. */
183function twoOracles(skeleton) {
184 const [first, second = first] = skeleton.oracles
185 return [first, second, ...skeleton.oracles.slice(2)]
186}
187
188/**
189 * The skeleton with the re-export chain drawn: oracle 0 imports support 0, which
190 * re-exports support 1. Oracle 0 and support 0 are unedited and support 1 is
191 * edited, so the re-export is the only route from the edit to oracle 0.
192 */
193function reexportChain(skeleton) {
194 return {
195 ...skeleton,
196 oracles: skeleton.oracles.map((oracle, index) =>
197 index === 0
198 ? { ...oracle, edited: false, untracked: false, targets: [0] }
199 : oracle,
200 ),
201 supports: skeleton.supports.map((support, index) => {
202 if (index === 0) {
203 return { ...support, edited: false, targets: [1], reexport: [true] }
204 }
205 if (index === 1) return { ...support, edited: true }
206 return support
207 }),
208 }
209}
210
211/**
212 * The skeleton with an oracle chain drawn: oracle 1 imports only oracle 0, which
213 * imports the edited support 0. The other oracle file is the only route from
214 * the edit to oracle 1.
215 */
216function oracleChain(skeleton) {
217 const [first, second, ...rest] = twoOracles(skeleton)
218 return {
219 ...skeleton,
220 oracles: [
221 {
222 ...first,
223 extension: `ts`,
224 untracked: false,
225 edited: false,
226 targets: [0],
227 },
228 {
229 ...second,
230 untracked: false,
231 edited: false,
232 fixedTargets: [`case-0-oracle.test.ts`],
233 },
234 ...rest,
235 ],
236 supports: skeleton.supports.map((support, index) =>
237 index === 0 ? { ...support, edited: true } : support,
238 ),
239 }
240}
241
242/**
243 * The skeleton with an untracked dependent drawn: oracle 1 is new and untracked
244 * and imports support 0, which the edit hook names.
245 */
246function untrackedDependent(skeleton) {
247 const [first, second, ...rest] = twoOracles(skeleton)
248 return {
249 ...skeleton,
250 oracles: [
251 first,
252 { ...second, untracked: true, fixedTargets: [`support-0.ts`] },
253 ...rest,
254 ],
255 hookName: `support-0.ts`,
256 }
257}
258
259/**
260 * The modules of a program, with the import edges that the grammar drew. A
261 * re-export is an edge that the module passes on by star export. A shape can
262 * fix a module's targets by name.
263 */
264function buildProgram(skeleton) {
265 const oracles = skeleton.oracles.map((oracle, index) => ({
266 // The rule skips basenames that start with `oracle-`, which are its own
267 // machinery, so generated oracle files use another prefix.
268 name: `case-${index}-oracle.test.${oracle.extension}`,
269 kind: `oracle`,
270 untracked: oracle.untracked,
271 // An untracked file is new, so it has no separate edit.
272 edited: oracle.edited && !oracle.untracked,
273 style: oracle.style,
274 targets: oracle.targets,
275 fixedTargets: oracle.fixedTargets,
276 }))
277 const supports = skeleton.supports.map((support, index) => ({
278 name: `support-${index}.ts`,
279 kind: `support`,
280 untracked: false,
281 edited: support.edited,
282 targets: support.targets,
283 reexport: support.reexport,
284 }))
285 const driver = skeleton.driver.present
286 ? [
287 {
288 name: `driver.test.ts`,
289 kind: `driver`,
290 untracked: false,
291 edited: skeleton.driver.edited,
292 targets: skeleton.driver.targets,
293 reexport: [],
294 },
295 ]
296 : []
297 const production = {
298 name: PRODUCTION,
299 kind: `production`,
300 untracked: false,
301 edited: skeleton.production.edited,
302 targets: [],
303 reexport: [],
304 }
305 const test = [...oracles, ...supports, ...driver]
306 // Only a tracked TypeScript oracle file can be imported by another one.
307 const importableOracles = oracles.filter(
308 (oracle) => !oracle.untracked && oracle.name.endsWith(`.ts`),
309 )
310 const allowed = {
311 oracle: [...supports, ...driver, ...importableOracles, production],
312 support: [...supports, production],
313 driver: [...supports],
314 }
315 const edges = new Map()
316 const reexports = new Map()
317 const byName = new Map(
318 [...test, production].map((module) => [module.name, module]),
319 )
320 for (const module of test) {
321 const targets = allowed[module.kind]
322 const chosen = (module.fixedTargets ?? []).map((name) => ({
323 target: byName.get(name),
324 reexport: false,
325 }))
326 for (const [position, index] of module.fixedTargets
327 ? []
328 : module.targets.entries()) {
329 if (targets.length === 0) break
330 const target = targets[index % targets.length]
331 if (chosen.some((edge) => edge.target === target) || target === module) {
332 continue
333 }
334 chosen.push({ target, reexport: module.reexport?.[position] === true })
335 }
336 edges.set(
337 module.name,
338 chosen.map((edge) => edge.target.name),
339 )
340 reexports.set(
341 module.name,
342 new Set(
343 chosen.filter((edge) => edge.reexport).map((edge) => edge.target.name),
344 ),
345 )
346 }
347 edges.set(production.name, [])
348 reexports.set(production.name, new Set())
349 const modules = [...oracles, ...supports, ...driver, production]
350 const ofKind = modules.filter((module) => module.kind === skeleton.hookKind)
351 const hookTarget =
352 skeleton.hookName ??
353 (ofKind.length === 0
354 ? RULE
355 : ofKind[skeleton.hookIndex % ofKind.length].name)
356 return {
357 oracles,
358 supports,
359 driver,
360 production,
361 ruleEdited: skeleton.ruleEdited,
362 edges,
363 reexports,
364 modules,
365 hookTarget,
366 }
367}
368
369/**
370 * The files that each scope treats as edited. The changed scope sees every
371 * edited tracked module and every untracked file. The named scope, which the
372 * pre-commit hook runs, sees the files it is given: the edited tracked modules.
373 * It runs only when there is one: the hook never runs it without files.
374 * The edit hook sees the one file that the hook input names.
375 */
376function editedByScope(program) {
377 const tracked = program.modules
378 .filter((module) => module.edited)
379 .map((module) => module.name)
380 const untracked = program.modules
381 .filter((module) => module.untracked)
382 .map((module) => module.name)
383 const rule = program.ruleEdited ? [RULE] : []
384 return {
385 changed: [...tracked, ...untracked, ...rule],
386 named: [...tracked, ...rule],
387 hook: [program.hookTarget],
388 }
389}
390
391// -- 2. Model -----------------------------------------------------------------
392//
393// The model reads only the graph. It grows the set of affected modules to a
394// fixed point: an edited test module is affected, and so is every module with
395// an edge into an affected module. Production is never affected, because the
396// rule never reads it, so an edge into production carries nothing. The oracle
397// files in the affected set are the ones to lint. When the edited files
398// include the rule's own source, every oracle file must be linted.
399
400/** The oracle files that a lint of `edited` must cover, as sorted basenames. */
401function predictSelected(program, edited) {
402 if (edited.includes(RULE))
403 return program.oracles.map((oracle) => oracle.name).sort()
404 const affected = new Set(edited.filter((name) => name !== PRODUCTION))
405 let grew = true
406 while (grew) {
407 grew = false
408 for (const [from, targets] of program.edges) {
409 if (affected.has(from)) continue
410 if (targets.some((target) => affected.has(target))) {
411 affected.add(from)
412 grew = true
413 }
414 }
415 }
416 return program.oracles
417 .filter((oracle) => affected.has(oracle.name))
418 .map((oracle) => oracle.name)
419 .sort()
420}
421
422// -- 3. Driver ----------------------------------------------------------------
423//
424// The driver runs the lint script that a developer or hook runs. It writes the
425// modules and the copy of the script and the rule into a temporary repository,
426// commits the tracked modules, edits them in the working tree, and writes the
427// untracked oracle files. It runs the changed scope (`lint:changed`), the named
428// scope (the pre-commit hook), and the edit hook in that one repository: the
429// hook selects from the file its input names, not from the working tree's
430// edits. Each report line names its oracle file. The driver reads those names;
431// it does not compute them. An exit status or stderr that is not a report is a
432// failed run, so a crashed script cannot pass as an empty selection.
433
434/** The text of one module, with or without its edit. */
435function moduleText(program, module, edited) {
436 const lines = []
437 const reexported = program.reexports.get(module.name) ?? new Set()
438 for (const target of program.edges.get(module.name) ?? []) {
439 const spec =
440 target === PRODUCTION
441 ? `../src/prod.js`
442 : `./${target.replace(/\.ts$/, module.kind === `oracle` && module.style === 1 ? `.js` : ``)}`
443 lines.push(
444 reexported.has(target) ? `export * from '${spec}'` : `import '${spec}'`,
445 )
446 }
447 if (module.kind === `oracle`) {
448 lines.push(`it('reads one value', () => { expect(1).toBe(1) })`)
449 }
450 if (module.kind === `production`) lines.push(`export const prod = 1`)
451 if (edited) lines.push(`// edited`)
452 return `${lines.join(`\n`)}\n`
453}
454
455let work
456let pluginDir
457let feedbackScript
458let runCountScript
459
460beforeAll(() => {
461 // Each run has its own directory, so concurrent runs cannot remove each
462 // other's repositories. The real path keeps the file names that the driver
463 // passes in the spelling that the script's repository root uses.
464 work = realpathSync(mkdtempSync(join(tmpdir(), `lint-scope-oracle-`)))
465 pluginDir = join(repoRoot, `scripts`, `eslint-plugin-oracle`)
466 // A mutant is run from a copy: LINT_SCOPE_SCRIPT names the copy under test.
467 feedbackScript =
468 process.env.LINT_SCOPE_SCRIPT ??
469 join(repoRoot, `scripts`, `agent-lint-feedback.mjs`)
470 runCountScript = join(repoRoot, `scripts`, `check-oracle-run-counts.mjs`)
471})
472
473afterAll(() => {
474 rmSync(work, { recursive: true, force: true })
475})
476
477/** Writes the base files, commits them, then writes the edited working tree. */
478function repositoryOf(program) {
479 const directory = mkdtempSync(join(work, `r`))
480 const git = (...args) =>
481 execFileSync(
482 `git`,
483 [
484 `-c`,
485 `user.name=oracle`,
486 `-c`,
487 `user.email=oracle@example.invalid`,
488 ...args,
489 ],
490 {
491 cwd: directory,
492 encoding: `utf8`,
493 stdio: [`ignore`, `pipe`, `pipe`],
494 },
495 )
496 git(`init`, `-q`, `-b`, `main`)
497 writeFileSync(
498 join(directory, `package.json`),
499 // The repository's root is an ES module package, as here.
500 JSON.stringify({ name: `root`, type: `module` }),
501 )
502 mkdirSync(join(directory, APP, `tests`), { recursive: true })
503 mkdirSync(join(directory, APP, `src`), { recursive: true })
504 writeFileSync(
505 join(directory, APP, `package.json`),
506 JSON.stringify({ name: `app` }),
507 )
508 // The plugin's sources, without its tests: its own oracle file would be an
509 // oracle file of this repository too.
510 cpSync(pluginDir, join(directory, `scripts`, `eslint-plugin-oracle`), {
511 recursive: true,
512 filter: (source) => !source.endsWith(`.test.js`),
513 })
514 writeFileSync(
515 join(directory, `scripts`, `agent-lint-feedback.mjs`),
516 readFileSync(feedbackScript, `utf8`),
517 )
518 writeFileSync(
519 join(directory, `scripts`, `check-oracle-run-counts.mjs`),
520 readFileSync(runCountScript, `utf8`),
521 )
522 const pathOf = (name) =>
523 name === RULE
524 ? join(directory, RULE)
525 : name === PRODUCTION
526 ? join(directory, APP, `src`, `prod.ts`)
527 : join(directory, APP, `tests`, name)
528 for (const module of program.modules) {
529 if (!module.untracked)
530 writeFileSync(pathOf(module.name), moduleText(program, module, false))
531 }
532 git(`add`, `-A`)
533 git(`commit`, `-q`, `-m`, `base`)
534 symlinkSync(join(repoRoot, `node_modules`), join(directory, `node_modules`))
535 for (const module of program.modules) {
536 if (module.edited || module.untracked)
537 writeFileSync(pathOf(module.name), moduleText(program, module, true))
538 }
539 if (program.ruleEdited) {
540 const rule = pathOf(RULE)
541 writeFileSync(rule, `${readFileSync(rule, `utf8`)}\n// edited\n`)
542 }
543 return { directory, pathOf }
544}
545
546const lintLine = /^(\S+?):\d+:\d+ .* \((oracle\/[\w-]+|parse)\)$/
547const budgetLine = /^\S+: .+: run budget (lowered|removed) /
548
549/** The oracle basenames in a report's lint lines. */
550function reportedOracles(lines) {
551 const found = new Set()
552 for (const line of lines) {
553 const match = lintLine.exec(line)
554 if (match !== null) found.add(match[1].split(`/`).pop())
555 }
556 return [...found].sort()
557}
558
559/**
560 * Runs the CLI and returns the oracle files that it reported. In text format
561 * the CLI exits 0 with no output, or 1 with report lines on stderr. As a
562 * Claude edit hook it exits 0 with no output, or 2 with a report on stderr.
563 * Anything else, such as a crash, which exits 1 with a stack trace, fails.
564 */
565function runCli(directory, args, input) {
566 const result = spawnSync(
567 process.execPath,
568 [`scripts/agent-lint-feedback.mjs`, ...args],
569 { cwd: directory, encoding: `utf8`, input },
570 )
571 const lines = result.stderr.split(`\n`).filter(Boolean)
572 const hook = args.includes(`--format=claude`)
573 const reported = hook ? 2 : 1
574 const valid =
575 result.stdout === `` &&
576 (result.status === 0
577 ? lines.length === 0
578 : result.status === reported &&
579 (hook
580 ? lines[0]?.startsWith(`Oracle lint reports`)
581 : lines.every(
582 (line) => lintLine.test(line) || budgetLine.test(line),
583 )))
584 if (!valid) {
585 throw new Error(`cli failed (exit ${result.status}):\n${result.stderr}`)
586 }
587 return reportedOracles(lines)
588}
589
590/** The oracle files that each scope lints, from one repository. */
591function observedSelections(program) {
592 const { directory, pathOf } = repositoryOf(program)
593 try {
594 const scopes = editedByScope(program)
595 const changed = runCli(directory, [`--format=text`])
596 // lint-staged runs the named scope once per nonempty chunk of staged
597 // files; without files the script runs its changed scope instead.
598 const named =
599 scopes.named.length === 0
600 ? undefined
601 : runCli(directory, [
602 `--format=text`,
603 ...scopes.named.map((name) => pathOf(name)),
604 ])
605 const input = JSON.stringify({
606 tool_input: { file_path: pathOf(program.hookTarget) },
607 })
608 const hook = runCli(directory, [`--format=claude`, `--event=edit`], input)
609 return { changed, named, hook }
610 } finally {
611 rmSync(directory, { recursive: true, force: true })
612 }
613}
614
615// -- 4. Comparison ------------------------------------------------------------
616//
617// Each observed selection must equal the model's prediction for its scope, as
618// sorted basenames. The check reports the first oracle file that the script
619// linted or missed, so a failure names the oracle file whose lint scope
620// diverged.
621
622/** Each observation equals the model's prediction, as sorted basenames. */
623function compareSelected(observed, expected) {
624 expect(observed).toEqual(expected)
625}
626
627// -- 5. Reach -----------------------------------------------------------------
628//
629// The states below are coverage of the graph, not a second model. A path is a
630// simple path of imports from one oracle file. A state counts once per history:
631// direct-dependent: a one-import path from an oracle file to an edited module.
632// transitive-dependent: a longer path of test modules to an edited module.
633// re-export-dependent: a re-export decides the selection: without the
634// re-export edges, the model selects fewer oracle files.
635// oracle-dependent: an oracle file reaches an edited module only through
636// another oracle file.
637// oracle-edit: an oracle file that is itself edited.
638// unrelated-edit: an edited test module that no oracle file reaches.
639// production-boundary: an edited production module that an oracle file reaches.
640// rule-edit: the rule's sources changed, so every oracle file is selected.
641// untracked-dependent: an untracked oracle file reaches the hook's file.
642// js-oracle: a JavaScript oracle file is selected.
643// hook-oracle, hook-support, hook-driver, hook-production, hook-rule: the
644// kind of file that the edit hook names.
645
646const STATES = [
647 `direct-dependent`,
648 `transitive-dependent`,
649 `re-export-dependent`,
650 `oracle-dependent`,
651 `oracle-edit`,
652 `unrelated-edit`,
653 `production-boundary`,
654 `rule-edit`,
655 `untracked-dependent`,
656 `js-oracle`,
657 `hook-oracle`,
658 `hook-support`,
659 `hook-driver`,
660 `hook-production`,
661 `hook-rule`,
662]
663const reach = createOracleReach(PROPERTY, STATES, { minimum: 2 })
664
665/** Every simple path of imports from `start`, as its list of modules. */
666function pathsFrom(program, start) {
667 const found = []
668 const walk = (node, nodes) => {
669 for (const target of program.edges.get(node) ?? []) {
670 if (nodes.includes(target)) continue
671 const path = [...nodes, target]
672 found.push(path)
673 if (target !== PRODUCTION) walk(target, path)
674 }
675 }
676 walk(start, [start])
677 return found
678}
679
680/** The program with some edges removed. */
681function withoutEdges(program, drop) {
682 return {
683 ...program,
684 edges: new Map(
685 [...program.edges].map(([from, targets]) => [
686 from,
687 targets.filter((target) => !drop(from, target)),
688 ]),
689 ),
690 }
691}
692
693/** Marks the states that the program enters. */
694function recordStates(program) {
695 reach.beginHistory()
696 const states = new Set()
697 const { changed, hook } = editedByScope(program)
698 const edited = new Set(changed)
699 if (program.ruleEdited) states.add(`rule-edit`)
700 const reached = new Set()
701 for (const oracle of program.oracles) {
702 if (oracle.edited) states.add(`oracle-edit`)
703 for (const path of pathsFrom(program, oracle.name)) {
704 for (const node of path) reached.add(node)
705 const end = path.at(-1)
706 if (!edited.has(end)) continue
707 if (end === PRODUCTION) {
708 states.add(`production-boundary`)
709 continue
710 }
711 states.add(
712 path.length === 2 ? `direct-dependent` : `transitive-dependent`,
713 )
714 }
715 }
716 const selected = predictSelected(program, changed).length
717 const oracleNames = new Set(program.oracles.map((oracle) => oracle.name))
718 if (
719 predictSelected(
720 withoutEdges(program, (from, target) =>
721 program.reexports.get(from)?.has(target),
722 ),
723 changed,
724 ).length < selected
725 )
726 states.add(`re-export-dependent`)
727 if (
728 predictSelected(
729 withoutEdges(program, (_, target) => oracleNames.has(target)),
730 changed,
731 ).length < selected
732 )
733 states.add(`oracle-dependent`)
734 for (const module of program.modules) {
735 const testModule = module.kind !== `production` && module.kind !== `oracle`
736 if (module.edited && testModule && !reached.has(module.name)) {
737 states.add(`unrelated-edit`)
738 }
739 }
740 const hookSelected = new Set(predictSelected(program, hook))
741 if (
742 program.oracles.some(
743 (oracle) =>
744 oracle.untracked &&
745 oracle.name !== program.hookTarget &&
746 hookSelected.has(oracle.name),
747 )
748 )
749 states.add(`untracked-dependent`)
750 if (
751 program.oracles.some(
752 (oracle) =>
753 oracle.name.endsWith(`.js`) &&
754 predictSelected(program, changed).includes(oracle.name),
755 )
756 )
757 states.add(`js-oracle`)
758 const target = program.modules.find(
759 (module) => module.name === program.hookTarget,
760 )
761 states.add(`hook-${target?.kind ?? `rule`}`)
762 for (const state of states) reach.reach(state)
763}
764
765function campaign(name) {
766 // A history runs its child processes synchronously, so the predicate yields
767 // between complete histories: the test worker then answers its progress
768 // messages, and a long campaign cannot time out the worker's RPC channel.
769 const predicate = async (program) => {
770 await setImmediate()
771 recordStates(program)
772 const observed = observedSelections(program)
773 const scopes = editedByScope(program)
774 compareSelected(observed.changed, predictSelected(program, scopes.changed))
775 if (observed.named !== undefined)
776 compareSelected(observed.named, predictSelected(program, scopes.named))
777 compareSelected(observed.hook, predictSelected(program, scopes.hook))
778 }
779 it(`${name}: fixed-seed campaign`, async () => {
780 await fc.assert(fc.asyncProperty(programArbitrary, predicate), {
781 numRuns: oracleRuns(BASE_RUNS),
782 seed: FIXED_SEED,
783 })
784 }, 1_200_000)
785 it(`${name}: random-seed campaign`, async () => {
786 await fc.assert(
787 fc.asyncProperty(programArbitrary, predicate),
788 oraclePropertyOptions(BASE_RUNS, PROPERTY),
789 )
790 }, 1_200_000)
791}
792
793describe(`lint selection after an edit`, () => {
794 campaign(`changed, named, and edit-hook scopes`)
795 // Every declared state must be entered by the campaigns above.
796 afterAll(() => {
797 if (process.env.TANSTACK_DB_ORACLE_REACH_REPORT)
798 console.log(`REACH`, JSON.stringify([...reach.counts()]))
799 reach.assertReached()
800 })
801})
802
803// The declaration names the parts above. It runs nothing, so it follows them.
804declareOracle({
805 model: [predictSelected],
806 check: [compareSelected],
807 grammar: [programArbitrary],
808})