Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

lint-scope-oracle.property.test.js

949 lines34.2 KB

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