diff --git a/.changeset/gap-cli-daemon-every-read.md b/.changeset/gap-cli-daemon-every-read.md
new file mode 100644
index 00000000..1f33e998
--- /dev/null
+++ b/.changeset/gap-cli-daemon-every-read.md
@@ -0,0 +1,15 @@
+---
+'@tanstack/oracles': patch
+---
+
+A check through `--daemon` now treats each tracked read as an input of the runs that made it, so after any change to a tracked input it reports what a cold run reports. Reads that stay untracked are listed below. Before, the daemon reused a run that read the old input. The new inputs are a file that a test reads through `fs` outside the package or under `node_modules`, or through `createReadStream`; a directory that a test lists (`readdir`, `opendir`, and their sync and `fs/promises` forms), by its entries; an environment variable that a test reads (or the set of variable names, when a test lists them); and a file or variable that Vitest, Vite, or the config reads in the CLI's process, while it loads or in a hook of any plugin, Vite's own included, such as the `tsconfig.json` that Vite's esbuild plugin reads or a sidecar file that a plugin writes into the code it transforms.
+
+The daemon now runs each check in the environment of the CLI that asked for it. A check from another environment, or after a file that Vitest, the config, or a plugin read or wrote has changed, starts a new daemon. Because Vitest and Vite read every environment variable while they start, any change to the environment runs every unit again, as a cold run does.
+
+Each check now hashes every file input from its content, so an edit that keeps a file's size and modification time, as `cp -p`, `rsync -t`, or `touch -r` leave it, is no longer missed. A test that stats a file by its size or times has that metadata as an input too, while a directory's stat is an input by its kind alone.
+
+A file that a test, or a Node process or worker thread it started at any depth, wrote before the test read it is the test's own output and no input, so a test whose child writes a temporary file is reused on an unchanged check.
+
+Not every read is tracked yet. These stay untracked, and the README lists them: a read through a file descriptor, a link's target, the other stat calls, `glob`, `copyFile` and `cp`; a directory's own metadata; a child process started with an environment that drops `NODE_OPTIONS`, and a writer that is not Node. Run the check cold after an edit to one of them. Vitest's own discovery listings are left out on purpose.
+
+The CLI sends its environment to its daemon's socket only when this user owns that socket, so another user's listener in the shared temporary directory cannot receive it.
diff --git a/README.md b/README.md
index ef918068..ab97f1f6 100644
--- a/README.md
+++ b/README.md
@@ -266,39 +266,83 @@ runs cold` and runs the check in its own process, which reports what the
run's output directory, and serves the next check. On Windows, which has no process groups, the run is not
supervised.
- A check through the daemon reuses a run while its inputs are unchanged:
- the modules the run loaded, and the files in the package that its tests
- read through `fs` (`readFileSync`, `readFile`, `existsSync`, `statSync`,
- and `fs/promises` `readFile` and `stat`), each by the content that the
- run read. A run that an edit overlapped, because a file changed after the
- run read it, is not reused. A directory that a test stats or tests for is
- an input as a directory, not by its content.
-
- Two kinds of input are not tracked yet. A Vite plugin whose output depends
- on anything but a module's text, such as a sidecar file that it reads, can
- make the daemon serve a run that read the plugin's old output. And the
- daemon's environment is fixed when it starts, so an environment variable
- that a later check sets does not reach the daemon's runs. After such a
- change, run the check cold (without `--daemon`), or stop the daemon with
- `oracle-gaps --stop-daemon --package
`. The maintainer decided on
- 2026-11-13 that the daemon tracks both and restarts when they change; a
- later release does that.
-
- These reads are no input, so an edit to the file alone does not rerun the
- tests that read it: a read outside the package or under `node_modules`; a
- read from a worker thread or child process that the test starts; and a
- read through any `fs` or `fs/promises` function other than the six above,
- or through one of those six given a file descriptor. That catch-all
- includes, for example, `readdir`, `opendir`, `glob`, `globSync`,
- `createReadStream`, `realpath`, `lstat`, `access`, `open`, `read`,
- `readSync`, `readv`, `fstat`, `fstatSync`, `copyFile`, `copyFileSync`, `cp`,
- `cpSync`, `openAsBlob`, `statfs`, `readlink`, the callback `stat`,
- `exists`, `watch`, and `watchFile`, and the `fs/promises` `readdir`,
- `opendir`, `glob`, `lstat`, `realpath`, `readlink`, `access`, `open`,
- `copyFile`, `cp`, `statfs`, and `watch`. Run the check cold (without
- `--daemon`) after an edit to a file read that way. A later release records
- all of them except `watch` and `watchFile`, which wait for future changes
- and stay no input (maintainer decision, 2026-11-13, with `watchFile` in the
+ A check through the daemon reuses a run while its inputs are unchanged.
+ Every read is an input (maintainer decision, 2026-11-16): the modules the
+ run loaded; the files its tests read through `fs` on any path, inside the
+ package or outside it, `node_modules` included (`readFileSync`,
+ `readFile`, `createReadStream`, and `fs/promises` `readFile`), each by the
+ content that the run read; the files its tests stat, by their existence
+ and kind (`existsSync`), or by their size, times, identity, and mode
+ (`statSync`, `stat` with or without a callback, and `fs/promises` `stat`),
+ where a directory's stat is an input by its kind alone, so a directory's
+ own size or times are not (a limit, CR-13); the directories its tests list
+ (`readdir`, `readdirSync`, `opendir`,
+ `opendirSync`, and `fs/promises` `readdir` and `opendir`), each by its
+ entries' names and kinds; the environment variables its tests read, by
+ value, or all of them when a test lists them; and what Vitest, Vite, and
+ the config read in the CLI's process, while Vitest loads and the contexts
+ warm, and in each hook of every plugin, Vite's own (such as the
+ `tsconfig.json` that its esbuild plugin reads) and the config's alike. A
+ file that a reader wrote earlier in the check, before it read it or tested
+ whether it exists, is its own output and no input (maintainer decision,
+ 2026-11-17). For a test, that includes a file that a Node process it
+ started wrote, at any depth: each such process preloads the runner's
+ write log through `NODE_OPTIONS` (maintainer decision, 2026-11-19). A
+ child started with an environment that drops `NODE_OPTIONS`, or a writer
+ that is not Node, is not seen, so its file stays an input. A file the
+ session wrote that is edited by hand afterwards is seen. Each check hashes
+ every file input from its content, so an edit that keeps a file's size and
+ modification time (`cp -p`, `rsync -t`, `touch -r`) is seen. A run that an
+ edit overlapped, because a file changed after the run read it, is not
+ reused. A directory that a test stats or tests for is an input as a
+ directory, not by its content.
+
+ A path that a run's own process tree wrote, created or copied before the
+ read, is no input, and a directory the run added entries to is no input;
+ mkdir and mkdtemp count as writes (accepted 2026-12-02, maintainer). A path
+ the run read present and then changed, which the tree did not write first,
+ is an input that moved. Limit, accepted 2026-12-02 (maintainer): a later run
+ that finds a leftover of an earlier run at such a path reuses the stored run,
+ so a test whose outcome depends on that leftover is not hermetic.
+
+ The CLI sends its environment with each request, so it sends it only to a
+ daemon socket that this user owns; a socket another user made in the
+ shared temporary directory is refused, and no request goes to it. On
+ Windows, a named pipe has no owner check here.
+
+ The daemon runs every check in the environment that the CLI asking for it
+ has. While a context warms, Vitest and Vite read every environment
+ variable by value, so a check from an environment that differs in any
+ variable, even one no test reads (`OLDPWD`, `SHLVL`, a terminal's session
+ id), starts a new daemon and runs every unit again, as a cold run does.
+ So does a check after a file that Vitest, the config, or a plugin read or
+ wrote has changed.
+
+ The harness gives each worker thread and each child process that a test
+ starts its preload, at any depth (a worker started by a worker included),
+ so their reads are inputs too. A `require` in a test
+ consults the `package.json` files that decide a package's `main` and
+ `type`; Node reads them itself, so the harness records them through a
+ wrapper on `Module._resolveFilename`, a private Node API (check.mjs says
+ what changes if a Node version alters it). A child process that
+ the test starts with an environment that drops `NODE_OPTIONS` is not
+ watched (#143). A file that the runner created for the run (its capture
+ rows and its `test-output.log`) is the runner's output: an append to one
+ of them reads nothing first, and a plain read of either is still an input.
+
+ These reads are no input yet, so an edit to the file alone does not rerun
+ the tests that read it: a read through a file descriptor, after `open`,
+ `openSync`, or the `fs/promises` `open` (#141); a link's target, or the
+ rest of the stat family, `lstat`, `readlink`, `realpath`, `access`, and
+ `exists` (#142); `glob`, `globSync`, `copyFile`,
+ `copyFileSync`, `cp`, `cpSync`, `openAsBlob`, `statfs`, and the
+ `fs/promises` `glob`, `copyFile`, `cp`, and `statfs` (#152); the
+ module-level reads of a test file whose tests are all skipped (#153); and
+ the earlier content of a file that a test partly writes or fails to write,
+ then reads. Run the check cold (without `--daemon`)
+ after an edit to a file read that way. A later release records all of
+ them except `watch` and `watchFile`, which wait for future changes and
+ stay no input (maintainer decision, 2026-11-13, with `watchFile` in the
family of `watch`).
- `packages/eslint-plugin-oracles` (`@tanstack/eslint-plugin-oracles`): the
diff --git a/packages/oracles/oracle-gaps/capture-setup.mjs b/packages/oracles/oracle-gaps/capture-setup.mjs
index 48394b19..841254ad 100644
--- a/packages/oracles/oracle-gaps/capture-setup.mjs
+++ b/packages/oracles/oracle-gaps/capture-setup.mjs
@@ -25,16 +25,30 @@
// of shrinking it: a kill needs one failing history, not the smallest one.
import { createHook } from 'node:async_hooks'
import { createHash } from 'node:crypto'
+import fs, {
+ appendFileSync,
+ closeSync,
+ existsSync,
+ fstatSync,
+ openSync,
+ readFileSync,
+ readSync,
+} from 'node:fs'
import { once } from 'node:events'
-import fs, { appendFileSync, readFileSync } from 'node:fs'
import { createRequire, syncBuiltinESMExports } from 'node:module'
import { connect, createServer } from 'node:net'
import { tmpdir } from 'node:os'
import { dirname, isAbsolute, join, resolve as resolvePath } from 'node:path'
-import { fileURLToPath } from 'node:url'
+import { fileURLToPath, pathToFileURL } from 'node:url'
import { threadId } from 'node:worker_threads'
import { afterAll, beforeEach, chai, expect, inject, vi } from 'vitest'
-import { posix, writeWhole } from './paths.mjs'
+import {
+ inputHash,
+ keepProperties,
+ patchWorkerThreads,
+ watchReads,
+} from './inputs.mjs'
+import { writeWhole } from './paths.mjs'
const run =
inject(`oracleGaps`) ??
@@ -71,14 +85,7 @@ const realNow = real.now
// A wrapper keeps every own property of the function it wraps, such as
// `util.promisify.custom`, so `util.promisify(setTimeout)` still resolves
-// with its value under the capture (law 3: a test that passes alone passes
-// under the CLI).
-function keepProperties(from, to) {
- for (const key of Reflect.ownKeys(from))
- if (key !== `prototype`)
- Object.defineProperty(to, key, Object.getOwnPropertyDescriptor(from, key))
- return to
-}
+// with its value under the capture (inputs.mjs, keepProperties).
// The paths to the clock, wrapped once per worker, before any test file
// loads, each telling the copy now running (`__oracleGapsClock`): a timer or
@@ -243,69 +250,183 @@ function appendClosingRow(row) {
writeWhole(`${hold}.${marker}`, ``)
appendFileSync(state.capture, row.slice(half))
}
-// The files this copy reads through fs inside the package: by a sync, a
-// promise, or a callback read, or a check of whether a file exists or what
-// it is. The daemon stores the run under them as it does the modules the
-// copy evaluated (the closing row's `loaded`), so an edit of only such a
-// file runs it again, as a cold run sees the edit (law 9). Reads under
-// node_modules and of the runner's own files are left out. Each path keeps
-// its hash from the copy's first read of it, taken as the runner hashes an
-// input (check.mjs, fileHashes), so the run is stored under the text it
-// read and not under an edit that lands later in the run (review of #55,
-// F1).
+// What this copy reads: each file through fs, on any path, node_modules
+// included, by a sync, a promise, or a callback read, or a check of whether
+// a file exists or what it is; and each environment variable, or the set of
+// names when the copy lists them (inputs.mjs). Every read is a daemon input
+// (maintainer decision, 2026-11-16): the daemon stores the run under them as
+// it does the modules the copy evaluated (the closing row's `loaded`), so an
+// edit of only such an input runs it again, as a cold run sees the edit
+// (law 9). A file keeps its hash from the copy's first read of it, so the
+// run is stored under the text it read and not under an edit that lands
+// later in the run (review of #55, F1). A variable's hash is the runner's,
+// from the environment it gives the check (check.mjs, servedHash). A file
+// that the copy, or a process it started at any depth, wrote before the copy
+// read it is its own output, no input, whether the copy reads its text or
+// tests whether it exists (`stat:`).
globalThis.__oracleGapsReads = new Map()
-if (!globalThis.__oracleGapsReading) {
- globalThis.__oracleGapsReading = true
- // A read's key follows the gap CLI's path rule (paths.mjs, copied beside
- // this file with it). The file system gets the native path.
- const root = `${posix(process.cwd()).replace(/\/+$/, ``)}/`
- const { readFileSync: readNow, statSync: statNow } = fs
- const hashNow = (path) => {
- try {
- return statNow(path).isFile()
- ? createHash(`sha1`).update(readNow(path)).digest(`hex`)
- : `not a file`
- } catch {
- return `missing`
- }
+const wrote = new Set()
+// The child processes' writes: every Node process a test starts preloads
+// child-writes.mjs, which each of its own children inherits through
+// NODE_OPTIONS, and appends the key of each file it writes to this copy's
+// log, in the session directory beside this file.
+// The session directory, from this file's path. Not `new URL(,
+// import.meta.url)`: a client-transform environment (jsdom) rewrites that
+// form to a URL of Vite's dev server.
+const home = dirname(fileURLToPath(import.meta.url))
+const childLog = join(
+ home,
+ `child-writes-${process.pid}-${threadId}-${(globalThis.__oracleGapsCopies = (globalThis.__oracleGapsCopies ?? 0) + 1)}.log`,
+)
+let childRead = 0
+/**
+ * Folds the log lines that the copy's process tree wrote since the last fold,
+ * in the order they were written (child-writes.mjs). A child's read of a file
+ * that the tree had not written is an input of the copy, with the hash the
+ * child took at that read; a child's write makes the file the tree's own
+ * output. A line still being written waits for the next fold (133-2).
+ */
+function foldChildren() {
+ // Only the bytes after the last fold (`childRead`), so a check's folds cost
+ // what the tree wrote since the last one, not the whole log (review of #133,
+ // 133-15).
+ let text
+ let fd
+ try {
+ fd = openSync(childLog, `r`)
+ const size = fstatSync(fd).size
+ if (size <= childRead) return
+ const chunk = Buffer.alloc(size - childRead)
+ readSync(fd, chunk, 0, chunk.length, childRead)
+ text = chunk.toString(`utf8`)
+ } catch {
+ return
+ } finally {
+ if (fd !== undefined) closeSync(fd)
}
- const record = (target) => {
- let path
- try {
- if (target instanceof URL) path = fileURLToPath(target)
- else if (typeof target === `string`) path = resolvePath(target)
- else if (Buffer.isBuffer(target)) path = resolvePath(target.toString())
- } catch {
- return
- }
- if (path === undefined) return
- const key = posix(path)
- const reads = globalThis.__oracleGapsReads
- if (
- key.startsWith(root) &&
- !key.includes(`/node_modules/`) &&
- !key.includes(`/.oracle-gaps`) &&
- !reads.has(key)
- )
- reads.set(key, hashNow(path))
+ const end = text.lastIndexOf(`\n`)
+ if (end < 0) return
+ const reads = globalThis.__oracleGapsReads
+ for (const line of text.slice(0, end).split(`\n`)) {
+ if (line === ``) continue
+ const [op, key, hash] = JSON.parse(line)
+ if (op === `W`) wrote.add(key)
+ // A child's stat or listing of a path the tree wrote before it is the
+ // tree's own output too: its key names the file, as ownOutput maps it.
+ else if (!wrote.has(ownKeyOf(key)) && !reads.has(key)) reads.set(key, hash)
}
- // A wrapper keeps the function's own properties (its name and length,
- // which code that dispatches on arity reads), so a test that passes alone
- // passes under the capture (law 3; review of #55).
- for (const [owner, names] of [
- [fs, [`readFileSync`, `readFile`, `existsSync`, `statSync`]],
- [fs.promises, [`readFile`, `stat`]],
- ])
- for (const name of names) {
- const original = owner[name]
- owner[name] = keepProperties(original, function (target, ...rest) {
- record(target)
- return original.call(this, target, ...rest)
- })
- }
- // An ES module's `import { readFileSync } from 'node:fs'` (and from
- // 'node:fs/promises') reads these from now on.
- syncBuiltinESMExports()
+ childRead += Buffer.byteLength(text.slice(0, end + 1))
+}
+/**
+ * Whether the copy or a process it started wrote the file that `key` names:
+ * a stat of a file is a read of the file (`stat:` and `statx:`).
+ */
+function ownOutput(key) {
+ foldChildren()
+ return wrote.has(ownKeyOf(key))
+}
+// The write log's key for a read's key: a stat, metadata, or listing of a path
+// names the path, which the log keys as `fs:` (the tree's writes and makes).
+function ownKeyOf(key) {
+ return key.replace(/^(stat|statx|dirs?):/, `fs:`)
+}
+// Rule: an append to the run's own capture rows or test-output.log reads
+// nothing first, since the runner created that file for this run, so its
+// text is the run's own output and not an input. The reuse miss of #133: the
+// log's first pre-read was recorded as missing, the log grew while the run
+// settled, so the unit was never stored. A plain read of either file is
+// still an input.
+const posixOf = (path) =>
+ process.platform === `win32` ? path.replaceAll(`\\`, `/`) : path
+function isRunnerOwnAppend(key, write) {
+ if (write !== `append` || !state.capture || key.startsWith(`env:`))
+ return false
+ const own = [state.capture, join(dirname(state.capture), `test-output.log`)]
+ const path = key.slice(key.indexOf(`:`) + 1)
+ return own.some((file) => path === posixOf(file))
+}
+watchReads((key, write) => {
+ // The child reads that came before this event fold first, so each is
+ // judged, in its order, before this read tests the tree's writes and the
+ // reads (CR-16: a child's earlier hash must not be overwritten here).
+ foldChildren()
+ const reads = globalThis.__oracleGapsReads
+ // A read, or the read that a write which keeps its bytes makes before the
+ // write (`append`, 133-3, CR-21), is an input unless the copy or its process
+ // tree wrote the file first, or the append is the runner's own
+ // (isRunnerOwnAppend). A write marks the file once it has succeeded (`true`).
+ if (
+ write !== true &&
+ !isRunnerOwnAppend(key, write) &&
+ !reads.has(key) &&
+ !wrote.has(key) &&
+ !ownOutput(key)
+ )
+ reads.set(key, key.startsWith(`env:`) ? null : inputHash(key))
+ if (write === true) wrote.add(key)
+})
+if (!globalThis.__oracleGapsChildren) {
+ globalThis.__oracleGapsChildren = true
+ process.env.NODE_OPTIONS =
+ `${process.env.NODE_OPTIONS ?? ``} --import=${pathToFileURL(join(home, `child-writes.mjs`)).href}`.trim()
+}
+process.env.ORACLE_GAPS_CHILD_WRITES = childLog
+// Node resolves a require without fs: the package.json files that decide a
+// request's main (its directory's) and type (the resolved file's package
+// scope) are read by Node itself, so the fs wrapper never sees them (probed:
+// editing a sub's main changed the module, and no fs read showed it). This
+// wraps Module._resolveFilename, Node's private resolver, in this realm. Each
+// resolution records the package.json files it consults, from the request's
+// candidate and from the resolved file's directory, up to the first that
+// exists (a missing one is recorded too), as inputs. The check (check.mjs,
+// the header) says what the oracle shows if a Node version renames it.
+const { Module } = createRequire(import.meta.url)(`node:module`)
+if (typeof Module?._resolveFilename !== `function`)
+ throw new Error(
+ `oracle-gaps: this Node has no Module._resolveFilename, so a require's package.json inputs cannot be recorded (capture-setup.mjs)`,
+ )
+const resolveFilename = Module._resolveFilename
+// The package.json keys from `dir` upward, through the first that exists.
+function scopeKeysOf(dir) {
+ const keys = []
+ for (let at = dir; ; at = dirname(at)) {
+ const key = `fs:${posixOf(join(at, `package.json`))}`
+ keys.push(key)
+ if (inputHash(key) !== `missing` || dirname(at) === at) break
+ }
+ return keys
+}
+function recordScope(dir) {
+ // The child reads that came first fold before these reads are tested (CR-26).
+ foldChildren()
+ const reads = globalThis.__oracleGapsReads
+ for (const key of scopeKeysOf(dir))
+ if (!reads.has(key) && !wrote.has(key) && !ownOutput(key))
+ reads.set(key, inputHash(key))
+}
+Module._resolveFilename = function (request, parent, ...rest) {
+ const from = parent?.filename
+ const relative =
+ typeof request === `string` &&
+ from !== undefined &&
+ (request.startsWith(`.`) || isAbsolute(request))
+ if (relative) recordScope(join(dirname(from), request))
+ const result = resolveFilename.call(this, request, parent, ...rest)
+ if (typeof result === `string` && isAbsolute(result))
+ recordScope(dirname(result))
+ return result
+}
+// Worker threads (#143): a worker starts with the NODE_OPTIONS its process
+// had at start, not later ones, so the copy's preload (child-writes.mjs) is
+// given to each worker in its execArgv, as each child process gets it. The
+// class is replaced in this realm only, and the builtin's ESM exports are
+// synced, so a test's `import { Worker }` gets the wrapper. A worker whose
+// `env` is an object gets the log's name too.
+if (!globalThis.__oracleGapsWorkers) {
+ globalThis.__oracleGapsWorkers = true
+ // The patch (inputs.mjs) is the same one each preloaded process applies, so
+ // a worker started from a worker is covered too (CR-25).
+ patchWorkerThreads(join(home, `child-writes.mjs`))
}
// A test's own writes to the process's stdout and stderr (a debugging
// `process.stdout.write`) go to the run's test-output.log, beside its
@@ -1283,14 +1404,20 @@ afterAll(() => {
// The hash of each file the copy read, from its first read, under its own
// key (`fs:`): a test's read of a file is another input than the
// module that its context serves from that file, which can differ from
- // the file's text (fourth review of #55, F-A2).
- const readAt = Object.fromEntries(
- [...globalThis.__oracleGapsReads].map(([path, hash]) => [
- `fs:${path}`,
- hash,
- ]),
- )
+ // the file's text (fourth review of #55, F-A2). A variable it read has no
+ // hash here (`env:`, null).
+ // The child processes' reads after the copy's last own read or write.
+ foldChildren()
+ const readAt = Object.fromEntries(globalThis.__oracleGapsReads)
+ // The files the copy or its process tree wrote or copied (`own`): the run's
+ // own output, which no input of the run is (check.mjs, settleIn).
+ const own = [...wrote]
+ .filter((key) => key.startsWith(`fs:`))
+ .map((key) => key.slice(`fs:`.length))
+ // A child process that lost a line of its log (child-writes.mjs) left the
+ // marker, so the run's reads are not all here (CR-19).
+ const childLost = existsSync(`${childLog}.lost`)
appendClosingRow(
- `${JSON.stringify({ file: thisFile, closed: true, at: realNow(), loaded, readAt, ...(skippedCopy ? { skipped: true } : {}) })}\n`,
+ `${JSON.stringify({ file: thisFile, closed: true, at: realNow(), loaded, readAt, own, childLost, ...(skippedCopy ? { skipped: true } : {}) })}\n`,
)
})
diff --git a/packages/oracles/oracle-gaps/check.mjs b/packages/oracles/oracle-gaps/check.mjs
index 846c4f36..30882283 100644
--- a/packages/oracles/oracle-gaps/check.mjs
+++ b/packages/oracles/oracle-gaps/check.mjs
@@ -13,16 +13,41 @@
// units, the ownership, and the options. A cold run computes every unit. The
// daemon keeps each unit in its evidence store with the hash of every module
// the run imported, as Vitest reports them, and of what was served for each
-// instrumented or patched source; a stored unit is reused only while every
-// one of those hashes is unchanged. So a check through the daemon reports
-// what a cold run reports (the CLI oracle's law 9). Not covered: a file a
-// test reads through `fs`, an environment variable other than the seed, and
-// a new file that changes how an unchanged import resolves.
+// instrumented or patched source, and of every other read the run made: a
+// file its tests read through `fs` on any path, a variable they read, and
+// what the config and its plugins read in this process (inputs.mjs; every
+// read is a daemon input, maintainer decision, 2026-11-16). A stored unit is
+// reused only while every one of those hashes is unchanged. So a check
+// through the daemon reports what a cold run reports (the CLI oracle's law
+// 9). Not covered: a read through another fs API than those inputs.mjs
+// watches, a read from a child process that a test starts with an environment
+// that drops NODE_OPTIONS (#143), and a new file that changes how an unchanged
+// import resolves. A worker thread a test starts is covered (capture-setup.mjs).
+// Own output (law 9, round 13, accepted 2026-12-02 (maintainer)): a path that
+// the run's own process tree wrote, created or copied before the read, is not
+// an input, and a directory the run added entries to is not an input; mkdir
+// and mkdtemp count as writes (inputs.mjs, capture-setup.mjs, settleIn). A path
+// the run read present and then changed, which the tree did not write first, is
+// an input that moved, so its run is not stored. Limit, accepted 2026-12-02
+// (maintainer): a later run that finds a leftover of an earlier run at such a
+// path reuses the stored run, so a test whose outcome depends on that leftover
+// is not hermetic, and not covered.
+// Vitest's own results cache is the runner's output (inputs.mjs isRunnerFile).
+// Node's own reads of the package.json files that a require consults (main,
+// type) are covered by a wrapper on Module._resolveFilename in the copy
+// (capture-setup.mjs). That is a private Node API, not a documented one: if a
+// Node version renames it, capture-setup.mjs throws at setup, so the copy and
+// the check fail loudly rather than run unwrapped; if Node changes its
+// behaviour so that the wrapper is bypassed, the package.json histories
+// (`an edit to the package.json main that a test requires`, and `type`) show it
+// as a daemon result that differs from the cold one (law 9, incremental equals
+// cold, RED on the unwrapped copy).
//
// A unit's identity also carries the global inputs: this CLI's own files,
// the harness, the Vite config and the files it loads, the package's
// manifest and the lockfile, the Node version, and the options that change a
// run (the seed, the test timeout, and bail).
+import { AsyncLocalStorage } from 'node:async_hooks'
import { spawn, spawnSync } from 'node:child_process'
import { createHash } from 'node:crypto'
import {
@@ -82,6 +107,19 @@ import {
specifierOf,
} from './paths.mjs'
import { stateDirOf } from './evidence.mjs'
+import { envHash, fileSha1, inputHash, watchReads } from './inputs.mjs'
+
+/**
+ * The URL a resolved module is imported from: its real path. Under Node's
+ * preserve-symlinks mode (NODE_PRESERVE_SYMLINKS=1, or --preserve-symlinks) a
+ * require resolves a package to its link, not its target, and an ESM import of
+ * the link does not find the dependencies that sit beside the target (pnpm
+ * links each package from node_modules/.pnpm): "Cannot find package
+ * '@vitest/utils'". The target is what Node imports by default, so the real
+ * path loads the same module in either mode.
+ */
+export const moduleUrlOf = (resolved) =>
+ pathToFileURL(realpathSync.native(resolved)).href
import {
baselineOf,
blockedOr,
@@ -203,6 +241,8 @@ const ownFiles = [
`stream.mjs`,
`authored.mjs`,
`capture-setup.mjs`,
+ `inputs.mjs`,
+ `child-writes.mjs`,
`paths.mjs`,
`evidence.mjs`,
`daemon.mjs`,
@@ -256,10 +296,67 @@ class KeepOrder {
}
}
-/** Hashes of files by content, memoized by size and modification time. */
+/**
+ * Every plugin of a resolved config, Vite's and Vitest's own as well as the
+ * config's, with each hook run under `reading` (openSession), so what a hook
+ * reads is a session input: the tsconfig.json that Vite's esbuild plugin
+ * reads is an input as a sidecar of the config's own plugin is (review of
+ * #133, F1). A `load` or `transform` hook names the module it serves. The
+ * runner's own plugin is left as it is. A plugin is wrapped once; a hook is
+ * a function or an object with a `handler`, as Vite takes it.
+ */
+const hooked = new WeakSet()
+function pluginHooks(plugins, reading, unrecorded) {
+ for (const option of plugins) {
+ if (option.name === `oracle-gaps-schemata` || hooked.has(option)) continue
+ hooked.add(option)
+ hookPlugin(option, reading, unrecorded)
+ }
+}
+function hookPlugin(option, reading, unrecorded) {
+ for (const [name, hook] of Object.entries(option)) {
+ const handler = typeof hook === `function` ? hook : hook?.handler
+ if (typeof handler !== `function`) continue
+ const at = { load: 0, transform: 1 }[name]
+ const watched = function (...args) {
+ const id = at === undefined ? undefined : args[at]
+ return reading.run(
+ {
+ hook: true,
+ module:
+ typeof id === `string`
+ ? `fs:${posix(id.split(`?`)[0])}`
+ : undefined,
+ // Vite's own plugins stat a path to learn only whether it is a file
+ // (resolution, as inputs.mjs's stat family says), so their metadata
+ // reads are kind reads: an edit of the file keeps its kind.
+ kindOnly: option.name.startsWith(`vite:`),
+ },
+ () => handler.apply(this, args),
+ )
+ }
+ // A frozen plugin object cannot take the wrapper: its assignment throws
+ // in this module's strict code. Its hooks are not recorded, so the check
+ // stores no unit of them, and names the plugin (CR-2).
+ try {
+ option[name] =
+ typeof hook === `function` ? watched : { ...hook, handler: watched }
+ } catch {
+ unrecorded.add(String(option.name))
+ return
+ }
+ }
+}
+
+/**
+ * Hashes of files by content, memoized by size and modification time for
+ * one check (`forget`, which each check calls first): an edit between two
+ * checks that keeps a file's size and modification time, as `cp -p` leaves
+ * it, is still seen (D10; the TLA model's weakened-stamp run).
+ */
function fileHashes() {
const memo = new Map()
- return (path) => {
+ const hashOf = (path) => {
let stat
try {
stat = statSync(path)
@@ -274,7 +371,7 @@ function fileHashes() {
if (known?.stamp === stamp) return known.hash
let hash
try {
- hash = sha1(readFileSync(path))
+ hash = fileSha1(path)
} catch {
// Removed between the stat and the read.
return `missing`
@@ -282,6 +379,8 @@ function fileHashes() {
memo.set(path, { stamp, hash })
return hash
}
+ hashOf.forget = () => memo.clear()
+ return hashOf
}
/** The lockfile that pins the package's dependencies, if any. */
@@ -341,9 +440,7 @@ export async function workspaceBundles(pkg) {
const requireVite = createRequire(
createRequire(join(pkg, `package.json`)).resolve(`vite`),
)
- const esbuild = await import(
- pathToFileURL(requireVite.resolve(`esbuild`)).href
- )
+ const esbuild = await import(moduleUrlOf(requireVite.resolve(`esbuild`)))
// A package's one ESM entry: its `exports` for `.`, under `import`, else
// `node` or `default`. A package with no `exports`, or one that also
// exports a subpath (other than its manifest), has none.
@@ -482,15 +579,117 @@ export async function openSession(pkg, pause = async () => {}) {
`the TypeScript this CLI depends on (${ts.version}) has no compiler API`,
`Reinstall @tanstack/oracles, which depends on TypeScript 5.`,
)
+ // What Vitest, the config, and the config's own plugins read in this
+ // process (`reading`): every plugin input is a daemon input (maintainer
+ // decision, 2026-11-16, "All of them"). What Vitest and Vite read while
+ // Vitest loads and while a context warms (`warmReads`, some hundred files
+ // and variables) is a global input of every unit (globalKey). What a hook
+ // of the config's own plugins reads (`hookReads`, pluginHooks), at any
+ // time, is an input of every unit that settles after it, with its hash
+ // from that read (settleIn). A daemon whose session read a file that has
+ // changed since is replaced (inputsChanged, daemon.mjs), since a plugin or
+ // a module may keep what it read. A load or transform hook's read of the
+ // module it serves is that module's own text, the module's input already.
+ // A file that the session wrote earlier in the check before it read it,
+ // such as the config Vite bundles into a temporary file, is the session's
+ // own output (maintainer decision, 2026-11-17, "Own writes aren't
+ // inputs": the same process, earlier in the check). Each check starts
+ // with no write (`wrote`), and a file the session wrote must still hold
+ // what it wrote at the next check (`written`, inputsChanged), since a
+ // hand edit of it is no write of the session. So is a variable that the
+ // CLI set (ORACLE_GAPS_STATE, which names each check's output), which a
+ // copy may read too. A read that comes after its warm ended, from work the
+ // warm left behind, is a hook's read, so the global inputs stay those of
+ // the warm itself.
+ const warmReads = new Map()
+ const hookReads = new Map()
+ // The hook reads in the order they came (`hookLog`), kept once in the
+ // store per session (`hook-log:`): a unit names the part of the log
+ // that came before it settled (`hooks::`), which is an input while
+ // every read in that part holds its hash, so no unit carries the reads
+ // themselves (about 3,000 on TanStack DB's suite; review of #133).
+ const hookLogId = sha1(`${process.pid}:${Date.now()}:${Math.random()}`)
+ const hookLog = []
+ // How much of the hook log the store holds (see check).
+ let hookLogStored = 0
+ // Per check: how far each session's log still holds (logHolds).
+ const holds = new Map()
+ const wrote = new Set()
+ const written = new Map()
+ const reading = new AsyncLocalStorage()
+ watchReads((read, write) => {
+ const at = reading.getStore()
+ const key =
+ at?.kindOnly && read.startsWith(`statx:`)
+ ? `stat:${read.slice(`statx:`.length)}`
+ : read
+ if (write === true && key.startsWith(`env:`)) wrote.add(key)
+ const reads = at?.hook || at?.done ? hookReads : warmReads
+ if (at === undefined || at.discovery || key === at.module) return
+ // A stat of a file the session wrote is no input either, as a copy's stat
+ // of its own output is not (capture-setup.mjs, ownOutput; CR-3).
+ const ownWrite =
+ wrote.has(key) || wrote.has(key.replace(/^(stat|statx):/, `fs:`))
+ // A read, or the read that a write which keeps its bytes makes before it
+ // (133-3, CR-21), is an input unless the session wrote the file first.
+ if (write !== true && !ownWrite && !reads.has(key)) {
+ const hash = key.startsWith(`env:`)
+ ? reads === hookReads
+ ? envHash(key.slice(4))
+ : null
+ : inputHash(key)
+ reads.set(key, hash)
+ if (reads === hookReads) hookLog.push([key, hash])
+ }
+ if (write === true) {
+ // A write is the session's, once it has succeeded: the file must still
+ // hold the text it wrote at the next check, so its hash is taken now,
+ // not at the check's end, where a hand edit made in between would be
+ // stored as the session's own text (`written`; CR-14).
+ wrote.add(key)
+ if (key.startsWith(`fs:`)) written.set(key, inputHash(key))
+ // A listed path that this write changed is no longer held by the hook
+ // log's prefixes, which a later unit would otherwise still judge held
+ // (CR-18).
+ holds.clear()
+ }
+ })
+ // Runs `work` as a warm under `reading`.
+ const warming = async (work) => {
+ const at = {}
+ try {
+ return await reading.run(at, work)
+ } finally {
+ at.done = true
+ }
+ }
+ // The plugins whose hooks could not be recorded (hookPlugin). While any is
+ // here, the session keeps no unit: each check computes every unit, as a cold
+ // run does, and names each plugin on its stream (CR-2).
+ const unrecorded = new Set()
+ globalThis.__oracleGapsPluginHooks = (plugins) =>
+ pluginHooks(plugins, reading, unrecorded)
const requireTarget = createRequire(join(pkg, `package.json`))
let createVitest
+ let resolved
try {
- ;({ createVitest } = await import(
- pathToFileURL(requireTarget.resolve(`vitest/node`)).href
- ))
+ resolved = requireTarget.resolve(`vitest/node`)
+ ;({ createVitest } = await warming(() => import(moduleUrlOf(resolved))))
} catch (error) {
+ // Where Vitest resolved and whether that is a real path (a symbolic link's
+ // target is what ESM imports from), named so a failure on another machine
+ // says which layout it had (the CI failure of the held histories).
+ const layout =
+ resolved === undefined
+ ? `resolved nothing`
+ : realPathOf(resolved) === posix(resolved)
+ ? `resolved ${resolved}, a real path`
+ : `resolved ${resolved}, not its real path ${realPathOf(resolved)}`
+ // The layout comes before the error's text, and the text's line breaks are
+ // flattened: the refusal's first line is the one a driver reads (the CI
+ // failure of the held histories, 3a3d54b1 showed no layout at all).
throw new Refusal(
- `the package's Vitest failed to load: ${error?.message ?? error}`,
+ `the package's Vitest failed to load (${layout}; NODE_OPTIONS ${JSON.stringify(process.env.NODE_OPTIONS ?? null)}; NODE_PRESERVE_SYMLINKS ${JSON.stringify(process.env.NODE_PRESERVE_SYMLINKS ?? null)}; execArgv ${JSON.stringify(process.execArgv)}): ${String(error?.message ?? error).replaceAll(`\n`, ` / `)}`,
`Install a working Vitest in the package, so that vitest/node loads from it.`,
)
}
@@ -527,7 +726,11 @@ export async function openSession(pkg, pause = async () => {}) {
writeFileSync(join(home, `host`), hostname())
const harness = join(home, `capture-setup.mjs`)
copyFileSync(join(here, `capture-setup.mjs`), harness)
- // The harness imports the path rule beside it (capture-setup.mjs).
+ // The harness imports the input rule and the path rule beside it, and
+ // preloads the child-write log into the processes a test starts
+ // (capture-setup.mjs).
+ copyFileSync(join(here, `inputs.mjs`), join(home, `inputs.mjs`))
+ copyFileSync(join(here, `child-writes.mjs`), join(home, `child-writes.mjs`))
copyFileSync(join(here, `paths.mjs`), join(home, `paths.mjs`))
// One wrapper config per context, over the package's own config (a path
// relative to the package, or undefined for none). Each serves its own
@@ -571,6 +774,11 @@ export default async (env) => {
plugins: [{
name: 'oracle-gaps-schemata',
enforce: 'pre',
+ // Every resolved plugin's hooks read their inputs under the runner's
+ // watch (check.mjs, pluginHooks).
+ configResolved(resolved) {
+ globalThis.__oracleGapsPluginHooks(resolved.plugins)
+ },
// A workspace dependency loads from its one-file bundle
// (workspaceBundles). A copy of a test file is not resolved here, so
// Vite keeps the absolute path that Vitest imports it by, and \`load\`
@@ -641,11 +849,58 @@ export default async (env) => {
// module by the text that its context serves.
const servedHash = (path, index) => {
if (path.startsWith(`fs:`)) return hashOf(path.slice(3))
+ // A variable by its value in the environment this check runs under, and
+ // a directory by its listing now.
+ if (path.startsWith(`env:`)) return envHash(path.slice(4))
+ if (path.startsWith(`hooks:`)) {
+ const [, id, n] = path.split(`:`)
+ return logHolds(id, Number(n)) >= Number(n) ? `held` : `changed`
+ }
+ if (path.startsWith(`shared:`)) return sharedHolds(path, index)
+ if (/^(dir|dirs|stat|statx):/.test(path)) return inputHash(path)
const text =
globalThis.__oracleGapsServe[index]?.get(path) ??
globalThis.__oracleGapsSchemata.get(path)
return text === undefined ? hashOf(path) : sha1(text)
}
+ // The inputs that many units read alike, a variable or a file under
+ // node_modules, are stored once per distinct set (`shared:`, a row
+ // of the store) and named by each unit that read them (sharedInputs), so
+ // a unit keeps only the inputs that are its own (review of #133, M
+ // "Optimize #133 before merging"). A set holds while each of its inputs
+ // holds its hash, judged once per check and context.
+ const shared = new Map()
+ const sharedHolds = (path, index) => {
+ const key = `${path}:${index}`
+ if (!shared.has(key)) {
+ const inputs = currentStore?.get(path)?.variants[0]?.inputs
+ shared.set(
+ key,
+ inputs?.every(([input, hash]) => servedHash(input, index) === hash)
+ ? `held`
+ : `changed`,
+ )
+ }
+ return shared.get(key)
+ }
+ // How much of a session's hook log, from its start, still holds its
+ // hashes in this check: a unit that names `hooks::` is unchanged
+ // while the first n reads hold. Another session's log is read from the
+ // store; the current one's grows while the check runs, so the count
+ // extends as later units ask.
+ let currentStore
+ const logHolds = (id, n) => {
+ const log =
+ id === hookLogId
+ ? hookLog
+ : (currentStore?.get(`hook-log:${id}`)?.variants[0]?.inputs ?? [])
+ const held = holds.get(id) ?? { count: 0, broken: false }
+ holds.set(id, held)
+ while (!held.broken && held.count < Math.min(n, log.length))
+ if (servedHash(log[held.count][0]) === log[held.count][1]) held.count += 1
+ else held.broken = true
+ return held.count
+ }
// A context transformed a module (its wrapper's transform hook): the hash
// of what it then serves.
globalThis.__oracleGapsTransformed = (index, path) =>
@@ -737,7 +992,7 @@ export default async (env) => {
const requireVite = createRequire(
createRequire(requireTarget.resolve(`vitest/node`)).resolve(`vite`),
)
- esbuild = await import(pathToFileURL(requireVite.resolve(`esbuild`)).href)
+ esbuild = await import(moduleUrlOf(requireVite.resolve(`esbuild`)))
} catch {
return
}
@@ -783,7 +1038,12 @@ export default async (env) => {
await new Promise((resolve) => service.on(`exit`, resolve))
throw new Error(`The service was stopped`)
}
- async function warmContext(settings, index) {
+ // A context warms under `reading` (see warmReads): what its config, Vite,
+ // and Vitest read while it warms is a global input.
+ function warmContext(settings, index) {
+ return warming(() => warmIn(settings, index))
+ }
+ async function warmIn(settings, index) {
await fromConfig(index, settings.config, warmProbe())
writeWrapper(index, settings.config)
// A context that fails to open gives its listener allowance back: one
@@ -808,6 +1068,10 @@ export default async (env) => {
teardownTimeout: settings.testTimeout,
typecheck: { enabled: false },
coverage: { enabled: false },
+ // The runner orders the files itself (KeepOrder), so Vitest's
+ // results cache, which it reads when a context warms and writes
+ // after each run, would only be an input that every run changes.
+ cache: false,
// Vitest 5 caches transformed modules on disk by default, keyed by
// the file, not by what this runner's plugin serves for it, so a
// patched or instrumented source could come back as an earlier text.
@@ -835,6 +1099,17 @@ export default async (env) => {
throw error
}),
)
+ // Vitest's discovery of the test files lists the package's directories.
+ // Each check discovers them again, outside any warm (specsOf), so what a
+ // listing found is never stale: those listings are no global input. The
+ // `--out` directories that runs create beside the tests would otherwise
+ // change every unit's identity at every check.
+ for (const project of context.projects ?? []) {
+ const globFiles = project.globFiles
+ if (typeof globFiles === `function`)
+ project.globFiles = (...args) =>
+ reading.run({ discovery: true }, () => globFiles.apply(project, args))
+ }
// Vitest 3 calls this step `init`; Vitest 4 renamed it `standalone`.
await fromConfig(
index,
@@ -1178,6 +1453,10 @@ export default async (env) => {
rows,
inputs: importsOf(file, modules, closing),
readAt: closing.readAt,
+ own: closing.own,
+ // A child process's log lost lines, so its reads are not all here
+ // (child-writes.mjs): the run is not stored (CR-19).
+ childLost: closing.childLost === true,
}
}
@@ -1208,6 +1487,8 @@ export default async (env) => {
seconds,
inputs: importsOf(file, modules, closing),
readAt: closing.readAt,
+ own: closing.own,
+ childLost: closing.childLost === true,
}
}
@@ -1577,6 +1858,8 @@ export default async (env) => {
rows: own.map((row) => [row.key, row]),
inputs: importsOf(item.file, [], closings.get(copies[i])),
readAt: closings.get(copies[i])?.readAt,
+ own: closings.get(copies[i])?.own,
+ childLost: closings.get(copies[i])?.childLost === true,
}
}),
timedOutAt: current,
@@ -1651,6 +1934,8 @@ export default async (env) => {
.map((row) => [map(row.key), { ...row, key: map(row.key) }]),
inputs: importsOf(item.file, modules, closings.get(copy)),
readAt: closings.get(copy)?.readAt,
+ own: closings.get(copy)?.own,
+ childLost: closings.get(copy)?.childLost === true,
}
}),
}
@@ -1775,12 +2060,57 @@ export default async (env) => {
return environments
}
- async function check(
+ // A check, after which each file the session wrote is known by its text.
+ async function check(...args) {
+ const store = args[1]
+ const log = args[2] ?? console.error
+ const unstored = () => unrecorded.size > 0
+ const kept = {
+ get: (id) => (unstored() ? undefined : store.get(id)),
+ put: (id, entry) => {
+ if (!unstored()) store.put(id, entry)
+ },
+ flush: () => store.flush?.(),
+ }
+ try {
+ return await checkIn(args[0], kept, ...args.slice(2))
+ } finally {
+ for (const name of unrecorded)
+ log(
+ streamLine(
+ `note`,
+ `plugin ${escapeControls(name)} has a frozen hook object: this check runs cold and stores no unit of it`,
+ ),
+ )
+ // A file the session wrote and then removed (Vite deletes the config it
+ // bundles into a temporary file once it has loaded it) is no longer the
+ // session's to keep: it is stored as missing, so the removal is not a
+ // change that restarts the daemon. An edit that keeps the file in place
+ // is still seen, since its hash stays the one taken when it was written
+ // (CR-14, and the regression that the write-time hash caused).
+ for (const key of wrote)
+ if (key.startsWith(`fs:`) && inputHash(key) === `missing`)
+ written.set(key, `missing`)
+ // The session's hook log, for units that later sessions look up, once
+ // it has grown: a put marks the store to be written again, whole.
+ if (hookLog.length > hookLogStored && !unstored()) {
+ store.put(`hook-log:${hookLogId}`, {
+ inputs: [...hookLog],
+ unit: null,
+ })
+ hookLogStored = hookLog.length
+ }
+ }
+ }
+ async function checkIn(
options,
store,
log = console.error,
progress = () => {},
gone = () => false,
+ // The daemon's diagnostic line (its log, daemon.log): a unit a check did
+ // not store, and why. Undefined for a cold run, which writes none.
+ diag = undefined,
) {
// A check whose caller has gone (a daemon's CLI that checked cold) stops
// before it writes more into its --out: here, at each phase's end, and
@@ -1790,6 +2120,13 @@ export default async (env) => {
if (gone()) throw new Error(`the check's caller has gone`)
}
stopIfGone()
+ // Each check hashes every input from its text (fileHashes), and starts
+ // with no write of its own.
+ hashOf.forget()
+ wrote.clear()
+ holds.clear()
+ shared.clear()
+ currentStore = store
const authored = options.mutants ? loadAuthored(options.mutants) : []
seedVariable = `${options.envPrefix}_SEED`
if (options.retiredFirstLimit)
@@ -1918,6 +2255,17 @@ export default async (env) => {
]
.sort()
.map((file) => [file, hashOf(file)]),
+ // What Vitest, Vite, and the config read while Vitest loaded and the
+ // contexts warmed (warmReads), each by its value at that read: the
+ // contexts were warmed on that text, so a file edited since is keyed
+ // by what the run used, and the next check, which finds the file
+ // changed, computes it again (CR-4). A variable is read now.
+ [...warmReads]
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
+ .map(([key, hash]) => [
+ key,
+ key.startsWith(`env:`) ? servedHash(key) : hash,
+ ]),
process.version,
options.seed ?? null,
settings,
@@ -1980,12 +2328,48 @@ export default async (env) => {
// a file's from the copy's first read of it (`readAt`), a module's from
// its context's transform of it, or else its hash at the start, or now.
// A path that changed while the run ran is invalidated, and the run is
- // not stored (undefined); nor is a run with no known input.
- function settleIn(context, started, paths, readAt = {}) {
+ // not stored (undefined); nor is a run with no known input. `label` names
+ // the unit in the diagnostic line (`diag`) of a run that is not stored.
+ // `own` is the run's own output (capture-setup.mjs): a path its tree
+ // created or copied is no input when the run read it absent, and so is a
+ // directory it made entries in (law 9, own outputs are not inputs). A path
+ // present when read, which the run then changed, is still an input.
+ function settleIn(
+ context,
+ started,
+ given,
+ runReadAt = {},
+ label,
+ own = [],
+ ) {
const index = indexOf.get(context)
const served = servedBy(index)
const loads = globalThis.__oracleGapsLoads[index]
- let stable = paths.length > 0
+ const owned = (path) =>
+ own.some((root) => path === root || path.startsWith(`${root}/`))
+ const runPaths = given.filter((key) => {
+ const path = key.slice(key.indexOf(`:`) + 1)
+ const absent = (runReadAt[key] ?? started.get(key)) === `missing`
+ if (/^(fs|stat|statx|dir|dirs):/.test(key) && absent && owned(path))
+ return false
+ if (
+ /^(dir|dirs):/.test(key) &&
+ own.some((root) => root.startsWith(`${path}/`))
+ )
+ return false
+ return true
+ })
+ let stable = runPaths.length > 0
+ const moved = []
+ // What the config's plugins have read so far, each with its hash from
+ // its read: the run may have read through any of it (see hookReads).
+ // A variable that the CLI set (`wrote`) is its own output, which a
+ // copy may read too (the harness's fallback read of ORACLE_GAPS_STATE).
+ const hooks = `hooks:${hookLogId}:${hookLog.length}`
+ const paths = [...new Set([...runPaths, hooks])].filter(
+ (path) => !(path.startsWith(`env:`) && wrote.has(path)),
+ )
+ const readAt = { [hooks]: `held`, ...runReadAt }
const inputs = paths.map((path) => {
const now = servedHash(path, index)
const hash =
@@ -1996,12 +2380,28 @@ export default async (env) => {
context.invalidateFile(posix(path))
loads?.delete(path)
}
- if (hash !== now) stable = false
+ if (hash !== now) {
+ stable = false
+ moved.push(
+ `${path} read at ${hash.slice(0, 12)}, at check end ${now.slice(0, 12)}`,
+ )
+ }
served.set(path, now)
return [path, hash]
})
+ if (!stable && label !== undefined && diag !== undefined)
+ diag(
+ `oracle-gaps: note unit ${label} is not stored: ${
+ moved.length > 0
+ ? `an input moved during its run: ${moved.join(`; `)}`
+ : `it read no input`
+ }`,
+ )
return stable ? inputs : undefined
}
+ // The name a diagnostic line gives a unit: its file, spec and select.
+ const labelOf = (file, spec, select) =>
+ `${relativeWithin(pkg, file) ?? posix(file)} spec ${spec} select ${JSON.stringify(select ?? null)}`
// A copy cut by a clock or by its call count: its own run's timeout, or
// Vitest's own limit ("Test timed out"), which the copy outlived. Such a
// copy is never charged, and it ends the mutant's copies (the outcome rule,
@@ -2015,12 +2415,32 @@ export default async (env) => {
// A unit cut by the wall clock is not stored: a rerun on another machine
// can finish it, so the daemon reruns it rather than reuse a backstop
// decision (M, 2026-11-23; I8, I12). A count or state cut is stored.
- const remember = (id, unit, inputs) => {
+ // A unit is stored without the hashes of what its copy read (`readAt`),
+ // which only its settling used: the stored inputs hold them.
+ const remember = (id, { readAt, own, ...unit }, inputs) => {
if (!inputs) return
- const entry = { inputs, unit }
+ const entry = { inputs: sharedInputs(inputs), unit }
hook?.stored(entry)
if (!cutByTime(unit)) store.put(id, entry)
}
+ // A unit's inputs with those that many units read alike (see
+ // sharedHolds) moved into one stored set, which the unit names.
+ const sharedInputs = (inputs) => {
+ const common = []
+ const own = []
+ for (const input of inputs)
+ (input[0].startsWith(`env:`) || input[0].includes(`/node_modules/`)
+ ? common
+ : own
+ ).push(input)
+ if (common.length < 2) return inputs
+ // In one order, so the copies of a file, which read the same modules
+ // in different orders, name one set.
+ common.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
+ const path = `shared:${sha1(JSON.stringify(common))}`
+ if (!store.get(path)) store.put(path, { inputs: common, unit: null })
+ return [...own, [path, `held`]]
+ }
// A batch run in a slot's context, with the inputs to store each item
// under: the modules its file's unmutated run read, and those its copy
// loaded beyond them, as a mutated branch can import a module.
@@ -2036,18 +2456,25 @@ export default async (env) => {
items,
options.seed ?? null,
)
- const inputs = items.map(({ file }, k) =>
- settleIn(
- context,
- started,
- [
- ...new Set([
- ...(fileInputs.get(file) ?? []),
- ...(batch.units[k]?.inputs ?? []),
- ]),
- ],
- batch.units[k]?.readAt,
- ),
+ const inputs = items.map(({ file, spec, select }, k) =>
+ // A unit whose child log lost lines is not stored (CR-19).
+ batch.units[k]?.childLost
+ ? undefined
+ : settleIn(
+ context,
+ started,
+ [
+ ...new Set([
+ ...(fileInputs.get(file) ?? []),
+ ...(batch.units[k]?.inputs ?? []),
+ ]),
+ ],
+ batch.units[k]?.readAt,
+ batch.units[k] && !batch.units[k].skipped
+ ? labelOf(file, spec, select)
+ : undefined,
+ batch.units[k]?.own,
+ ),
)
return { ...batch, inputs }
}
@@ -2089,7 +2516,19 @@ export default async (env) => {
if (!result.timedOut && spec.startsWith(`unmutated:`))
fileInputs.set(file, result.inputs)
if (paths) {
- const inputs = settleIn(context, started, paths, result.readAt)
+ // A run whose child log lost lines is not stored (CR-19).
+ const inputs = result.childLost
+ ? undefined
+ : settleIn(
+ context,
+ started,
+ paths,
+ result.readAt,
+ keep && !result.skipped
+ ? labelOf(file, spec, runOptions.select)
+ : undefined,
+ result.own,
+ )
if (keep) remember(id, result, inputs)
}
return result
@@ -3103,7 +3542,31 @@ export default async (env) => {
removeHome()
}
- return { check, close }
+ /**
+ * Whether a file the session read (warmReads, hookReads) or wrote
+ * (written) holds other text now: a
+ * daemon then serves no more checks, since a plugin or a module may keep
+ * what it read (daemon.mjs).
+ */
+ // The keys whose text changed since the session read or wrote them (the
+ // restart reason names them, daemon.mjs `restartReason`).
+ // The session's input state now: how many tracked inputs it compares, which
+ // changed (their keys), and each gate input's stored and current hash (a key
+ // that names a gate, for the daemon's log).
+ const inputState = () => {
+ const changed = []
+ const gates = []
+ let compared = 0
+ for (const [key, hash] of [...warmReads, ...hookReads, ...written]) {
+ if (key.startsWith(`env:`)) continue
+ compared += 1
+ const now = inputHash(key)
+ if (now !== hash) changed.push(key)
+ if (key.includes(`gate`)) gates.push({ key, stored: hash, now })
+ }
+ return { compared, changed, gates }
+ }
+ return { check, close, inputState }
}
/**
diff --git a/packages/oracles/oracle-gaps/child-writes.mjs b/packages/oracles/oracle-gaps/child-writes.mjs
new file mode 100644
index 00000000..1070f068
--- /dev/null
+++ b/packages/oracles/oracle-gaps/child-writes.mjs
@@ -0,0 +1,60 @@
+// What a test's own child processes read and write, at any depth. The harness
+// (capture-setup.mjs) preloads this file into every Node process that a test
+// starts (`--import` in NODE_OPTIONS, which each child passes on to its own
+// children) and names a log per copy (ORACLE_GAPS_CHILD_WRITES). Each line is
+// a JSON array, written as the process makes the call:
+// ["R", key, hash] a read of the input `key`, hashed now, before the read;
+// ["W", key] a write of the file `key`, which makes it the tree's own
+// output, so a later read of it is no input.
+// An append reads the text it adds to, then writes (`R` and then `W`), so the
+// text is an input and the file is still the tree's output after the write.
+// The copy folds the log in order (capture-setup.mjs, foldChildren): a read
+// the tree had not written is an input of the test, whichever process made
+// it (maintainer decisions "Own writes aren't inputs", 2026-11-17, "Optimize
+// #133 before merging", 2026-11-19; review of #133, F-2). An environment
+// variable is the CLI's to watch: the whole environment restarts the daemon.
+// The log is written through a file descriptor, which no wrapper watches.
+import { openSync, writeFileSync, writeSync } from 'node:fs'
+import { fileURLToPath } from 'node:url'
+import { inputHash, patchWorkerThreads, watchReads } from './inputs.mjs'
+
+const log = process.env.ORACLE_GAPS_CHILD_WRITES
+if (log) {
+ // The log is telemetry: a failed write (a full disk, a log that cannot be
+ // opened) must not change the child's own result (CR-19). The child then
+ // goes on unlogged, and leaves `.lost`, which the copy reads, so the
+ // run that it belongs to is not stored as complete.
+ let fd
+ let lost = false
+ const lose = () => {
+ lost = true
+ try {
+ writeFileSync(`${log}.lost`, ``)
+ } catch {
+ // The marker cannot be written either; nothing more to do.
+ }
+ }
+ try {
+ fd = openSync(log, `a`)
+ } catch {
+ lose()
+ }
+ const put = (line) => {
+ if (lost) return
+ try {
+ writeSync(fd, `${JSON.stringify(line)}\n`)
+ } catch {
+ lose()
+ }
+ }
+ watchReads((key, write) => {
+ if (key.startsWith(`env:`)) return
+ if (write !== true) put([`R`, key, inputHash(key)])
+ // A write is logged once it has succeeded (inputs.mjs), so a failed one
+ // makes nothing the tree's own (CR-12).
+ if (write === true) put([`W`, key])
+ })
+ // A worker started by this process, or by a worker, gets the preload too
+ // (CR-25).
+ patchWorkerThreads(fileURLToPath(import.meta.url))
+}
diff --git a/packages/oracles/oracle-gaps/constructed-order.json b/packages/oracles/oracle-gaps/constructed-order.json
index 8ab8b86d..c832a21e 100644
--- a/packages/oracles/oracle-gaps/constructed-order.json
+++ b/packages/oracles/oracle-gaps/constructed-order.json
@@ -162,6 +162,42 @@
"an authored mutant's failing-law spin cut blocks it",
"a behavioral kill decides before a later owner's copy passes the work budget",
"an unregistered soft verdict before a later calibration spin survives the cut",
- "a test edits the helper it read twice, during checks through the daemon"
+ "a test edits the helper it read twice, during checks through the daemon",
+ "an edit to a file in the package that keeps its size and modification time",
+ "an edit to a file outside the package that a test reads",
+ "an edit to a file under node_modules that a test reads",
+ "an edit to an environment variable that a test reads",
+ "an edit to a file the config's plugin reads when the config resolves",
+ "an edit to a file the config's plugin reads when it transforms a test",
+ "an edit to a directory listing that a test reads",
+ "an edit to a directory a test reads through opendir",
+ "an edit to a file a test reads through a stream",
+ "an edit to the tsconfig that Vite's own plugin reads",
+ "an edit to a directory the config lists when it loads",
+ "a hand edit of a file the config's plugin writes",
+ "a test that reads a file its child process wrote, rechecked through the daemon",
+ "an edit to a file the test stats for its size, by statSync",
+ "an edit to a file the test stats for its size, by fs/promises stat",
+ "an edit to a file the test stats for its size, by the callback stat",
+ "an edit to a file a test appends to, then reads",
+ "an edit to a file a test appends to with flag a, then reads",
+ "an edit to a file a test requires as JSON",
+ "an edit to a file that a test child process reads",
+ "a test that writes to the console, rechecked through the daemon",
+ "an edit to a file a test reads inside a worker thread",
+ "an edit to the package.json main that a test requires",
+ "an edit to the package.json type that a test requires",
+ "an edit to a gate that a test reads, during a check through the daemon",
+ "an edit to a file a test reads inside a worker started by a worker",
+ "an edit to a file a test tries to create exclusively, then reads",
+ "an edit to a file a test opens for update, then reads",
+ "an edit to a file that a child process reads when its own log fails",
+ "an edit to a file a test reads through a link and dot-dot",
+ "an edit to a file a test reads in a worker with strict mode",
+ "an unchanged check through the daemon while a config's plugin writes, stats and removes a scratch file",
+ "a check through the daemon of a config whose plugin object is frozen",
+ "an unchanged check through the daemon while a test made the files it reads: a file its child process makes after the test checks for it",
+ "an unchanged check through the daemon while a test made the files it reads: a copy its child process reads, in a directory it removes",
+ "an unchanged check through the daemon while a test made the files it reads: a directory it lists before it writes a file into it"
]
}
diff --git a/packages/oracles/oracle-gaps/daemon.mjs b/packages/oracles/oracle-gaps/daemon.mjs
index e656ffdf..ce54ca76 100644
--- a/packages/oracles/oracle-gaps/daemon.mjs
+++ b/packages/oracles/oracle-gaps/daemon.mjs
@@ -32,8 +32,10 @@
import { spawn } from 'node:child_process'
import { randomUUID } from 'node:crypto'
import {
+ appendFileSync,
existsSync,
linkSync,
+ lstatSync,
mkdirSync,
openSync,
readFileSync,
@@ -130,6 +132,22 @@ async function pauseAt(point) {
* reaches it. The bound changes the run's path, never its outcome: the CLI
* then checks cold (v21.2 R39, I15).
*/
+/**
+ * Whether a daemon's endpoint is one this user may send to: a Unix socket
+ * that this user owns (CR-6). Absent, it is ours to start a daemon at, so the
+ * connect reports that. A named pipe (Windows) has no owner check here, which
+ * the README lists as a limit.
+ */
+function endpointIsOurs(endpoint) {
+ if (process.platform === `win32`) return true
+ try {
+ const stat = lstatSync(endpoint)
+ return stat.isSocket() && stat.uid === process.getuid()
+ } catch {
+ return true
+ }
+}
+
function send(pkg, message, bounded = false) {
return new Promise((settle, reject) => {
// Test-only (ORACLE_GAPS_TEST_WAIT_MARK, a path): the bound is a pause
@@ -141,14 +159,32 @@ function send(pkg, message, bounded = false) {
settle(value)
}
const fail = reject
- const socket = connect(socketOf(pkg))
+ // The request carries this CLI's environment, so it goes only to a socket
+ // this user made (CR-6). On a shared host another user can listen on the
+ // path first, in the shared temporary directory, so an endpoint that is
+ // not ours is refused, and no byte of the request is written to it.
+ const endpoint = socketOf(pkg)
+ if (!endpointIsOurs(endpoint)) {
+ reject(
+ new Error(
+ `the daemon's socket ${endpoint} is not a socket this user owns, so the check does not send its environment to it; remove that path and check again`,
+ ),
+ )
+ return
+ }
+ const socket = connect(endpoint)
let reply = ``
socket.on(`connect`, () => socket.write(`${JSON.stringify(message)}\n`))
if (bounded) {
socket.setTimeout(WAIT_MS)
- socket.on(`timeout`, () =>
- mark === undefined ? done({ silent: true }) : writeMark(mark, ``),
- )
+ socket.on(`timeout`, () => {
+ if (mark !== undefined) return writeMark(mark, ``)
+ logNote(
+ pkg,
+ `the CLI gave up waiting: ${WAIT_MS} ms with no beat or reply from the daemon; this check runs cold`,
+ )
+ done({ silent: true })
+ })
}
socket.on(`data`, (chunk) => {
reply += chunk
@@ -234,7 +270,12 @@ export async function requestDaemon(pkg, argv, code) {
let reply
const sent = Date.now()
try {
- reply = await send(pkg, { argv, cwd: process.cwd(), code }, true)
+ // The CLI's environment, which the daemon must run the check under.
+ reply = await send(
+ pkg,
+ { argv, cwd: process.cwd(), code, env: process.env },
+ true,
+ )
held += Date.now() - sent
// A daemon that stopped answering: the CLI checks cold (R39) and leaves
// it; the daemon drops the check once it sees the CLI gone.
@@ -345,14 +386,27 @@ const listening = (socket) =>
* Takes the package's lock, or returns false when a live daemon holds it.
*/
async function takeLock(lock, socket) {
+ // Test-visible lock transitions (daemon.log): who holds the lock, never its token.
+ const note = (text) => {
+ try {
+ appendFileSync(
+ join(dirname(lock), `daemon.log`),
+ `${new Date().toISOString()} oracle-gaps: pid ${process.pid}: lock ${text}\n`,
+ )
+ } catch {}
+ }
+ const holderOf = (text) =>
+ text === undefined ? `absent` : `held by pid ${text.split(':')[0]}`
for (;;) {
try {
writeFileSync(lock, token, { flag: `wx` })
+ note(`taken`)
return true
} catch (error) {
if (error.code !== `EEXIST`) throw error
}
const seen = readText(lock)
+ note(`found ${holderOf(seen)}`)
for (let waited = 0; waited < GRACE_MS; waited += 100) {
if (await listening(socket)) return false
await sleep(100)
@@ -367,6 +421,7 @@ async function takeLock(lock, socket) {
} catch {
continue
}
+ note(`moved the stale lock ${holderOf(readText(claim))}`)
if (readText(claim) !== seen)
try {
linkSync(claim, lock)
@@ -378,11 +433,53 @@ async function takeLock(lock, socket) {
}
}
+// An environment as one value: its names and values, in name order.
+const envKey = (env) => JSON.stringify(Object.entries(env ?? {}).sort())
+
+// A line of daemon.log (the daemon's and the CLI's own notes, never a stream):
+// each names its time, so a stretch can be measured from the log.
+export const logNote = (pkg, text) => {
+ try {
+ appendFileSync(
+ join(stateDirOf(pkg), `daemon.log`),
+ `${new Date().toISOString()} oracle-gaps: pid ${process.pid}: ${text}\n`,
+ )
+ } catch {
+ // A note that cannot be written loses nothing a check reports.
+ }
+}
+
+// Why a request restarts this daemon, in the order the request handler has
+// always tested it (the first reason only), or undefined when none holds. An
+// input's changed keys are named, since a restart reason is a diagnosis.
+// It returns { why, inputs }: `inputs` is the session's input state (check.mjs
+// inputState) when the tracked inputs were compared, else undefined.
+function restartReason(message, code, ownEnv, session, codeIdentity) {
+ if (codeIdentity() !== code) return { why: `the code of this copy changed` }
+ if (message.code !== code) return { why: `the request is of other code` }
+ if (envKey(message.env) !== ownEnv)
+ return { why: `the request's environment differs from the daemon's` }
+ const inputs = session.inputState()
+ if (inputs.changed.length > 0) {
+ const shown = inputs.changed.slice(0, 8).join(`, `)
+ return {
+ why: `a tracked input changed: ${shown}${inputs.changed.length > 8 ? ` and ${inputs.changed.length - 8} more` : ``}`,
+ inputs,
+ }
+ }
+ return { why: undefined, inputs }
+}
+
async function serve(pkg) {
+ // The environment this daemon runs its checks under, which the CLI that
+ // started it gave it, taken before the session sets anything in it.
+ const ownEnv = envKey(process.env)
mkdirSync(stateDirOf(pkg), { recursive: true })
const lock = join(stateDirOf(pkg), `daemon.lock`)
const socket = socketOf(pkg)
if (!(await takeLock(lock, socket))) process.exit(0)
+ // Test-visible (daemon.log): the process's exit, after any shutdown line.
+ process.on(`exit`, (code) => logNote(pkg, `process exit ${code}`))
// A dead daemon's socket; this daemon holds the lock.
removeSocket(socket)
let closing = false
@@ -411,13 +508,13 @@ async function serve(pkg) {
})
// Stops serving: the requests already queued run first, each hearing
// `closing`, then the daemon shuts down.
- const close = () => {
+ const close = (why = `closed`) => {
closing = true
- queue = queue.then(() => shutdown())
+ queue = queue.then(() => shutdown(undefined, { exitCode: 0 }, why))
}
const closeAfter = (ms) => {
clearTimeout(idle)
- idle = setTimeout(close, ms)
+ idle = setTimeout(() => close(`idle for ${ms} ms`), ms)
}
// Resolves once the reply has left this process, so a daemon that exits
// next cannot cut it short; a reply longer than the socket's buffer is
@@ -465,36 +562,69 @@ async function serve(pkg) {
if (!request.includes(`\n`)) return
const message = JSON.parse(request)
// A closing daemon serves nothing more; the caller waits for the next.
- if (closing) return reply(connection, { closing: true })
+ if (closing) {
+ logNote(pkg, `declined a request: the daemon is closing`)
+ return reply(connection, { closing: true })
+ }
if (message.stop) {
closing = true
- queue = queue.then(() => shutdown(connection))
+ queue = queue.then(() =>
+ shutdown(connection, undefined, `stopped by a request`),
+ )
return
}
waiting.add(connection)
overlap?.accepted()
+ const arrived = Date.now()
queue = queue.then(async () => {
clearTimeout(idle)
// A request queued before the session failed hears why.
- if (failure)
+ if (failure) {
+ logNote(pkg, `declined a request: the session failed to open`)
return reply(connection, {
code,
stdout: ``,
stderr: ``,
failed: sent(failure),
})
- if (closing) return reply(connection, { closing: true })
+ }
+ if (closing) {
+ logNote(pkg, `declined a request: the daemon is closing`)
+ return reply(connection, { closing: true })
+ }
// A daemon whose code changed, or that a CLI of other code asks (a
// second install), declines this check and closes after the
// requests already queued, each of which hears `closing`; the CLI
- // then starts a daemon of its own code.
- if (codeIdentity() !== code || message.code !== code) {
+ // then starts a daemon of its own code. So does a daemon asked from
+ // another environment than its own, or whose session read a file
+ // that changed since (check.mjs, inputsChanged): every read is a
+ // daemon input (maintainer decision, 2026-11-16), and a module or a
+ // plugin may keep what it read, so the CLI starts a daemon in its own
+ // environment, which reads them again.
+ const decided = restartReason(
+ message,
+ code,
+ ownEnv,
+ session,
+ codeIdentity,
+ )
+ if (decided.why !== undefined) {
+ logNote(pkg, `replaced by a new daemon: ${decided.why}`)
closing = true
- queue = queue.then(() => shutdown(connection, { restart: true }))
+ queue = queue.then(() =>
+ shutdown(connection, { restart: true }, `replaced`),
+ )
return
}
+ // The decision that kept this daemon, with what it compared: the tracked
+ // inputs' count and any gate input's stored and current hash.
+ logNote(
+ pkg,
+ `kept for a check: compared ${decided.inputs.compared} tracked inputs, none changed; gates ${JSON.stringify(decided.inputs.gates)}`,
+ )
// The test-only hold before a check runs (`pauseAt`).
await pauseAt(`daemon-check`)
+ const checkStarted = Date.now()
const stderr = []
let stdout = ``
let failed
@@ -518,6 +648,8 @@ async function serve(pkg) {
(line) => stderr.push(`${line}\n`),
beat,
() => connection.destroyed,
+ // The daemon's log (daemon.log): a unit not stored, and why.
+ (line) => console.error(line),
)
// The store is a cache: a flush that fails (a full disk) loses
// nothing the check reported, so the reply stands, and the units
@@ -533,6 +665,10 @@ async function serve(pkg) {
} catch (error) {
failed = sent(error)
}
+ logNote(
+ pkg,
+ `served a check${failed === undefined ? `` : ` that failed`}: ${checkStarted - arrived} ms queued (the session's open included), ${Date.now() - checkStarted} ms checking`,
+ )
await reply(connection, {
code,
stdout,
@@ -553,9 +689,10 @@ async function serve(pkg) {
// it unlinks the socket path, and a daemon that lost its lock may find the
// path taken by the successor that holds the lock now, whose socket it
// would remove.
- async function shutdown(connection, value = { exitCode: 0 }) {
+ async function shutdown(connection, value = { exitCode: 0 }, why = `closed`) {
closing = true
clearInterval(watch)
+ logNote(pkg, `shutting down: ${why}`)
await session?.close()
// A store that cannot write its last check (a full disk) is no reason to
// keep the lock: the next daemon starts cold.
@@ -592,15 +729,27 @@ async function serve(pkg) {
// one rather than hearing this error again.
failure = error
writeFileSync(errorFileOf(pkg), JSON.stringify(sent(error)))
+ logNote(pkg, `the session failed to open: ${error?.message ?? error}`)
opened()
- close()
+ close(`the session failed to open`)
return
}
rmSync(errorFileOf(pkg), { force: true })
opened()
// A daemon whose lock another daemon took serves no more.
watch = setInterval(() => {
- if (!closing && readText(lock) !== token) close()
+ if (closing) return
+ let now
+ let errno
+ try {
+ now = readFileSync(lock, `utf8`)
+ } catch (error) {
+ errno = error.code
+ }
+ if (now !== token)
+ close(
+ `the lock names another daemon (${now === undefined ? `read error ${errno}` : `held by pid ${now.split(`:`)[0]}`})`,
+ )
}, 2000)
closeAfter(idleMs)
}
diff --git a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs
index 04854972..09c2b4f2 100644
--- a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs
+++ b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs
@@ -11,12 +11,14 @@ import {
readFileSync,
readlinkSync,
rmSync,
+ statSync,
symlinkSync,
unlinkSync,
+ utimesSync,
writeFileSync,
} from 'node:fs'
import { createRequire } from 'node:module'
-import { dirname, join } from 'node:path'
+import { dirname, join, posix as posixPath } from 'node:path'
import { fileURLToPath } from 'node:url'
import fc from 'fast-check'
@@ -695,6 +697,11 @@ const earlierEdits = edits.filter((edit) => !laterEdits.includes(edit))
const faults = [`corruptStore`]
// A history's no faults, one value, as `NO_LATER_STEPS`.
const NO_FAULTS = Object.freeze([])
+// The edit of the gate input that file b's verdict reads (`inputRead`),
+// which flips it between `open` and `shut`. It is drawn in its own field
+// (`inputSteps`), after `laterSteps`, so the fields before it draw as they
+// did (the generator rule: new draws go last).
+const inputEdits = [`inputGate`]
// A history's no later edits, one value, so `histories` can take it back
// (fc.constant takes back only its own reference).
const NO_LATER_STEPS = Object.freeze([])
@@ -707,6 +714,12 @@ const laterStepsOf = (history) =>
history.witness === false && history.steps != null
? [...(history.laterSteps ?? []), ...(history.faults ?? [])]
: []
+// The input edits a history takes after its later edits, by the same rule.
+const NO_INPUT_STEPS = Object.freeze([])
+const inputStepsOf = (history) =>
+ history.witness === false && history.steps != null
+ ? (history.inputSteps ?? [])
+ : []
// The steps that act on the daemon and change no file.
const daemonEvents = new Set([
`restart`,
@@ -1355,7 +1368,7 @@ const drawn = fc.record({
// a push, which occurs more than once in the source, and the push's own
// line. Law 16 judges such a mutant on a changed line when any of its
// lines changed. Where no such push exists, the find stays one line.
- // Drawn last (the generator rule).
+ // Drawn after `diffBase` (the generator rule); the gate fields follow it.
authoredSpan: fc.boolean(),
// The history's backstop (`--hang-limit`), drawn (M, 2026-11-16, "Randomness
// wins"): null is the full limit, and a longer one moves no copy into the
@@ -1401,6 +1414,145 @@ const drawn = fc.record({
// law, never a kill (C 2026-11-24, "Every built-in cut by an excluded test
// ends the copy as a gap": blocked by a failing law that caused it).
failingLawHangs: fc.constant(false),
+ // Every read is a daemon input (maintainer decision, 2026-11-16, "All of
+ // them"): a file a test reads through fs on any path, node_modules
+ // included; an environment variable a test reads; and what the config's
+ // own plugin reads. File b's verdicts also wait on one such gate input,
+ // which the `inputGate` edit flips between `open` and `shut` (law 9). The
+ // gate is a JSON file that the test reads with a sync read: in the
+ // package's tests (`inside`), beside the package and outside it
+ // (`outside`), or in a package under its node_modules (`module`); or the
+ // variable GAP_INPUT_GATE (`env`); or a file the config's own plugin
+ // reads, once when the config resolves (`pluginConfig`) or each time it
+ // transforms a test file (`pluginTransform`), and writes into the test's
+ // text; or the listing of a directory of the package's tests, which holds
+ // one empty file named `open` or `shut`, read by `readdirSync`
+ // (`listing`) or by `opendirSync` (`opendir`): the edit renames that file,
+ // so no file's text changes; or the package's gate file read through a
+ // stream (`stream`, createReadStream); or an input of Vite's own plugins,
+ // the package's tsconfig.json, whose useDefineForClassFields decides
+ // whether a declared class field is an own property (`tsconfig`); or a
+ // listing that the config makes when it loads and gives to the tests
+ // through `define` (`configListing`); or a file that the config's plugin
+ // writes when the config resolves, which the edit then changes by hand
+ // (`pluginWrite`: a cold run's plugin writes it again, so the cold result
+ // does not change, and the daemon must not read the hand edit). These fields change what a history runs, so
+ // they are drawn (maintainer decision, 2026-11-16, "Randomness wins"), and
+ // last.
+ inputRead: fc.constantFrom(
+ `none`,
+ `none`,
+ `none`,
+ `inside`,
+ `outside`,
+ `module`,
+ `env`,
+ `pluginConfig`,
+ `pluginTransform`,
+ `listing`,
+ `opendir`,
+ `stream`,
+ `tsconfig`,
+ `configListing`,
+ `pluginWrite`,
+ `stat`,
+ `statAsync`,
+ `statCallback`,
+ `append`,
+ `flagAppend`,
+ `required`,
+ `childRead`,
+ `threadRead`,
+ `requireMain`,
+ `requireType`,
+ `wxExisting`,
+ `rplus`,
+ `threadNested`,
+ `childLost`,
+ `linkDotDot`,
+ `threadStrict`,
+ ),
+ // Each write of a gate file keeps its size (`open` and `shut` have one
+ // length) and gets back one fixed modification time, as `cp -p`, `rsync
+ // -t`, or `touch -r` leave a file: a cache keyed by size and time cannot
+ // tell the two texts apart (D10; the TLA model's weakened-stamp run).
+ keepStamp: fc.constantFrom(false, false, false, true),
+ // The input edits, which follow a history's steps and later edits.
+ inputSteps: fc.oneof(
+ { weight: 3, arbitrary: fc.constant(NO_INPUT_STEPS) },
+ {
+ weight: 1,
+ arbitrary: fc.array(fc.constantFrom(...inputEdits), {
+ minLength: 1,
+ maxLength: 2,
+ }),
+ },
+ ),
+ // Whether file b, as it loads, reads a file that its test's own child
+ // process wrote: a node child starts a node grandchild, which writes the
+ // file in a new temporary directory and prints the directory, and file b
+ // reads the file and removes the directory. A file that the test's own
+ // process tree wrote earlier in the check is its own output, no input
+ // (maintainer decisions "Own writes aren't inputs", 2026-11-17, and
+ // "Optimize #133 before merging", 2026-11-19), so an unchanged recheck
+ // through the daemon reuses file b's runs although the directory differs
+ // in every run. It changes what a history runs, so it is drawn (randomness
+ // wins, 2026-11-16), and last.
+ childWrite: fc.constantFrom(
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ true,
+ ),
+ // The Vite environment that file b runs in when it reads what its child
+ // process wrote (`childWrite`): the config's (`node`), or one that
+ // transforms its modules for the client (`client`), as a jsdom
+ // environment does. The client transform rewrites `new URL(,
+ // import.meta.url)` to a URL of the dev server, in the harness that runs in
+ // the file's environment too, so the harness's own path to the child
+ // preload must not take that form (TanStack DB's jsdom suite). Only file b
+ // takes it, and only where it reads no gate input or data, whose paths
+ // take that form in the file's own text.
+ childEnvironment: fc.constantFrom(`node`, `node`, `node`, `client`),
+ // Whether a mid-run edit (`midrun`, by file a's test) lands on the gate file
+ // that file b's verdict reads, not on the helper (`midrunTarget`, drawn
+ // earlier). Drawn last, so every field above draws as before.
+ midrunGate: fc.constantFrom(
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ true,
+ ),
+ // Drawn last (CR-3): a config plugin that writes a scratch file beside the
+ // config, tests it, and removes it at each resolve (`scratchPlugin`).
+ scratchPlugin: fc.constantFrom(false, false, false, false, true),
+ // Drawn last (CR-2): the config's plugin object is frozen, so the runner cannot wrap its hooks (`frozenPlugin`).
+ frozenPlugin: fc.constantFrom(false, false, false, false, true),
+ // File b's own output (OWN_OUTPUT_READS): drawn last, so the draws above keep
+ // their values for every seed. Most histories run without it. The arbitrary
+ // takes every shape, so a constructed history of one can shrink.
+ ownOutput: fc.constantFrom(
+ `none`,
+ `none`,
+ `none`,
+ `none`,
+ `none`,
+ `none`,
+ `none`,
+ `none`,
+ `created`,
+ `copied`,
+ `listed`,
+ `childStat`,
+ ),
})
// The edit sequence over the witness module, the one list of steps that a
@@ -1541,6 +1693,22 @@ const plainStops = (stopRuns) =>
: stopRuns.length === 0
? NO_STOPS
: stopRuns
+// The neutral value of each drawn field that a history may leave out: a
+// history filed before the field was drawn (fixed histories of main, such as
+// #165) does not set it. A drawn record holds the constant, so the take-back
+// reads an absent field as it, as `faults` does, and the arbitrary takes the
+// history back.
+const drawnNeutral = {
+ inputRead: `none`,
+ keepStamp: false,
+ inputSteps: NO_INPUT_STEPS,
+ childWrite: false,
+ childEnvironment: `node`,
+ midrunGate: false,
+ scratchPlugin: false,
+ frozenPlugin: false,
+ ownOutput: `none`,
+}
const histories = drawn.map(
(history) => {
const kept = keepsSteps(history) ? history : { ...history, steps: null }
@@ -1558,8 +1726,9 @@ const histories = drawn.map(
if (!keepsSteps(history))
throw new Error(`a history with the witness module takes no steps`)
// A constructed backstop outside the drawn set (`hangMs`) comes back as null.
- const { slowTwin, hangMs, ...drawnValue } =
+ const { slowTwin, hangMs, ...given } =
/** @type {Record} */ (value)
+ const drawnValue = { ...drawnNeutral, ...given }
const tests = /** @type {Record[]} */ (drawnValue.tests)
const plain =
/** @type {{ steps: unknown[] | null, stopRuns: Array<{ when: string }> } & Record} */ ({
@@ -1609,14 +1778,21 @@ const histories = drawn.map(
? { ...taken, faults: NO_FAULTS }
: taken
const later = (steps ?? []).filter((step) => laterEdits.includes(step))
+ // An input edit in `steps` moves to `inputSteps` in the same way.
+ const inputs = (steps ?? []).filter((step) => inputEdits.includes(step))
const remaining = (steps ?? []).filter(
- (step) => !laterEdits.includes(step) && !faults.includes(step),
+ (step) =>
+ !laterEdits.includes(step) &&
+ !faults.includes(step) &&
+ !inputEdits.includes(step),
)
- if (later.length === 0 && struck.length === 0) return faulted
+ if (later.length === 0 && struck.length === 0 && inputs.length === 0)
+ return faulted
return {
...faulted,
steps: remaining.length > 0 ? remaining : null,
...(later.length > 0 ? { laterSteps: later } : {}),
+ ...(inputs.length > 0 ? { inputSteps: inputs } : {}),
}
},
)
@@ -3836,7 +4012,11 @@ function resolveHistory(history) {
template: history.template,
fault: history.fault,
stability: history.stability,
- steps: [...(history.steps ?? []), ...laterStepsOf(history)],
+ steps: [
+ ...(history.steps ?? []),
+ ...laterStepsOf(history),
+ ...inputStepsOf(history),
+ ],
pauseEngages: history.pauseEngages !== false,
warmReplaced: history.warmReplaced === true,
replyHeld: history.replyHeld === true,
@@ -3848,6 +4028,28 @@ function resolveHistory(history) {
spinThrows: history.spinThrows === true,
slowStart: history.slowStart ?? false,
shortWait: history.shortWait === true,
+ childWrite: history.childWrite === true,
+ ownOutput: history.ownOutput ?? `none`,
+ // A client environment rewrites `new URL(..., import.meta.url)` to the dev
+ // server's URL, so file b's raw-import check (rawImport) cannot read the
+ // module there: such a history runs its file b in node (CR-8).
+ childEnvironment:
+ history.childWrite === true &&
+ (history.inputRead ?? `none`) === `none` &&
+ (history.fsRead ?? `none`) === `none` &&
+ !(history.tests ?? []).some((t) => t.file === `b` && t.rawImport)
+ ? (history.childEnvironment ?? `node`)
+ : `node`,
+ // The gate input that file b's verdicts also wait on (`inputRead`), and
+ // whether each write of a gate file keeps its size and modification time
+ // (`keepStamp`).
+ // A plugin's gate needs a config to hold the plugin: with none, file b
+ // reads no gate.
+ inputRead:
+ configGated(history) && configOf(history).configPath === undefined
+ ? `none`
+ : (history.inputRead ?? `none`),
+ keepStamp: history.keepStamp === true,
// Whether a step edits file b's helper during a check (`midrun`): then
// file a loads the helper and holds the test that edits it.
midrun: [...(history.steps ?? []), ...laterStepsOf(history)].includes(
@@ -3880,6 +4082,8 @@ function resolveHistory(history) {
matcherOwns: history.matcherOwns ?? `none`,
config: history.config ?? `object`,
prePlugin: history.prePlugin === true,
+ scratchPlugin: history.scratchPlugin === true,
+ frozenPlugin: history.frozenPlugin === true,
tornRows: history.tornRows === true,
...configOf(history),
configEnv: history.configEnv === true,
@@ -6486,6 +6690,415 @@ const dataReads = {
],
}
+// The code of the worker that a worker starts for `threadNested` (CR-25).
+const NESTED_INNER = `const fs = require('node:fs'); const { parentPort, workerData } = require('node:worker_threads'); parentPort.postMessage(JSON.parse(fs.readFileSync(workerData, 'utf8')).gate === 'open')`
+const NESTED_OUTER = `const { Worker } = require('node:worker_threads'); const { parentPort, workerData } = require('node:worker_threads'); const inner = new Worker(${JSON.stringify(NESTED_INNER)}, { eval: true, workerData }); inner.once('message', (open) => parentPort.postMessage(open === true)); inner.once('error', (error) => { throw error })`
+// The code of the worker for `threadStrict`.
+const STRICT_WORKER = `'use strict'; const fs = require('node:fs'); const { parentPort, workerData } = require('node:worker_threads'); const plain = function () { return this }; parentPort.postMessage(plain() === undefined && JSON.parse(fs.readFileSync(workerData, 'utf8')).gate === 'open')`
+// The gate input of file b's verdicts (`inputRead`): the variable that
+// `env` reads, and the file each other kind reads. A gate file holds
+// `open` or `shut`, two words of one length, so an edit keeps its size.
+const INPUT_GATE_VAR = `GAP_INPUT_GATE`
+const gateText = (open) =>
+ `${JSON.stringify({ gate: open ? `open` : `shut` })}\n`
+// The modification time, in seconds, that every write of a gate file gets
+// back under `keepStamp`.
+const GATE_STAMP = 1_700_000_000
+// The kinds that read the gate file's size and not its text (`stat`, the
+// promise and callback forms of `stat`): their `shut` text is longer than
+// `open`, so the size tells the two apart, and an edit changes the size. The
+// size of `open` is the reader's constant.
+const SIZE_GATES = [`stat`, `statAsync`, `statCallback`]
+const OPEN_SIZE = gateText(true).length
+const gateTextFor = (kind, open) =>
+ kind === `requireMain`
+ ? `${JSON.stringify({ main: open ? `open.js` : `shut.js` })}\n`
+ : kind === `requireType`
+ ? `${JSON.stringify({ type: open ? `commonjs` : `module` })}\n`
+ : SIZE_GATES.includes(kind) && !open
+ ? `${JSON.stringify({ gate: `shut`, pad: `....` })}\n`
+ : gateText(open)
+// A fixture path under the directory beside the package (`outsideOf`),
+// which is outside it; writeFixture places it there.
+const BESIDE = `/`
+/** The directory beside the package `dir` that holds its outside files. */
+const outsideOf = (dir) => `${dir}.outside`
+const gateFiles = {
+ inside: `tests/gate.json`,
+ stream: `tests/gate.json`,
+ outside: `${BESIDE}gate.json`,
+ module: `node_modules/gap-gate/gate.json`,
+ pluginConfig: `tests/plugin-gate.json`,
+ pluginTransform: `tests/plugin-gate.json`,
+ stat: `tests/gate.json`,
+ statAsync: `tests/gate.json`,
+ statCallback: `tests/gate.json`,
+ append: `tests/gate.json`,
+ flagAppend: `tests/gate.json`,
+ required: `tests/gate.json`,
+ childRead: `tests/gate.json`,
+ threadRead: `tests/gate.json`,
+ requireMain: `tests/sub/package.json`,
+ requireType: `tests/sub/package.json`,
+ wxExisting: `tests/gate.json`,
+ rplus: `tests/gate.json`,
+ threadNested: `tests/gate.json`,
+ childLost: `tests/gate.json`,
+ // The file the read of `link/../gate.json` opens. A kernel resolves `..` after
+ // a symbolic link (POSIX: a/gate.json, CR-22). win32 resolves `..` lexically
+ // before the link is followed, so the same spelling opens tests/gate.json
+ // (CI's Windows ENOENT on tests\gate.json, 5db6b8ed fixed seed 20261105).
+ linkDotDot:
+ process.platform === `win32` ? `tests/gate.json` : `tests/a/gate.json`,
+ threadStrict: `tests/gate.json`,
+}
+/** Whether the gate input is one that the config's own plugin reads. */
+const pluginGated = (history) =>
+ history.inputRead === `pluginConfig` ||
+ history.inputRead === `pluginTransform`
+/** Whether the gate lives in the config (a plugin, or the config's own listing). */
+const configGated = (history) =>
+ pluginGated(history) ||
+ history.inputRead === `configListing` ||
+ history.inputRead === `pluginWrite`
+// Whether a test's verdict waits on the gate input.
+const inputGated = (plan, file, t) =>
+ plan.inputRead !== `none` &&
+ file === `b` &&
+ t.judges &&
+ t.judgeBy === `verdict`
+// How file b reads its gate input, by each kind (`inputRead`). The outside
+// file lies in the directory beside the package, named by the package's
+// own directory with `.outside` after it. The plugin kinds read the text
+// that the config's plugin wrote in place of `__GAP_INPUT_GATE__`.
+const readGateFile = (path) =>
+ `const readInput = async () => ({ open: JSON.parse(readGate(${path}, 'utf8')).gate === 'open' })`
+const inputReads = {
+ inside: [
+ `import { readFileSync as readGate } from 'node:fs'`,
+ readGateFile(`new URL('./gate.json', import.meta.url)`),
+ ],
+ outside: [
+ `import { readFileSync as readGate } from 'node:fs'`,
+ `import { fileURLToPath as gatePackage } from 'node:url'`,
+ readGateFile(
+ `gatePackage(new URL('..', import.meta.url)).replace(/[\\\\/]+$/, '') + '.outside/gate.json'`,
+ ),
+ ],
+ module: [
+ `import { readFileSync as readGate } from 'node:fs'`,
+ readGateFile(
+ `new URL('../node_modules/gap-gate/gate.json', import.meta.url)`,
+ ),
+ ],
+ env: [
+ `const readInput = async () => ({ open: process.env.${INPUT_GATE_VAR} !== 'shut' })`,
+ ],
+ pluginConfig: [
+ `const readInput = async () => ({ open: __GAP_INPUT_GATE__ === 'open' })`,
+ ],
+ pluginTransform: [
+ `const readInput = async () => ({ open: __GAP_INPUT_GATE__ === 'open' })`,
+ ],
+ tsconfig: [
+ `class GateBase {}`,
+ `class GateField extends GateBase { field!: number }`,
+ `const readInput = async () => ({ open: Object.hasOwn(new GateField(), 'field') })`,
+ ],
+ configListing: [
+ `const readInput = async () => ({ open: __GAP_INPUT_GATE__ === 'open' })`,
+ ],
+ pluginWrite: [
+ `import { readFileSync as readGate } from 'node:fs'`,
+ readGateFile(`new URL('./gen.json', import.meta.url)`),
+ ],
+ stream: [
+ `import { createReadStream as streamGate } from 'node:fs'`,
+ `const readInput = async () => { const chunks: Array = []; for await (const chunk of streamGate(new URL('./gate.json', import.meta.url))) chunks.push(chunk as Buffer); return { open: JSON.parse(Buffer.concat(chunks).toString('utf8')).gate === 'open' } }`,
+ ],
+ listing: [
+ `import { readdirSync as listGate } from 'node:fs'`,
+ `const readInput = async () => ({ open: listGate(new URL('./gate-dir/', import.meta.url)).includes('open') })`,
+ ],
+ opendir: [
+ `import { opendirSync as openGate } from 'node:fs'`,
+ `const readInput = async () => { const dir = openGate(new URL('./gate-dir/', import.meta.url)); const names: Array = []; for (let entry = dir.readSync(); entry; entry = dir.readSync()) names.push(entry.name); dir.closeSync(); return { open: names.includes('open') } }`,
+ ],
+ stat: [
+ `import { statSync as statGate } from 'node:fs'`,
+ `const readInput = async () => ({ open: statGate(new URL('./gate.json', import.meta.url)).size === ${OPEN_SIZE} })`,
+ ],
+ statAsync: [
+ `import { stat as statGateAsync } from 'node:fs/promises'`,
+ `const readInput = async () => ({ open: (await statGateAsync(new URL('./gate.json', import.meta.url))).size === ${OPEN_SIZE} })`,
+ ],
+ statCallback: [
+ `import { stat as statGateCallback } from 'node:fs'`,
+ `const readInput = () => new Promise((resolve, reject) => statGateCallback(new URL('./gate.json', import.meta.url), (error, stats) => (error ? reject(error) : resolve({ open: stats.size === ${OPEN_SIZE} }))))`,
+ ],
+ append: [
+ `import { appendFileSync as appendGate, readFileSync as readGate } from 'node:fs'`,
+ `const readInput = async () => { const url = new URL('./gate.json', import.meta.url); appendGate(url, ''); return { open: JSON.parse(readGate(url, 'utf8')).gate === 'open' } }`,
+ ],
+ flagAppend: [
+ `import { writeFileSync as writeGate, readFileSync as readGate } from 'node:fs'`,
+ `const readInput = async () => { const url = new URL('./gate.json', import.meta.url); writeGate(url, '', { flag: 'a' }); return { open: JSON.parse(readGate(url, 'utf8')).gate === 'open' } }`,
+ ],
+ required: [
+ `import { createRequire as requireFrom } from 'node:module'`,
+ `import { fileURLToPath as gatePath } from 'node:url'`,
+ `const readInput = async () => { const path = gatePath(new URL('./gate.json', import.meta.url)); const req = requireFrom(import.meta.url); delete req.cache[path]; return { open: req(path).gate === 'open' } }`,
+ ],
+ childRead: [
+ `import { execFileSync as runGateChild } from 'node:child_process'`,
+ `import { fileURLToPath as gatePath } from 'node:url'`,
+ `const readInput = async () => ({ open: JSON.parse(runGateChild(process.execPath, ['-e', "process.stdout.write(require('node:fs').readFileSync(process.argv[1], 'utf8'))", gatePath(new URL('./gate.json', import.meta.url))], { encoding: 'utf8' })).gate === 'open' })`,
+ ],
+ // File b reads the gate in a worker thread, which runs the same code and
+ // reports back through a message (worker_threads, #143).
+ requireMain: [
+ `import { createRequire as requireFrom } from 'node:module'`,
+ `const readInput = async () => { const req = requireFrom(import.meta.url); const path = req.resolve('./sub'); delete req.cache[path]; return { open: req(path).open === true } }`,
+ ],
+ requireType: [
+ `import { createRequire as requireFrom } from 'node:module'`,
+ `const readInput = async () => { const req = requireFrom(import.meta.url); const path = req.resolve('./sub'); delete req.cache[path]; return { open: req(path).open === true } }`,
+ ],
+ // A failed exclusive create of the existing gate file (CR-12): the write
+ // throws EEXIST, the test catches it, and then reads the file.
+ wxExisting: [
+ `import { writeFileSync as writeGate, readFileSync as readGate } from 'node:fs'`,
+ `const readInput = async () => { const url = new URL('./gate.json', import.meta.url); try { writeGate(url, '', { flag: 'wx' }) } catch { /* the file exists */ } return { open: JSON.parse(readGate(url, 'utf8')).gate === 'open' } }`,
+ ],
+ // An open for update without truncation writes no bytes here, and keeps
+ // the file's text, which the test then reads (CR-21).
+ rplus: [
+ `import { writeFileSync as writeGate, readFileSync as readGate } from 'node:fs'`,
+ `const readInput = async () => { const url = new URL('./gate.json', import.meta.url); writeGate(url, '', { flag: 'r+' }); return { open: JSON.parse(readGate(url, 'utf8')).gate === 'open' } }`,
+ ],
+ // A worker that starts a worker, which reads the gate (CR-25).
+ threadNested: [
+ `import { Worker as GateWorker } from 'node:worker_threads'`,
+ `import { fileURLToPath as gatePath } from 'node:url'`,
+ `const readInput = () => new Promise((resolve, reject) => { const outer = new GateWorker(${JSON.stringify(NESTED_OUTER)}, { eval: true, workerData: gatePath(new URL('./gate.json', import.meta.url)) }); outer.once('message', (open) => resolve({ open: open === true })); outer.once('error', reject) })`,
+ ],
+ // A child whose own write-log cannot be opened (a directory at its path):
+ // the child keeps its result, and the gate it read decides the verdict (CR-19).
+ childLost: [
+ `import { execFileSync as runGateChild } from 'node:child_process'`,
+ `import { mkdirSync as makeLogDir, rmSync as removeLog } from 'node:fs'`,
+ `import { fileURLToPath as gatePath } from 'node:url'`,
+ `const readInput = async () => { const log = process.env.ORACLE_GAPS_CHILD_WRITES; if (log) { removeLog(log, { force: true }); makeLogDir(log) } return { open: JSON.parse(runGateChild(process.execPath, ['-e', "process.stdout.write(require('node:fs').readFileSync(process.argv[1], 'utf8'))", gatePath(new URL('./gate.json', import.meta.url))], { encoding: 'utf8' })).gate === 'open' } }`,
+ ],
+ // A path spelled through a symbolic link and `..` (CR-22): the kernel opens
+ // a/gate.json, while a lexical reading of the same spelling names gate.json.
+ // The path is a string, because a URL's `..` is resolved before the call.
+ linkDotDot: [
+ `import { readFileSync as readGate } from 'node:fs'`,
+ `import { fileURLToPath as linkPath } from 'node:url'`,
+ `const readInput = async () => ({ open: JSON.parse(readGate(linkPath(new URL('.', import.meta.url)) + 'link/../gate.json', 'utf8')).gate === 'open' })`,
+ ],
+ // A worker whose code opens with 'use strict': its open is the gate only
+ // when its plain call sees no `this`, which holds in strict mode alone
+ // (CR-24: a capture prefix ahead of the directive makes the worker sloppy).
+ threadStrict: [
+ `import { Worker as GateWorker } from 'node:worker_threads'`,
+ `import { fileURLToPath as gatePath } from 'node:url'`,
+ `const readInput = () => new Promise((resolve, reject) => { const worker = new GateWorker(${JSON.stringify(STRICT_WORKER)}, { eval: true, workerData: gatePath(new URL('./gate.json', import.meta.url)) }); worker.once('message', (open) => resolve({ open: open === true })); worker.once('error', reject) })`,
+ ],
+ threadRead: [
+ `import { Worker as GateWorker } from 'node:worker_threads'`,
+ `import { fileURLToPath as gatePath } from 'node:url'`,
+ `const readInput = () => new Promise((resolve, reject) => { const worker = new GateWorker("const fs = require('node:fs'); const { parentPort, workerData } = require('node:worker_threads'); parentPort.postMessage(JSON.parse(fs.readFileSync(workerData, 'utf8')).gate === 'open')", { eval: true, workerData: gatePath(new URL('./gate.json', import.meta.url)) }); worker.once('message', (open) => resolve({ open: open === true })); worker.once('error', reject) })`,
+ ],
+}
+// File b's read of a file that its test's child process tree wrote
+// (`childWrite`): the grandchild writes `child.txt` in a new directory under
+// the OS temporary directory and prints the directory, which the child
+// passes on; file b tests that the file exists, which is a read of it by
+// existence and kind (G42's stat family), checks its text, and removes the
+// directory.
+const CHILD_WRITE = `const fs = require('node:fs'), os = require('node:os'), path = require('node:path'); const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gap-child-')); fs.writeFileSync(path.join(dir, 'child.txt'), 'written'); process.stdout.write(dir)`
+const CHILD_START = `process.stdout.write(require('node:child_process').execFileSync(process.execPath, ['-e', ${JSON.stringify(CHILD_WRITE)}], { encoding: 'utf8' }))`
+const childWriteRead = [
+ `import { execFileSync as runChild } from 'node:child_process'`,
+ `import { existsSync as childExists, readFileSync as readChild, rmSync as removeChild } from 'node:fs'`,
+ `import { join as joinChild } from 'node:path'`,
+ `const childDir = runChild(process.execPath, ['-e', ${JSON.stringify(CHILD_START)}], { encoding: 'utf8' })`,
+ `if (!childExists(joinChild(childDir, 'child.txt'))) throw new Error('the child process wrote no file')`,
+ `const childText = readChild(joinChild(childDir, 'child.txt'), 'utf8')`,
+ `removeChild(childDir, { recursive: true, force: true })`,
+ `if (childText !== 'written') throw new Error('the child process wrote another text')`,
+]
+// File b's own output (`ownOutput`), made in the run and read by it, which
+// the run must not record as an input: `created` (the test checks for a file,
+// its child process makes it, and the test reads and removes it), `copied`
+// (the test copies a file into a new directory, its child process reads the
+// copy, and the test removes the directory), and `listed` (the test lists a
+// new directory, writes a file into it, and lists it again). Each is a
+// read of a path that the run itself changes before the check ends.
+const CHILD_OWN_STAT = `const fs = require('node:fs'), os = require('node:os'), path = require('node:path'); const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gap-own-stat-')); if (!fs.existsSync(dir)) throw new Error('the child saw no directory it made'); process.stdout.write(dir)`
+const OWN_OUTPUT_READS = {
+ created: [
+ `import { execFileSync as ownRun } from 'node:child_process'`,
+ `import { mkdtempSync as ownMake, readFileSync as ownRead, rmSync as ownRemove, writeFileSync as ownWrite } from 'node:fs'`,
+ `import { tmpdir as ownTmp } from 'node:os'`,
+ `import { join as ownJoin } from 'node:path'`,
+ `const ownDirectory = ownMake(ownJoin(ownTmp(), 'gap-own-'))`,
+ `const ownFile = ownJoin(ownDirectory, 'made.txt')`,
+ `ownRun(process.execPath, ['-e', ${JSON.stringify(`const fs = require('node:fs'); let found = true; try { fs.readFileSync(process.argv[1]) } catch { found = false } if (!found) fs.writeFileSync(process.argv[1], 'made')`)}, ownFile])`,
+ `if (ownRead(ownFile, 'utf8') !== 'made') throw new Error('the child made another text')`,
+ ],
+ copied: [
+ `import { execFileSync as ownRun } from 'node:child_process'`,
+ `import { copyFileSync as ownCopy, mkdtempSync as ownMake, rmSync as ownRemove } from 'node:fs'`,
+ `import { tmpdir as ownTmp } from 'node:os'`,
+ `import { fileURLToPath as ownPath } from 'node:url'`,
+ `import { join as ownJoin } from 'node:path'`,
+ `const ownCopyDirectory = ownMake(ownJoin(ownTmp(), 'gap-copy-'))`,
+ `const ownCopied = ownJoin(ownCopyDirectory, 'strict.ts')`,
+ `ownCopy(ownPath(new URL('./strict.ts', import.meta.url)), ownCopied)`,
+ `const ownText = ownRun(process.execPath, ['-e', ${JSON.stringify(`process.stdout.write(require('node:fs').readFileSync(process.argv[1], 'utf8').slice(0, 12))`)}, ownCopied], { encoding: 'utf8' })`,
+ `if (ownText.length === 0) throw new Error('the child read no copy')`,
+ `ownRemove(ownCopyDirectory, { recursive: true, force: true })`,
+ ],
+ listed: [
+ `import { existsSync as ownExists, mkdtempSync as ownMake, readdirSync as ownList, rmSync as ownRemove, writeFileSync as ownWrite } from 'node:fs'`,
+ `import { tmpdir as ownTmp } from 'node:os'`,
+ `import { join as ownJoin } from 'node:path'`,
+ `const ownListDirectory = ownMake(ownJoin(ownTmp(), 'gap-list-'))`,
+ `if (ownList(ownListDirectory).length !== 0) throw new Error('the new directory held entries')`,
+ `ownWrite(ownJoin(ownListDirectory, 'report.json'), '{}')`,
+ `if (ownList(ownListDirectory).length !== 1) throw new Error('the directory did not hold the report')`,
+ `if (!ownExists(ownListDirectory)) throw new Error('the directory the test made was gone')`,
+ `ownRemove(ownListDirectory, { recursive: true, force: true })`,
+ ],
+ // The child process makes the directory and checks it (existsSync, a stat in
+ // the child) and passes its name back; the test then checks it too (present,
+ // made by its tree before the check) and removes it. Both reads are of the
+ // tree's own output, which the run must not record (check.mjs, foldChildren
+ // and ownOutput): recorded, the directory's removal would move an input.
+ childStat: [
+ `import { execFileSync as ownRun } from 'node:child_process'`,
+ `import { existsSync as ownExists, rmSync as ownRemove } from 'node:fs'`,
+ `const ownStatDirectory = ownRun(process.execPath, ['-e', ${JSON.stringify(CHILD_OWN_STAT)}], { encoding: 'utf8' })`,
+ `if (!ownExists(ownStatDirectory)) throw new Error('the test saw no directory its child made')`,
+ `ownRemove(ownStatDirectory, { recursive: true, force: true })`,
+ ],
+}
+/** The variables a check of `state` runs with: the gate's, under `env`. */
+const inputEnv = (plan, state) =>
+ plan.inputRead === `env`
+ ? { [INPUT_GATE_VAR]: state.inputOpen ? `open` : `shut` }
+ : {}
+
+// The gate kinds whose file the config's plugins, Vite, or the config read in
+// the CLI process, so the session holds them as its inputs (check.mjs,
+// `reading`; pluginWrite is the session's own write, which a hand edit changes).
+export const PLUGIN_INPUT_READS = new Set([
+ `pluginConfig`,
+ `pluginTransform`,
+ `tsconfig`,
+ `configListing`,
+ `pluginWrite`,
+])
+
+// The restart rule (G34, the daemon restarts when a tracked environment or
+// plugin input changes; daemon.mjs `envKey(message.env) !== ownEnv` and
+// `codeIdentity() !== code`, check.mjs `inputsChanged`). A check through the
+// daemon is served by the daemon that its previous check was served by unless
+// one of these changed since that check: the environment its CLI sent, the
+// CLI's code (`cliCode`: the copy, its edited copy, or another install), or
+// the gate file of a plugin input (`inputOpen`, for a plugin gate kind). The
+// e2e oracle judges each pair of consecutive daemon checks that both reported
+// (check.pid) against this rule; a refused check's session is not judged
+// (law 9's limit).
+// For `pluginWrite` the gate file is the file the config's plugin writes at each
+// warm of the session (as `open`), so the `inputOpen` of a previous check is the
+// text that check left: `open` where its daemon warmed, else the hand edit's
+// state (the driver records it so). The daemon's session (check.mjs, `written`,
+// inputsChanged) compares the file's text with what it wrote, so a hand edit
+// that the next warm wrote back is no change of the session's input.
+const envOf = (env) => JSON.stringify(Object.entries(env ?? {}).sort())
+// The gate kinds the session reads at config time (its open and each warm-up),
+// so the session holds them as inputs from the start of a daemon's session.
+export const CONFIG_GATE_READS = new Set([
+ `pluginConfig`,
+ `tsconfig`,
+ `configListing`,
+ `pluginWrite`,
+])
+// A transform-time read (pluginTransform) is a unit's input, not a session
+// read: the plugin's transform runs where a unit computes, and the session
+// records the gate only then. So a gate change owes a restart only after a
+// check that ran a unit (`ran`: the previous check's computed units), where the
+// transform could have read the gate in the session (law 9's limit: a check
+// that ran a unit for other files only is judged the same).
+export const restartOwed = (plan, check, previous) =>
+ envOf(check.env) !== envOf(previous.env) ||
+ check.cliCode !== previous.cliCode ||
+ (CONFIG_GATE_READS.has(plan.inputRead) &&
+ check.inputOpen !== previous.inputOpen) ||
+ (plan.inputRead === `pluginTransform` &&
+ previous.ran > 0 &&
+ check.inputOpen !== previous.inputOpen)
+
+// The steps after which a check's daemon is a new process by the step's own
+// act (a start, a kill, a stop, a reset, a mid-run edit): the restart law
+// does not judge that check's pid. Every other step's pid is judged.
+export const RESTART_NOT_JUDGED = new Set([
+ `start`,
+ `restart`,
+ `crash`,
+ `crashAtOnce`,
+ `reboot`,
+ `reusedPid`,
+ `stopAtOnce`,
+ `dieMidCheck`,
+ `resetBeforeRead`,
+])
+// The steps that end the daemon which ran their check, after the check ran (a
+// kill or a stop of the held or reset daemon, a mid-run edit's restart): the
+// pair that starts after one of them is not judged.
+const ENDS_DAEMON_AFTER = new Set([
+ `dieMidCheck`,
+ `resetBeforeRead`,
+ `stopAtOnce`,
+ `midrun`,
+])
+/**
+ * Whether the restart law judges the pid of `check` against the pid of the
+ * check before it (`previous`, undefined when none has a pid). The law's rule
+ * (law 9): it judges a pair of consecutive daemon checks only when both
+ * reported, neither check's step ends or replaces its daemon by its own act
+ * (RESTART_NOT_JUDGED, ENDS_DAEMON_AFTER), and the CLI's daemon protocol did
+ * not replace the daemon between them: neither check fell back to a cold run
+ * (`fellBack`: its daemon held it past the CLI's bound, or sent nothing, so
+ * the CLI started a fresh daemon or ran cold; a start past the bound is one
+ * such check). A start is no end: the daemon it makes serves the next check.
+ */
+// The steps that remove the daemon's lock with the state directory
+// (cleanState). The daemon's lock watch runs every 2 s, so the daemon that
+// served the check before the removal, or the one after it, may leave at its
+// next watch tick and be replaced by a new daemon at the following check. The
+// protocol does this (daemon.mjs `watch`: "the lock names another daemon"),
+// and the law says the state goes while the daemon may still run; so neither
+// the step's own check nor the check after it is judged. Not judged means no
+// pid is recorded for them (the restart observation, law 9).
+export const LOCK_LOST_AT = new Set([`cleanState`])
+export const restartJudged = (step, previousStep, check, previous) =>
+ previous !== undefined &&
+ previous.pid !== undefined &&
+ !RESTART_NOT_JUDGED.has(step) &&
+ !LOCK_LOST_AT.has(step) &&
+ !LOCK_LOST_AT.has(previousStep) &&
+ step !== `midrun` &&
+ !ENDS_DAEMON_AFTER.has(previousStep) &&
+ check.reported &&
+ previous.reported &&
+ !check.fellBack &&
+ !previous.fellBack
+
function oracleTestFile(plan, file, state = undefined) {
const sites = sitesOf(plan)
const entries = [
@@ -6535,6 +7148,9 @@ function oracleTestFile(plan, file, state = undefined) {
const out = [
// A per-file environment, which Vitest reads from the file's text.
...(plan.pragma && file === `a` ? [`// @vitest-environment marked`] : []),
+ ...(plan.childEnvironment === `client` && file === `b`
+ ? [`// @vitest-environment client-marked`]
+ : []),
`import { ${holdsFailingLaw(plan, file) && plan.failingLawHook !== `none` ? `${plan.failingLawHook}, ` : ``}${plan.tests.some((t) => t.file === file && t.cleanupThrows) ? `afterEach, ` : ``}describe, expect, test${plan.tests.some((t) => t.file === file && (t.spies || t.timed === `spiedclock`)) ? `, vi` : ``} } from 'vitest'`,
...(plan.tests.some((t) => t.file === file && t.shrinks)
? [`import fc from 'fast-check'`]
@@ -6605,6 +7221,13 @@ function oracleTestFile(plan, file, state = undefined) {
`import * as sut from '../src/sut'`,
...(file === `b` ? [`import { strict } from './strict'`] : []),
...(file === `b` && plan.fsRead !== `none` ? dataReads[plan.fsRead] : []),
+ ...(file === `b` && plan.inputRead !== `none`
+ ? inputReads[plan.inputRead]
+ : []),
+ ...(file === `b` && plan.childWrite ? childWriteRead : []),
+ ...(file === `b` && plan.ownOutput !== `none`
+ ? OWN_OUTPUT_READS[plan.ownOutput]
+ : []),
...stubs,
// State that tests of this file share (the `w_shared` witness).
`const shared = { value: 0 }`,
@@ -6881,7 +7504,7 @@ function oracleTestFile(plan, file, state = undefined) {
// A lazy gate is imported only where the output differs, so
// the unmutated run never loads it. It is open before any
// edit, so the model need not read it.
- ` if (${when} && JSON.stringify(${out}) !== ${JSON.stringify(expected)}${lazyGated(plan, file, t) ? ` && (await import('./lazy')).open` : ``}${fsGated(plan, file, t) ? ` && (await readData()).open` : ``}) {`,
+ ` if (${when} && JSON.stringify(${out}) !== ${JSON.stringify(expected)}${lazyGated(plan, file, t) ? ` && (await import('./lazy')).open` : ``}${fsGated(plan, file, t) ? ` && (await readData()).open` : ``}${inputGated(plan, file, t) ? ` && (await readInput()).open` : ``}) {`,
` g.__oracleVerdict?.({ property: 'fixture-${file}', law: '${t.law}', checkpoint: 'trace' })`,
` throw new Error('violation')`,
` }`,
@@ -6899,7 +7522,7 @@ function oracleTestFile(plan, file, state = undefined) {
: []),
t.asProp
? ` fcTest.prop([fcv.integer({ min: ${PROPERTY.min}, max: ${PROPERTY.max} })], { numRuns: ${PROPERTY.numRuns}, seed: ${PROPERTY.seed} })('${testName(t, index)}', async (n) => {`
- : ` test('${testName(t, index)}', ${hangsIn(t) || t.slow || t.ioWait || t.timerWait || t.pendingIo || t.timed || lazyGated(plan, file, t) || fsGated(plan, file, t) ? `async ` : ``}() => {`,
+ : ` test('${testName(t, index)}', ${hangsIn(t) || t.slow || t.ioWait || t.timerWait || t.pendingIo || t.timed || lazyGated(plan, file, t) || fsGated(plan, file, t) || inputGated(plan, file, t) ? `async ` : ``}() => {`,
...partsOf(t).flatMap(campaign),
` })`,
`})`,
@@ -6921,7 +7544,7 @@ function oracleTestFile(plan, file, state = undefined) {
`test('fixed seed 999', () => {})`,
)
// The mid-run edit: the first run of this test after the driver marks an
- // edit pending (`midrun.txt`, `pending:`) rewrites file b's
+ // edit pending (`.oracle-gaps-midrun.txt`, `pending:`) rewrites file b's
// helper, or the data file, with that value and marks the edit done, so
// every later run of it, in this check or another, changes nothing. It
// calls nothing of the source under test, so no mutant reaches it. In
@@ -6934,7 +7557,11 @@ function oracleTestFile(plan, file, state = undefined) {
// after the helper edit, starts from an edited text, which a guard of the
// first state would fail on, so its edit would never land (#165).
const midrunRead =
- plan.midrunTarget === `data` ? `(await readData()).open` : `strict`
+ plan.midrunTarget === `data`
+ ? `(await readData()).open`
+ : plan.midrunTarget === `gate`
+ ? `(await readInput()).open`
+ : `strict`
if (plan.midrun && file === plan.midrunBy)
out.push(
`test('${MIDRUN_EDITORS[plan.midrunTarget].test}', async () => {`,
@@ -6943,21 +7570,24 @@ function oracleTestFile(plan, file, state = undefined) {
: [
` if (${(state?.midrunFrom ?? true) ? `!(${midrunRead})` : midrunRead}) throw new Error('${MIDRUN_EDITORS[plan.midrunTarget].message}')`,
]),
- // The marker sits in the run's own session directory, beside the
- // runner's harness (the worker's first setup file), which is no input
- // of a run by design (check.mjs, ownHarness). So the marker's own edit
- // does not decide whether the run is stored: only the helper's or the
- // data's text does. A run with no harness, or no marker, edits nothing.
+ // The marker sits in the package, beside the daemon's session directory
+ // (the worker's first setup file is there), and it is runner-owned
+ // (inputs.mjs isRunnerFile), so the marker's own edit does not decide
+ // whether the run is stored: only the helper's or the data's text does.
+ // A run with no harness, or no marker, edits nothing.
` const harness = (globalThis as { __vitest_worker__?: { config?: { setupFiles?: Array } } }).__vitest_worker__?.config?.setupFiles?.[0]`,
` if (!harness) return`,
- ` const marker = markerPath(markerDir(harness), 'midrun.txt')`,
+ ` const marker = markerPath(markerDir(markerDir(harness)), '.oracle-gaps-midrun.txt')`,
` let text = ''`,
` try { text = readMarker(marker, 'utf8') } catch { return }`,
` if (!text.startsWith('pending:')) return`,
` const value = text.slice('pending:'.length).trim()`,
plan.midrunTarget === `data`
? ` writeEdit(new URL('./data.json', import.meta.url), \`{"open":\${value}}\\n\`)`
- : ` writeEdit(new URL('./strict.ts', import.meta.url), \`export const strict = \${value}\\n\`)`,
+ : plan.midrunTarget === `gate`
+ ? // The gate file, as the gate kind writes it, open or shut.
+ ` writeEdit(new URL('./gate.json', import.meta.url), value === 'true' ? ${JSON.stringify(gateTextFor(plan.inputRead, true))} : ${JSON.stringify(gateTextFor(plan.inputRead, false))})`
+ : ` writeEdit(new URL('./strict.ts', import.meta.url), \`export const strict = \${value}\\n\`)`,
` writeEdit(marker, 'done\\n')`,
`})`,
)
@@ -7161,13 +7791,21 @@ const MIDRUN_EDITORS = {
test: `edits the data during the check`,
message: `the data this run read is closed`,
},
+ gate: {
+ test: `edits the gate during the check`,
+ message: `the gate this run read is shut`,
+ },
}
/** What a mid-run edit changes: the data file only when file b reads one. */
const midrunTargetOf = (history) =>
- history.midrunTarget === `data` && (history.fsRead ?? `none`) !== `none`
- ? `data`
- : `helper`
+ // A gate file that the history's gate kind reads (`midrunGate`, a build-only
+ // flag: the drawn `midrunTarget` keeps its values, so main's draws stay).
+ history.midrunGate === true && gateFiles[history.inputRead] !== undefined
+ ? `gate`
+ : history.midrunTarget === `data` && (history.fsRead ?? `none`) !== `none`
+ ? `data`
+ : `helper`
// Law 9's fixture state: the history, and what the edits outside it set.
const initialState = (plan) => ({
@@ -7178,6 +7816,8 @@ const initialState = (plan) => ({
lazyOpen: true,
// What `tests/data.json` holds: whether file b's data gate is open.
dataOpen: true,
+ // Whether file b's gate input reads `open` (`inputRead`).
+ inputOpen: true,
// How many mid-run edits have landed (`midrun`).
midruns: 0,
// What the mid-run edit's target held before the latest one landed, which
@@ -7212,17 +7852,63 @@ const PRE_PLUGIN = `{ name: 'gap-pre-rewrite', enforce: 'pre', transform(code, i
// memory, so only the runner's own \`load\` can answer for it (review of #103).
const LOAD_PLUGIN = `{ name: 'gap-own-load', load(id) { const path = id.split('?')[0]; return path.endsWith('.test.ts') ? readFileSync(path, 'utf8') : undefined } }`
+// The config's own plugin that writes a scratch file beside the config, tests
+// whether it exists, and removes it, at each resolve (`scratchPlugin`). The
+// stat of the session's own write is no input (check.mjs, ownWrite; CR-3).
+// The config's own plugin, frozen (`frozenPlugin`): a runner's wrapper cannot be assigned to its hooks (CR-2).
+const FROZEN_PLUGIN = `{ name: 'gap-frozen', transform(code) { return undefined } }`
+const SCRATCH_PLUGIN = `{ name: 'gap-scratch', configResolved() { const path = new URL('./gap-scratch.txt', import.meta.url); writeScratch(path, 'scratch\\n'); if (scratchExists(path)) removeScratch(path) } }`
+// The same plugin in a CommonJS config, which has no `import.meta`: its file is
+// named by `__dirname`, as the CommonJS gate path is (a config that wrote the
+// ESM form threw at resolve and refused, the run naming no config).
+const SCRATCH_PLUGIN_CJS = `{ name: 'gap-scratch', configResolved() { const path = require('node:url').pathToFileURL(require('node:path').join(__dirname, 'gap-scratch.txt')); writeScratch(path, 'scratch\\n'); if (scratchExists(path)) removeScratch(path) } }`
+// The config's own plugin that reads the gate file (`inputRead`
+// `pluginConfig` or `pluginTransform`) and writes its word in place of
+// `__GAP_INPUT_GATE__` in each test file it transforms. It finds the file
+// from the config's own location (`gatePath`), not from a root, which a
+// config's test root moves. `pluginConfig` reads it once, when the config
+// resolves; `pluginTransform` reads it in each transform.
+const GATE_READ = `JSON.parse(readGate(gatePath, 'utf8')).gate`
+const gatePlugin = (plan) =>
+ plan.inputRead === `pluginWrite`
+ ? `{ name: 'gap-input-gate', configResolved() { writeGate(gatePath, '{"gate":"open"}\\n') } }`
+ : `(() => { let gate; return { name: 'gap-input-gate', configResolved() { ${plan.inputRead === `pluginConfig` ? `gate = ${GATE_READ}` : ``} }, transform(code, id) { return id.split('?')[0].endsWith('.test.ts') ? code.replaceAll('__GAP_INPUT_GATE__', JSON.stringify(${plan.inputRead === `pluginConfig` ? `gate` : GATE_READ})) : undefined } } })()`
+// The gate file's path from a config at `configPath` (in the package, or in
+// its parent, where the package is the directory `pkg`).
+const gateFromConfig = (configPath, target = `tests/plugin-gate.json`) =>
+ posixPath.relative(
+ posixPath.dirname(posixPath.join(`/pkg`, configPath)),
+ `/pkg/${target}`,
+ )
+// The file or directory the config reads or writes, by gate kind.
+const configTargets = {
+ configListing: `tests/gate-dir`,
+ pluginWrite: `tests/gen.json`,
+}
+
/**
* The text of the package's config, in its syntax (`configOf`), with the
* fault, the top-level await, or the `require` calls the plan holds. `test`
* is the config's `test` object.
*/
-function configText(plan, test) {
+function configText(plan, test, configPath = plan.configPath) {
const commonjs = plan.configSyntax === `cjs`
const plugins = [
...(plan.prePlugin ? [PRE_PLUGIN] : []),
+ ...(plan.scratchPlugin
+ ? [commonjs ? SCRATCH_PLUGIN_CJS : SCRATCH_PLUGIN]
+ : []),
+ ...(plan.frozenPlugin ? [`Object.freeze(${FROZEN_PLUGIN})`] : []),
...(plan.loadPlugin ? [LOAD_PLUGIN] : []),
+ ...(pluginGated(plan) || plan.inputRead === `pluginWrite`
+ ? [gatePlugin(plan)]
+ : []),
]
+ // The config's listing of the gate directory, given to the tests.
+ const define =
+ plan.inputRead === `configListing`
+ ? `, define: { __GAP_INPUT_GATE__: JSON.stringify(listGate(gatePath).includes('open') ? 'open' : 'shut') }`
+ : ``
const config = `defineConfig(${
{ object: ``, function: `() => (`, async: `async () => (`, promise: `` }[
plan.config
@@ -7231,7 +7917,7 @@ function configText(plan, test) {
plan.fault === `projects`
? `{ projects: [{ test: { name: 'unit', ...${test} } }] }`
: test
- }${plugins.length > 0 ? `, plugins: [${plugins.join(`, `)}]` : ``} }${plan.config === `object` || plan.config === `promise` ? `` : `)`})`
+ }${plugins.length > 0 ? `, plugins: [${plugins.join(`, `)}]` : ``}${define} }${plan.config === `object` || plan.config === `promise` ? `` : `)`})`
// A promise of the config, a null default, or a config cut off mid-object.
const body =
plan.fault === `configNull`
@@ -7250,6 +7936,26 @@ function configText(plan, test) {
: [`import { fileURLToPath } from 'node:url'`]),
// Only a config in ES module syntax has the load plugin (`loadPluginOf`).
...(plan.loadPlugin ? [`import { readFileSync } from 'node:fs'`] : []),
+ ...(plan.scratchPlugin
+ ? commonjs
+ ? [
+ `const { writeFileSync: writeScratch, existsSync: scratchExists, unlinkSync: removeScratch } = require('node:fs')`,
+ ]
+ : [
+ `import { writeFileSync as writeScratch, existsSync as scratchExists, unlinkSync as removeScratch } from 'node:fs'`,
+ ]
+ : []),
+ ...(configGated(plan)
+ ? commonjs
+ ? [
+ `const { readFileSync: readGate, readdirSync: listGate, writeFileSync: writeGate } = require('node:fs')`,
+ `const gatePath = require('node:path').join(__dirname, '${gateFromConfig(configPath, configTargets[plan.inputRead])}')`,
+ ]
+ : [
+ `import { readFileSync as readGate, readdirSync as listGate, writeFileSync as writeGate } from 'node:fs'`,
+ `const gatePath = new URL('${gateFromConfig(configPath, configTargets[plan.inputRead])}', import.meta.url)`,
+ ]
+ : []),
...(plan.fault === `configThrows`
? [`throw new Error('the fixture config broke')`]
: []),
@@ -7476,6 +8182,7 @@ function fixtureFiles(plan, state = initialState(plan)) {
[altConfigPath(plan)]: configText(
plan,
test.replace(`'tests/**/*.test.ts'`, `'tests/a.test.ts'`),
+ altConfigPath(plan),
),
}
: {}),
@@ -7499,6 +8206,49 @@ function fixtureFiles(plan, state = initialState(plan)) {
...(plan.fsRead !== `none`
? { 'tests/data.json': `${JSON.stringify({ open: state.dataOpen })}\n` }
: {}),
+ // The gate file, which under `keepStamp` gets back one modification
+ // time each time it is written.
+ // The gate directory of a listing, which holds one empty file, named
+ // by the gate's word.
+ ...([`listing`, `opendir`, `configListing`].includes(plan.inputRead)
+ ? { [`tests/gate-dir/${state.inputOpen ? `open` : `shut`}`]: `` }
+ : {}),
+ // The package's tsconfig.json, read by Vite's own esbuild plugin.
+ ...(plan.inputRead === `tsconfig`
+ ? {
+ 'tsconfig.json': `${JSON.stringify({ compilerOptions: { target: `ES2022`, useDefineForClassFields: state.inputOpen } })}\n`,
+ }
+ : {}),
+ // The file the config's plugin writes, as a hand edit leaves it.
+ ...(plan.inputRead === `pluginWrite`
+ ? { 'tests/gen.json': gateText(state.inputOpen) }
+ : {}),
+ // A package that the test requires: its main picks one of two files
+ // (requireMain), or its type decides how a CommonJS file loads (requireType).
+ ...(plan.inputRead === `requireMain`
+ ? {
+ 'tests/sub/open.js': `module.exports = { open: true }\n`,
+ 'tests/sub/shut.js': `module.exports = { open: false }\n`,
+ }
+ : {}),
+ ...(plan.inputRead === `requireType`
+ ? { 'tests/sub/index.js': `module.exports = { open: true }\n` }
+ : {}),
+ // The link, and the directory it names, are fixture state, so the run
+ // only reads through them (CR-22).
+ ...(plan.inputRead === `linkDotDot`
+ ? { 'tests/a/b/keep.txt': `kept\n`, 'tests/link': { link: 'a/b' } }
+ : {}),
+ ...(gateFiles[plan.inputRead] === undefined
+ ? {}
+ : {
+ [gateFiles[plan.inputRead]]: plan.keepStamp
+ ? {
+ text: gateTextFor(plan.inputRead, state.inputOpen),
+ mtime: GATE_STAMP,
+ }
+ : gateTextFor(plan.inputRead, state.inputOpen),
+ }),
// A workspace dependency with module state, linked through node_modules.
'deps/state-dep/package.json': manifest({
name: `state-dep`,
@@ -7606,6 +8356,24 @@ function fixtureFiles(plan, state = initialState(plan)) {
].join(`\n`),
}
: {}),
+ // The client-transform environment that file b names when it reads what
+ // its child process wrote (`childEnvironment`).
+ ...(plan.childEnvironment === `client`
+ ? {
+ [`${testRoot.environments ?? `node_modules`}/vitest-environment-client-marked/package.json`]: `${JSON.stringify({ name: `vitest-environment-client-marked`, type: `module`, exports: `./index.js` })}\n`,
+ [`${testRoot.environments ?? `node_modules`}/vitest-environment-client-marked/index.js`]:
+ [
+ `export default {`,
+ ` name: 'client-marked',`,
+ ` viteEnvironment: 'client',`,
+ ` setup() {`,
+ ` return { teardown() {} }`,
+ ` },`,
+ `}`,
+ ``,
+ ].join(`\n`),
+ }
+ : {}),
// A copy that a check which died left behind (the runner names its
// copies `.oracle-gaps---`). It is no test file: a check
// that took it for one would refuse the run.
@@ -7621,10 +8389,18 @@ function fixtureFiles(plan, state = initialState(plan)) {
}
for (const file of oracleFilesOf(plan))
files[`tests/${file}.test.ts`] = oracleTestFile(plan, file, state)
+ // The hand edit of the file the plugin writes also changes file b's own
+ // text, so the daemon runs b again and reads the edited file.
+ if (
+ plan.inputRead === `pluginWrite` &&
+ files[`tests/b.test.ts`] !== undefined
+ )
+ files[`tests/b.test.ts`] +=
+ `// the plugin's file was edited to ${state.inputOpen ? `open` : `shut`}\n`
// Each mid-run edit changes file a's own text too (a count of them), so
// the daemon runs file a's tests again in the check the edit lands in,
- // instead of reusing their evidence: the marker sits in the daemon's
- // session directory, which is no input of a run.
+ // instead of reusing their evidence. The marker is runner-owned, so no run
+ // takes it as an input.
if (plan.midrun)
files[`tests/${plan.midrunBy}.test.ts`] +=
`// mid-run edits: ${state.midruns}\n`
@@ -7691,7 +8467,20 @@ function removePath(path) {
// The paths each fixture directory holds, so a state that lacks a file of
// the state before it removes that file.
const written = new Map()
-function writeFixture(dir, files) {
+// Where a fixture path lies: in the package, or beside it (`BESIDE`).
+const placeOf = (dir, path) =>
+ path.startsWith(BESIDE)
+ ? join(outsideOf(dir), path.slice(BESIDE.length))
+ : join(dir, path)
+// The state text a file had at the previous daemon check (`base`, a files map),
+// or undefined where every file is written (a start, a restart or crash step,
+// a cold run). A daemon check writes only the files whose state text changed
+// since that check (R1): a file that a plugin wrote since then keeps the
+// plugin's output, and the harness does not re-apply the hand edit over it as
+// if the history had edited the file again. Nothing else changes: the removal
+// of a file the state lacks, and the stamp of a file that is written.
+const sameState = (a, b) => JSON.stringify(a) === JSON.stringify(b)
+function writeFixture(dir, files, base) {
for (const sub of [
`src`,
`tests`,
@@ -7704,14 +8493,25 @@ function writeFixture(dir, files) {
if (!existsSync(join(dir, `node_modules/state-dep`)))
symlinkSync(`../deps/state-dep`, join(dir, `node_modules/state-dep`), `dir`)
for (const path of written.get(dir) ?? [])
- if (!(path in files)) removePath(join(dir, path))
- for (const [path, text] of Object.entries(files)) {
- const at = join(dir, path)
+ if (!(path in files)) removePath(placeOf(dir, path))
+ for (const [path, value] of Object.entries(files)) {
+ if (base !== undefined && sameState(base[path], value)) continue
+ const at = placeOf(dir, path)
mkdirSync(dirname(at), { recursive: true })
+ // A file may name the modification time it gets back (`keepStamp`).
+ const text = typeof value?.text === `string` ? value.text : value
// An unchanged file keeps its modification time, as in a real package.
if (typeof text === `string`) {
- if (!existsSync(at) || readFileSync(at, `utf8`) !== text)
- writeFileSync(at, text)
+ const changed = !existsSync(at) || readFileSync(at, `utf8`) !== text
+ if (changed) writeFileSync(at, text)
+ // The stamp is set after a content write, or where the time differs: a
+ // utimes call always advances the ctime, which a stat input reads, so an
+ // unchanged recheck must not make one (CR-20).
+ if (
+ value.mtime !== undefined &&
+ (changed || Math.floor(statSync(at).mtimeMs / 1000) !== value.mtime)
+ )
+ utimesSync(at, value.mtime, value.mtime)
} else if (linkTarget(at) !== text.link) {
// A link that a later state points elsewhere is replaced.
removePath(at)
@@ -7783,21 +8583,29 @@ function applyEdit(state, edit) {
// A mid-run edit leaves file b's helper as the helper edit does.
if (edit === `helper`) return { ...state, strict: !state.strict }
if (edit === `midrun`)
- return midrunTargetOf(state.history) === `data`
+ return midrunTargetOf(state.history) === `gate`
? {
...state,
- dataOpen: !state.dataOpen,
+ inputOpen: !state.inputOpen,
midruns: state.midruns + 1,
- midrunFrom: state.dataOpen,
- }
- : {
- ...state,
- strict: !state.strict,
- midruns: state.midruns + 1,
- midrunFrom: state.strict,
+ midrunFrom: state.inputOpen,
}
+ : midrunTargetOf(state.history) === `data`
+ ? {
+ ...state,
+ dataOpen: !state.dataOpen,
+ midruns: state.midruns + 1,
+ midrunFrom: state.dataOpen,
+ }
+ : {
+ ...state,
+ strict: !state.strict,
+ midruns: state.midruns + 1,
+ midrunFrom: state.strict,
+ }
if (edit === `lazy`) return { ...state, lazyOpen: !state.lazyOpen }
if (edit === `fsData`) return { ...state, dataOpen: !state.dataOpen }
+ if (edit === `inputGate`) return { ...state, inputOpen: !state.inputOpen }
if (edit === `seed`) return { ...state, seed: state.seed === 1 ? 2 : 1 }
if (edit === `config`) return { ...state, altConfig: !state.altConfig }
// A seed no other step uses, so the check has fresh work to be killed in.
@@ -8052,10 +8860,16 @@ function readSummary(summary) {
export {
drawn,
+ gateFiles,
+ gateTextFor,
NO_STOPS,
NO_LATER_STEPS,
NO_FAULTS,
faults,
+ NO_INPUT_STEPS,
+ inputEdits,
+ inputEnv,
+ outsideOf,
MIDRUN_EDITORS,
captureWitness,
outsideRepository,
diff --git a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs
index 4544a7a6..6d7cb912 100644
--- a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs
+++ b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs
@@ -230,7 +230,10 @@
* state reports: the same exit status and refusal cause, the same run
* identity, results, and summary. Only how the result was produced may
* differ: durations, the options that name the output directory and the
- * daemon, and the counts of reused and computed evidence. The edits change
+ * daemon, and the counts of reused and computed evidence. A check through
+ * the daemon whose plugin hook cannot be recorded (a frozen hook object) is
+ * computed as a cold run computes it and stores no unit of it; its stream
+ * note names the plugin. The edits change
* a test, a source statement, the source's line numbers, an owns list,
* the authored mutant, a helper module that one oracle file imports, a
* module that a test imports only where its output differs, the
@@ -284,6 +287,49 @@
* hold released by the daemon's count of accepted requests, so its reach
* names a measured overlap, not two processes' timing. A completed check
* through the daemon names its own report in its done line.
+ * The daemon that serves a check is the one that served the check before
+ * it, unless an environment variable, the CLI's code, or a plugin gate
+ * file changed in between (the restart rule, G34: model restartOwed). The
+ * environment is the one each CLI sent, and a daemon keeps the environment
+ * of the CLI that started it: two checks at once that start it with the
+ * test-only hold variable (ORACLE_GAPS_TEST_HOLD_OVERLAP), so a check from
+ * a CLI without it restarts the daemon (daemon.mjs, envKey of the request
+ * against the daemon's own). A
+ * pluginWrite gate file is the file the config's plugin writes as `open` at
+ * each warm of the session, so a check whose daemon warmed leaves it open,
+ * and a hand edit that the next warm wrote back (or one that sets it to the
+ * text it already holds) changes no tracked input: the daemon is kept, and
+ * its check equals a cold run's (round 17, 2026-12-02; the probe in
+ * check.mjs `inputsChanged` shows the session holds the rewritten text).
+ * The law judges a pair of consecutive daemon checks only when both reported,
+ * neither check's step ends its daemon by its own act (a stop, kill or
+ * reset after the check, a start, a restart, a crash, a mid-run edit), and
+ * the CLI's daemon protocol did not replace the daemon between them: no
+ * cold fallback in either check (a start past the bound, a daemon that
+ * stopped answering, a held reply, a daemon that sent nothing; model
+ * restartJudged). Limit: a check that was refused before its session ran
+ * is not judged, so a plugin gate's restart after a refused start (which a
+ * session of pluginWrite opens) is outside this law. The mid-run scoping is
+ * accepted 2026-12-02 (coordinator): a mid-run edit restarts the daemon of
+ * the check it overlaps, so that check and the one after it are not judged
+ * against the rule; the mid-run family judges the edit instead.
+ * The cleanState step removes the state directory, daemon.lock included. The
+ * daemon's lock watch runs every 2 s, so the daemon that served the check
+ * before the removal may leave at its next watch tick and be replaced at the
+ * following check (daemon.mjs `watch`). The protocol does this, and the law
+ * says the daemon's state goes while the daemon may still run. So neither the
+ * cleanState check nor the check after it is judged (model LOCK_LOST_AT,
+ * accepted by the coordinator, 2026-12-03). Limit: a watch tick after two or
+ * more checks would still be a replacement the law does not judge; the
+ * exemption is bounded by the durations of the checks between the removal
+ * and the next tick.
+ * A transform-time gate read (pluginTransform) is a unit input, not a
+ * session read: a plugin's transform runs where a unit computes, so a gate
+ * change owes a restart only after a check that ran a unit (model
+ * restartOwed, CONFIG_GATE_READS and `ran`; decision 2026-12-03). The
+ * config-time gate kinds (pluginConfig, tsconfig, configListing,
+ * pluginWrite) owe the restart on every change. Limit: a check that ran a
+ * unit for other files only is judged the same way.
* 10. **The runner runs the package as Vitest does.** From any install path
* (one with a space and `#` included), for any spelling of `--source`
* (`./`, a redundant segment, an absolute path through a symbolic link
@@ -526,10 +572,26 @@
* the check it overlaps must report, for each mutant, what a cold run of
* the state before or after the edit reports, and the runner must store no
* run under a text it did not read (see the limits). An edit can change a
- * file that a test reads through `fs` (`fsData`). Law 9's edits do not
- * include an environment variable other than the seed, a new file that changes how an
+ * file that a test reads through `fs` (`fsData`), and the gate input that
+ * file b's verdict reads (`inputGate`): a file in the package, outside it,
+ * or under node_modules, the variable GAP_INPUT_GATE, or a file the config's
+ * own plugin reads, since every read is a daemon input (maintainer decision,
+ * 2026-11-16). Law 9's edits do not include another environment variable
+ * than the seed and the gate's, a new file that changes how an
* unchanged import resolves, a change to the Vite config or the installed
* packages, or checks at once other than the two that start the daemon.
+ * Own output (law 9, round 13, 2026-12-02; accepted 2026-12-02 (maintainer)):
+ * a path the run's own process tree wrote, created or copied before the read,
+ * is not an input, and a directory the run added entries to is not an input;
+ * mkdir and mkdtemp count as writes (the constructed histories `ownOutput`: a
+ * test whose child makes the file it checks for, a copy its child reads, a
+ * listing before a write, a directory its child makes, checks, and removes). A
+ * path the run reads present and then changes, which the tree did not write
+ * first, is an input that moved, so its run is not stored (a file the test
+ * rewrites with different content each run). The limit, accepted 2026-12-02
+ * (maintainer): a later run that finds a leftover of an earlier run at such a
+ * path reuses the stored run, so a test whose outcome depends on its own
+ * leftover is not hermetic, and is not covered.
* The harness keeps every global a copy defines configurable, by wrapping
* `Object.defineProperty`, `Object.defineProperties`, and
* `Reflect.defineProperty`, so that each copy in the shared realm starts
@@ -538,6 +600,7 @@
* under the report, which law 3's capture clause does not cover
* (maintainer decision, 2026-11-08; such a test belongs outside the
* owns-declaring files). The daemon count after a stop is read from the process list. Two
+ * owns-declaring files). The daemon count after a stop is read from the process list. Two
* daemon defects have no observation here: a stale lock removed without
* the atomic claim (two daemons serve until the loser sees its lock taken,
* within 2 s), and a stop that releases the lock before it closes the
@@ -692,12 +755,22 @@ import {
sourceArgument,
outsideRepository,
ENV_PREFIX,
+ gateFiles,
+ gateTextFor,
HEARTBEAT_MS,
FULL_LIMIT_MS,
backstopOf,
NO_LATER_STEPS,
NO_STOPS,
NO_FAULTS,
+ NO_INPUT_STEPS,
+ inputEnv,
+ outsideOf,
+ PLUGIN_INPUT_READS,
+ RESTART_NOT_JUDGED,
+ LOCK_LOST_AT,
+ restartJudged,
+ restartOwed,
} from './gap-report-model-oracle.mjs'
const here = dirname(fileURLToPath(import.meta.url))
@@ -974,7 +1047,7 @@ function beforeLastLine(stderr, foreign) {
}
function runCli(dir, files, how = {}) {
- writeFixture(dir, files)
+ writeFixture(dir, files, how.fixtureBase)
const before = new Set(filesUnder(dir))
const { args, out: outBase } = cliArgs(dir, files, how)
// Each call has its own output directory: its retention lines are then its own, even when a
@@ -2207,7 +2280,7 @@ const byRole = (a, b) => {
* starts, so a driver can watch the directory its own call writes.
*/
async function runClisAtOnce(dir, files, hows, outs = []) {
- writeFixture(dir, files)
+ writeFixture(dir, files, hows[0]?.fixtureBase)
return Promise.all(
hows.map(async (how) => {
const { args, out: outBase } = cliArgs(dir, files, how)
@@ -2297,6 +2370,10 @@ function namedScratch(text, names) {
// check runs cold instead (R39: a cold fallback names its cause).
const coldFallbackNote =
/^oracle-gaps: note the package's daemon sent nothing for \d+ s; this check runs cold/
+// The note a CLI writes for a plugin whose hook object is frozen, so that its
+// hooks cannot be recorded: the check runs cold and stores no unit (CR-2).
+const frozenPluginNote =
+ /^oracle-gaps: note plugin gap-frozen has a frozen hook object: this check runs cold and stores no unit of it$/
// A run's own output directory, `out`, named `` in each
// spelling the stack may use, wherever it is a whole path: not followed by
@@ -2813,6 +2890,9 @@ function readRunIn(dir, out, status, stderr, cli, stdout, derived) {
laws: r.laws,
// The cut that ended a timeout (classify.mjs `outcomeOf`).
cause: r.outcome === `timeout` ? r.detail : undefined,
+ // The error that a crash's first failing test threw (classify.mjs
+ // `outcomeOf`), so a classification violation names the crash.
+ crash: r.outcome === `crashed` ? r.detail : undefined,
// The built-in law of a kill that a cut by count or state decided
// (bounded work or no progress), null for a behavioral law.
builtIn:
@@ -2896,6 +2976,16 @@ const waitGone = async (pid) => {
* The paths that the package's daemon stored any run under, from its
* evidence store (evidence.mjs), or none when it has stored nothing.
*/
+// Whether the package's store holds no unit. A store that cannot be read (the
+// corruptStore step overwrites it) decides no state: false, not a guess.
+function storedNoneReadable(dir) {
+ try {
+ return storedUnits(stateDirOf(realpathSync(dir))).length === 0
+ } catch {
+ return false
+ }
+}
+
function storedInputs(dir) {
return storedUnits(stateDirOf(realpathSync(dir))).flatMap((row) =>
row.variants.flatMap((variant) => variant.inputs.map(([path]) => path)),
@@ -2928,8 +3018,15 @@ async function incremental(dir, plan, cli, copy, observe, states) {
if (!reportText.includes(RUN_LINE))
throw new Error(`the cli edit no longer finds the summary's run line`)
const cold = new Map()
+ // A state is its files, its seed, its CLI, and the variables it sets.
const fingerprint = (files, state, other = false) =>
- JSON.stringify([files, state.seed, state.cliEdited, other])
+ JSON.stringify([
+ files,
+ state.seed,
+ state.cliEdited,
+ other,
+ inputEnv(plan, state),
+ ])
cold.set(fingerprint(fixtureFiles(plan), initialState(plan)), cli)
// A cold result without the run identity, which every edit changes, so
// that two states compare by what they report.
@@ -2977,9 +3074,50 @@ async function incremental(dir, plan, cli, copy, observe, states) {
markDirs.push(marks)
return marks
}
+ // The hold's mark is a fresh directory in every run, so a restart's recorded
+ // environment names it by the order it first appeared in this history, which
+ // is the same in each run of it (the determinism law). Its path is not an
+ // observation.
+ const holdMarks = new Map()
+ const markOrdinal = (path) => {
+ if (!holdMarks.has(path)) holdMarks.set(path, holdMarks.size + 1)
+ return holdMarks.get(path)
+ }
+ const recordedEnv = (env) =>
+ env === undefined
+ ? undefined
+ : Object.fromEntries(
+ Object.entries(env).map(([name, value]) => [
+ name,
+ name === `ORACLE_GAPS_TEST_HOLD_OVERLAP`
+ ? `hold mark ${markOrdinal(value)}`
+ : value,
+ ]),
+ )
// How many runs the daemon computed in a check of a state that nothing
// changed, where it owes none (undefined elsewhere).
let unchangedComputed
+ // The daemon check before this one, and the pid and inputs that served it
+ // (the restart observable, G34): undefined after a start or a kill. A pid
+ // is recorded as its ordinal among the daemons this history met (the first
+ // is 1), so the trace repeats between runs, where process ids do not.
+ // The files and step of the previous check (R1: writeFixture writes only what changed).
+ let lastFiles
+ let lastStep
+ let lastDaemon
+ // The gate text the last check wrote (`gateSeen`), and the text on disk after
+ // it (`gateOnDisk`): a pluginWrite warm rewrites the file as open (law 9).
+ let gateSeen = true
+ let gateOnDisk = true
+ const daemonOrdinals = new Map()
+ const ordinalOf = (pid) => {
+ if (!daemonOrdinals.has(pid))
+ daemonOrdinals.set(pid, daemonOrdinals.size + 1)
+ // DIAGNOSTIC (test-only, to revert): ordinal -> real pid, for violation text.
+ globalThis.__oracleRealPids ??= new Map()
+ globalThis.__oracleRealPids.set(daemonOrdinals.get(pid), pid)
+ return daemonOrdinals.get(pid)
+ }
// The check through the daemon during which a mid-run edit landed, and a
// cold run of the state before the edit (the `midrun` step).
let midrunChecks
@@ -3011,8 +3149,19 @@ async function incremental(dir, plan, cli, copy, observe, states) {
: reportText,
)
const files = fixtureFiles(resolveHistory(state.history), state)
+ // R1 (the driver's rule, writeFixture): a daemon check writes only the files
+ // whose state text changed since the previous check. A start, a restart or
+ // crash step, and a check after one write every file (fixtureBase undefined).
+ const previousStep = lastStep
+ const fixtureBase =
+ RESTART_NOT_JUDGED.has(step) || RESTART_NOT_JUDGED.has(previousStep)
+ ? undefined
+ : lastFiles
+ lastFiles = files
+ lastStep = step
const key = fingerprint(files, state, step === `otherInstall`)
const how = {
+ fixtureBase,
seed: state.seed,
outMode: plan.outMode,
unsupervised: plan.unsupervised,
@@ -3025,11 +3174,15 @@ async function incremental(dir, plan, cli, copy, observe, states) {
...configArgs(plan),
// After the `config` edit, `--config` names the second config.
...(state.altConfig ? { config: altConfigPath(plan) } : {}),
- // A warm daemon's check under a 3 s bound (`shortWait`): one that works
+ // The gate variable of this state, when file b's verdicts read one, and
+ // a warm daemon's check under a 3 s bound (`shortWait`): one that works
// longer tells its CLI so, by its beats.
- ...(plan.shortWait && step !== `start`
- ? { env: { ORACLE_GAPS_TEST_WAIT_MS: `3000` } }
- : {}),
+ env: {
+ ...inputEnv(plan, state),
+ ...(plan.shortWait && step !== `start`
+ ? { ORACLE_GAPS_TEST_WAIT_MS: `3000` }
+ : {}),
+ },
}
// The first check may be two at once, which must reach one daemon, and
// so are the two after a crash.
@@ -3062,6 +3215,10 @@ async function incremental(dir, plan, cli, copy, observe, states) {
const hold = overlapMark
? { env: { ORACLE_GAPS_TEST_HOLD_OVERLAP: overlapMark } }
: {}
+ // The environment each of the checks at once sends: the hold's, which
+ // replaces the plan's (`...hold` above). The daemon they start keeps it, so
+ // the next check from another environment restarts the daemon (law 9).
+ const sentEnv = twice ? (hold.env ?? how.env) : how.env
const [daemon, ...others] = twice
? (
await runClisAtOnce(dir, files, [
@@ -3079,7 +3236,8 @@ async function incremental(dir, plan, cli, copy, observe, states) {
overlapMark !== undefined &&
existsSync(overlapMark) &&
Number(readFileSync(overlapMark, `utf8`)) >= 2
- if (!cold.has(key)) cold.set(key, runCli(dir, files, how))
+ if (!cold.has(key))
+ cold.set(key, runCli(dir, files, { ...how, fixtureBase: undefined }))
const coldRun = cold.get(key)
if (plan.outMode === `default`)
states.add(`a daemon check with the default output directory`)
@@ -3092,11 +3250,102 @@ async function incremental(dir, plan, cli, copy, observe, states) {
// after the daemon's earlier check of the same state, whose evidence is
// stored before it replies. So one of the two computes and the other
// reuses, whichever order the daemon took them in.
- const reuseOwed = plan.tests.every((t) => !t.flaky)
+ // A plugin whose hook cannot be recorded stores no unit, so its rechecks
+ // reuse nothing and compute as a cold run does (law 9, CR-2).
+ const reuseOwed = plan.tests.every((t) => !t.flaky) && !plan.frozenPlugin
unchangedComputed =
step === `recheck` && reuseOwed ? computedRuns(daemon) : undefined
const laterComputed =
twice && reuseOwed ? computedRuns(others[0]) : undefined
+ // The restart observable (G34): the pid that ran this check (check.pid),
+ // against the pid of the daemon's previous check. A start or a kill has no
+ // previous daemon to compare with, since its pid changes by its own act.
+ const cliCode =
+ step === `otherInstall` ? `other` : state.cliEdited ? `edited` : `copy`
+ // A mid-run edit restarts the daemon of the check it overlaps (midrun), and the
+ // check after it is not judged against the one before: the mid-run family
+ // judges that restart (law 9's limit).
+ const priorDaemon = lastDaemon
+ // Whether the CLI's protocol ran this check cold, after its daemon held it
+ // or sent nothing (heldPhase, slowOpen, a cold fallback, R39).
+ const fellBack =
+ daemon.held === true ||
+ daemon.stream.notes.some((note) => coldFallbackNote.test(note))
+ // The gate text that this check leaves for the next one (`inputOpen`). A
+ // pluginWrite gate is a file the config's plugin writes in configResolved,
+ // as `open` (gatePlugin), at every warm of the session: a daemon that
+ // warmed in this check (a start, or a new process id) leaves the file open,
+ // whatever the hand edit made, so the next check compares with `open`, not
+ // with the hand edit's state (law 9; the restart rule's pluginWrite limit).
+ // Any other check leaves the text the hand edit made.
+ const warmedHere =
+ daemon.checkPid !== undefined &&
+ (priorDaemon === undefined ||
+ ordinalOf(daemon.checkPid) !== priorDaemon.pid)
+ // The text the check starts on: a step that edits the gate (its state
+ // differs from the state the last check wrote) starts on the edit's state;
+ // any other step starts on the text the previous check left on disk, which
+ // a warm of the plugin rewrote as `open` (the restart law compares it).
+ const writesGate = state.inputOpen !== gateSeen
+ const startOpen =
+ plan.inputRead === `pluginWrite` && !writesGate
+ ? gateOnDisk
+ : state.inputOpen
+ const leftOpen =
+ plan.inputRead === `pluginWrite`
+ ? warmedHere
+ ? true
+ : startOpen
+ : state.inputOpen
+ gateSeen = state.inputOpen
+ gateOnDisk = leftOpen
+ lastDaemon =
+ daemon.checkPid === undefined
+ ? undefined
+ : {
+ pid: ordinalOf(daemon.checkPid),
+ env: sentEnv,
+ cliCode,
+ // The units this check computed: a transform-time gate read is a
+ // session input only where a unit ran (restartOwed).
+ ran: computedRuns(daemon),
+ inputOpen: leftOpen,
+ reported: daemon.reported === true,
+ fellBack,
+ step,
+ }
+ const restart =
+ daemon.checkPid === undefined
+ ? undefined
+ : {
+ step,
+ previousStep,
+ pid: ordinalOf(daemon.checkPid),
+ previousPid: priorDaemon?.pid,
+ env: recordedEnv(sentEnv),
+ previousEnv: recordedEnv(priorDaemon?.env),
+ cliCode,
+ previousCode: priorDaemon?.cliCode,
+ inputOpen: startOpen,
+ previousInputOpen: priorDaemon?.inputOpen,
+ reported: daemon.reported === true,
+ previousReported: priorDaemon?.reported,
+ fellBack,
+ previousFellBack: priorDaemon?.fellBack,
+ previousRan: priorDaemon?.ran,
+ }
+ // The restart observation is recorded only where the restart law judges
+ // it (model: restartJudged): a refused check's daemon pid depends on when
+ // the previous daemon exits, and a held check's on the CLI's fallback, so
+ // recording either would make the trace nondeterministic (law 9; S-3(a)).
+ const judged =
+ restart !== undefined &&
+ restartJudged(
+ step,
+ previousStep,
+ { reported: restart.reported, fellBack },
+ priorDaemon,
+ )
for (const [i, run] of [daemon, ...others].entries()) {
// A daemon's call: the daemon the driver killed during it, if any, or
// the one that held its check until the CLI fell back, wrote the lines
@@ -3122,6 +3371,7 @@ async function incremental(dir, plan, cli, copy, observe, states) {
step: i === 0 ? step : `${step} (a second check at once)`,
markerStored,
unchangedComputed: i === 0 ? unchangedComputed : laterComputed,
+ restart: i === 0 && judged ? restart : undefined,
midrun:
i === 0 && step === `midrun` && midrunChecks
? {
@@ -3224,6 +3474,25 @@ async function incremental(dir, plan, cli, copy, observe, states) {
[daemon, ...others].every((run) => run.refusal !== undefined)
)
states.add(`two checks at once on a session that cannot open`)
+ // A frozen plugin object (CR-2): the check named the plugin, and the store
+ // holds no unit of it (stored units are the session's, storedUnits).
+ if (
+ plan.frozenPlugin &&
+ daemon.stream.notes.some((note) => frozenPluginNote.test(note)) &&
+ storedNoneReadable(dir)
+ )
+ states.add(
+ `a check through the daemon with a frozen plugin object named it and stored no unit`,
+ )
+ // A daemon restart on a changed plugin input (G34): the check whose plugin
+ // gate file changed was served by a new daemon.
+ if (
+ judged &&
+ restart.pid !== restart.previousPid &&
+ PLUGIN_INPUT_READS.has(plan.inputRead) &&
+ restart.inputOpen !== restart.previousInputOpen
+ )
+ states.add(`a daemon restart on a changed plugin input`)
if (plan.fault === `brokenVitest` && daemon.refusal !== undefined)
states.add(`a session failure larger than a socket buffer`)
const after = {
@@ -3268,6 +3537,27 @@ async function incremental(dir, plan, cli, copy, observe, states) {
states.add(
`an unchanged check through the daemon computed nothing while a test read a source through fs`,
)
+ // File b read a file that its test's child process tree wrote, in a
+ // new temporary directory each run: the file is the tree's own output,
+ // so the unchanged recheck reused b's runs (`childWrite`).
+ if (plan.childWrite)
+ states.add(
+ `an unchanged check through the daemon computed nothing while a test read what its child process wrote`,
+ )
+ // File b made the files it reads during its run (`ownOutput`): the
+ // unchanged recheck reused b's runs, although each read was of the run's
+ // own output (check.mjs, settleIn; the own-output rule of law 9).
+ if (plan.ownOutput !== `none`)
+ states.add(
+ `an unchanged check through the daemon computed nothing while a test made the files it reads`,
+ )
+ // File a's test wrote to the process's streams, so its copy appended to
+ // the run's own test-output.log, which the run creates (capture-setup.mjs,
+ // isRunnerOwnAppend): the unchanged recheck reused a's runs.
+ if (plan.consoleOutput)
+ states.add(
+ `an unchanged check through the daemon computed nothing while a test wrote to the console`,
+ )
}
// A daemon check after an edit that computed fewer runs cut off by their
// call budget than the cold run of the same state reused such a run, so
@@ -3308,6 +3598,17 @@ async function incremental(dir, plan, cli, copy, observe, states) {
// The other install's summary reads otherwise by construction, so its
// check is no edit, and the next edit is compared with the state before.
if (step === `otherInstall`) return
+ // A hand edit of a file the config's plugin writes leaves the cold result
+ // as it was (the cold run's plugin writes the file again); the check
+ // through the daemon is judged against it all the same.
+ if (
+ step === `inputGate` &&
+ plan.inputRead === `pluginWrite` &&
+ daemon.reported
+ )
+ states.add(
+ `a hand edit of a file the config's plugin writes was checked through the daemon`,
+ )
// An edit that changes the cold result is one a stale cache could miss.
if (step !== `start` && result(previous) !== result(coldRun)) {
states.add(`edit ${step} changed the cold result`)
@@ -3316,6 +3617,30 @@ async function incremental(dir, plan, cli, copy, observe, states) {
states.add(
`an edit to data read through ${plan.fsRead} changed the cold result`,
)
+ // An edit of only the gate input that file b's verdicts read, by each
+ // kind, and one that kept the gate file's size and modification time.
+ if (step === `inputGate`) {
+ states.add(
+ `an edit to the ${plan.inputRead} gate input changed the cold result`,
+ )
+ // Only a gate file keeps its stamp; a listing's edit renames a file.
+ if (
+ plan.keepStamp &&
+ ![
+ `env`,
+ `listing`,
+ `opendir`,
+ `tsconfig`,
+ `configListing`,
+ `stat`,
+ `statAsync`,
+ `statCallback`,
+ ].includes(plan.inputRead)
+ )
+ states.add(
+ `an edit that kept a file's size and modification time changed the cold result`,
+ )
+ }
// The daemon's previous check stored runs of file b's copies that read
// the data and spun (`spinData`), a file that b's unmutated run never
// reads: the runner must store each such run under the inputs it read
@@ -3558,22 +3883,34 @@ async function incremental(dir, plan, cli, copy, observe, states) {
// root, the tests' files live where `tests` links to).
const target = fixturePathOf(
plan,
- plan.midrunTarget === `data` ? `tests/data.json` : `tests/strict.ts`,
+ plan.midrunTarget === `data`
+ ? `tests/data.json`
+ : plan.midrunTarget === `gate`
+ ? gateFiles[plan.inputRead]
+ : `tests/strict.ts`,
)
const after = files[target]
- const value = after.includes(`true`)
- // The marker goes in the running daemon's session directory, where
- // the test finds it beside the runner's harness. With no daemon
- // running (a step before killed it), no edit lands.
- const [daemonPid] = daemonsOf(dir)
- const marker =
- daemonPid && join(dir, `.oracle-gaps-${daemonPid}`, `midrun.txt`)
- if (marker && existsSync(dirname(marker)))
- writeFileSync(marker, `pending:${value}\n`)
+ const value =
+ plan.midrunTarget === `gate`
+ ? after === gateTextFor(plan.inputRead, true)
+ : after.includes(`true`)
const before = {
...files,
- [target]: after.replace(String(value), String(!value)),
+ [target]:
+ plan.midrunTarget === `gate`
+ ? gateTextFor(plan.inputRead, !value)
+ : after.replace(String(value), String(!value)),
}
+ // The marker sits in the package, not in the daemon's session directory:
+ // the check that the edit overlaps restarts the daemon (file b's text
+ // counts its mid-run edits, which the session reads), and a restart
+ // removes the session directory. The name is one for the package, since
+ // the restarted daemon has another process id. It is runner-owned
+ // (inputs.mjs isRunnerFile), so no run takes it as an input. With no
+ // daemon running (a step before killed it), no edit lands.
+ const [daemonPid] = daemonsOf(dir)
+ const marker = daemonPid && join(dir, `.oracle-gaps-midrun.txt`)
+ if (marker) writeFileSync(marker, `pending:${value}\n`)
const during = runCli(dir, before, { ...how, daemon: true })
const landed =
marker &&
@@ -3595,14 +3932,22 @@ async function incremental(dir, plan, cli, copy, observe, states) {
`a run edited the text an earlier edit had made, during a check through the daemon`,
)
}
- const next = runCli(dir, files, { ...how, daemon: true })
+ const next = runCli(dir, files, {
+ ...how,
+ daemon: true,
+ fixtureBase: before,
+ })
// The marker is out of a run's inputs by design; a runner that stored
// a run under it would let the marker's edit, and not the helper's or
// the data's, decide whether a run is stored.
markerStored ||= storedInputs(dir).some((path) =>
- path.endsWith(`/midrun.txt`),
+ path.endsWith(`/.oracle-gaps-midrun.txt`),
)
- midrunChecks = { during, before: runCli(dir, before, how), landed }
+ midrunChecks = {
+ during,
+ before: runCli(dir, before, { ...how, fixtureBase: undefined }),
+ landed,
+ }
// The check the edit overlapped, through the daemon, and the cold run of
// the state before the edit: each call's lines are judged as any call's.
for (const run of [during, midrunChecks.before])
@@ -3681,7 +4026,12 @@ async function incremental(dir, plan, cli, copy, observe, states) {
let warm
if (!mid) {
const [warmRun] = await runClisAtOnce(dir, files, [
- { ...how, daemon: true, outName: `out-warm`, env },
+ {
+ ...how,
+ daemon: true,
+ outName: `out-warm`,
+ env: { ...how.env, ...env },
+ },
])
observe(
`retention:warm`,
@@ -3691,6 +4041,15 @@ async function incremental(dir, plan, cli, copy, observe, states) {
cold: false,
}),
)
+ // The daemon writes its served mark after its reply, and the reply
+ // resolves once the CLI's socket closes, so the CLI may exit before the
+ // mark exists: the mark is awaited, not sampled (diag, 2026-12-03).
+ for (
+ let waited = 0;
+ pidOf(servedMark) === undefined && waited < 10_000;
+ waited += 20
+ )
+ await new Promise((r) => setTimeout(r, 20))
warm = pidOf(servedMark)
// The warm daemon is stopped before the pause is armed: an armed daemon
// holds the stop's own connection unread, so the stop would never end.
@@ -3698,7 +4057,9 @@ async function incremental(dir, plan, cli, copy, observe, states) {
writeFileSync(armMark, ``)
}
let finished = false
- const running = runClisAtOnce(dir, files, [{ ...how, daemon: true, env }])
+ const running = runClisAtOnce(dir, files, [
+ { ...how, daemon: true, env: { ...how.env, ...env } },
+ ])
running.then(() => {
finished = true
})
@@ -3917,6 +4278,7 @@ async function driver(plan, observe) {
cli: plan.cliPath === `spaced` ? copy : here,
...configArgs(plan),
env: {
+ ...inputEnv(plan, initialState(plan)),
...(plan.rejectBatch > 0
? { ORACLE_GAPS_TEST_REJECT_BATCH: String(plan.rejectBatch) }
: {}),
@@ -5663,13 +6025,19 @@ async function driver(plan, observe) {
observe,
states,
)
- for (const state of states) observe(`reach`, state)
+ // Reach is a set (the glossary's `reach`; the framework reads it as one),
+ // so its order carries no law. The insertion order of two states followed
+ // the daemon's timing: the two runs of one history recorded the same
+ // states in another order (CI 46958617422, observation 59, "reused
+ // evidence" and "edit helper changed the cold result"). Record them sorted.
+ for (const state of [...states].sort()) observe(`reach`, state)
} finally {
if (copy) rmSync(copy, { recursive: true, force: true })
rmSync(`${dir}.samples`, { recursive: true, force: true })
rmSync(`${dir}.runner-writes`, { recursive: true, force: true })
rmSync(`${dir}.runner-timers`, { recursive: true, force: true })
removePath(`${dir}.link`)
+ rmSync(outsideOf(dir), { recursive: true, force: true })
written.delete(dir)
dropHook(dir)
try {
@@ -5761,6 +6129,57 @@ function incrementalCheck(observations, expected, plan) {
},
)
}
+ // The restart observable (G34): the pid of a check's daemon changes exactly
+ // where the restart rule owes a restart (model: restartOwed). A surviving
+ // restart and a missing one both fail, and so does a restart at an
+ // unchanged recheck.
+ // A recorded pid that no pair of reported checks judges is a timing value:
+ // the trace must not carry it (the driver records it only where judged).
+ if (
+ value.restart !== undefined &&
+ !restartJudged(
+ value.restart.step,
+ value.restart.previousStep,
+ {
+ reported: value.restart.reported,
+ fellBack: value.restart.fellBack,
+ },
+ value.restart.previousPid === undefined
+ ? undefined
+ : {
+ pid: value.restart.previousPid,
+ reported: value.restart.previousReported,
+ fellBack: value.restart.previousFellBack,
+ },
+ )
+ )
+ return violation(
+ `incremental`,
+ `the check through the daemon at ${step} recorded its daemon's pid, though no pair judges it (a fault, a held or cold-fallback check, or a check that did not report): the pid depends on timing`,
+ `restart iff a tracked input changed`,
+ )
+ if (value.restart !== undefined) {
+ const { restart: r } = value
+ const owed = restartOwed(
+ plan,
+ { env: r.env, cliCode: r.cliCode, inputOpen: r.inputOpen },
+ {
+ env: r.previousEnv,
+ cliCode: r.previousCode,
+ inputOpen: r.previousInputOpen,
+ ran: r.previousRan,
+ },
+ )
+ const restarted = r.pid !== r.previousPid
+ if (restarted !== owed)
+ return violation(
+ `incremental`,
+ owed
+ ? `the check through the daemon at ${step} kept the daemon that served its previous check (pid ${r.pid}, real ${globalThis.__oracleRealPids?.get(r.pid)} from ${globalThis.__oracleRealPids?.get(r.previousPid)}), though a tracked input changed`
+ : `the check through the daemon at ${step} was served by a new daemon (pid ${r.previousPid} to ${r.pid}, real ${globalThis.__oracleRealPids?.get(r.previousPid)} to ${globalThis.__oracleRealPids?.get(r.pid)}), though no tracked input changed`,
+ `restart iff a tracked input changed`,
+ )
+ }
if (value.unchangedComputed > 0)
return violation(
`incremental`,
@@ -5803,7 +6222,7 @@ function incrementalCheck(observations, expected, plan) {
if (daemon.held && daemon.exit !== cold.exit)
return violation(
`incremental`,
- `after ${step}, the daemon held the check and the CLI did not fall back to a cold check: it exited ${daemon.exit}${daemon.exit > 128 ? ` when the driver's backstop stopped it` : ``}, and the cold run exited ${cold.exit}`,
+ `after ${step}, the daemon held the check and the CLI did not fall back to a cold check: it exited ${daemon.exit}${daemon.exit > 128 ? ` when the driver's backstop stopped it` : ``} (${daemon.refusal ?? daemon.stderr ?? `no refusal`}), and the cold run exited ${cold.exit}`,
`cold fallback`,
)
if (daemon.rewritten.length > 0)
@@ -6234,7 +6653,7 @@ function check(plan, observations, expected) {
if (kind !== owed.kind)
return violation(
`cli`,
- `${site(got)}: ${kind}, owed ${owed.kind}`,
+ `${site(got)}: ${kind}, owed ${owed.kind}${got.crash === undefined ? `` : `; the crash threw ${JSON.stringify(got.crash)}`}`,
owed.kind === `unowned` || kind === `unowned`
? `ownership`
: `classification`,
@@ -7249,6 +7668,19 @@ const calibrations = [
},
),
},
+ {
+ // The violation names the error of the crash it reports (its `crash`).
+ name: `a kill is reported as a crash, and names the error`,
+ law: `classification`,
+ difference: `the crash threw "calibration error"`,
+ corrupt: firstWhere(
+ (m) => !m.probe && m.outcome === `killed`,
+ (m) => {
+ m.outcome = `crashed`
+ m.crash = `calibration error`
+ },
+ ),
+ },
{
name: `an owned mutant is reported as unowned`,
law: `ownership`,
@@ -7544,6 +7976,53 @@ calibrations.push(
// holds only when the edit landed (fourth review of #55, F-C1): with no
// edit, that check reads one state, so a mutant of file b that it reports
// as neither cold run does, killed for survived, is a violation.
+// The restart observable (G34, law 9's restart rule): a check that a changed
+// plugin input owes a new daemon, and that kept its daemon, is named; and a
+// check at an unchanged recheck that a new daemon served is named.
+calibrations.push({
+ name: `the check that a changed plugin input reached kept the daemon of the check before it`,
+ law: `restart iff a tracked input changed`,
+ history: {
+ constructed: `an edit to a file the config's plugin reads when the config resolves`,
+ },
+ corrupt: (trace) => {
+ const index = trace.findIndex(
+ (o) =>
+ o.checkpoint === `incremental` &&
+ o.value.restart?.previousPid !== undefined &&
+ o.value.restart.reported &&
+ o.value.restart.previousReported &&
+ o.value.restart.pid !== o.value.restart.previousPid,
+ )
+ if (index < 0) return undefined
+ const value = structuredClone(trace[index].value)
+ value.restart.pid = value.restart.previousPid
+ return trace.map((o, i) => (i === index ? { ...o, value } : o))
+ },
+})
+
+calibrations.push({
+ name: `the unchanged recheck that a new daemon served is named`,
+ law: `restart iff a tracked input changed`,
+ history: {
+ constructed: `an unchanged check through the daemon while a config's plugin writes, stats and removes a scratch file`,
+ },
+ corrupt: (trace) => {
+ const index = trace.findIndex(
+ (o) =>
+ o.checkpoint === `incremental` &&
+ o.value.step === `recheck` &&
+ o.value.restart?.previousPid !== undefined &&
+ o.value.restart.reported &&
+ o.value.restart.previousReported,
+ )
+ if (index < 0) return undefined
+ const value = structuredClone(trace[index].value)
+ value.restart.pid = value.restart.previousPid + 1000
+ return trace.map((o, i) => (i === index ? { ...o, value } : o))
+ },
+})
+
calibrations.push({
name: `the check a mid-run edit did not reach reports a mutant of the editing file as neither cold run did`,
law: `incremental equals cold`,
@@ -8212,6 +8691,36 @@ const incrementalStates = [
`the daemon ran from a path with a space and #`,
`of two checks held in the daemon at once, one computed and the other reused`,
]
+// The kinds of gate input that file b's verdicts may read (`inputRead`).
+const inputKinds = [
+ `inside`,
+ `outside`,
+ `module`,
+ `env`,
+ `pluginConfig`,
+ `pluginTransform`,
+ `listing`,
+ `opendir`,
+ `stream`,
+ `tsconfig`,
+ `configListing`,
+ `stat`,
+ `statAsync`,
+ `statCallback`,
+ `append`,
+ `flagAppend`,
+ `required`,
+ `childRead`,
+ `threadRead`,
+ `requireMain`,
+ `requireType`,
+ `wxExisting`,
+ `rplus`,
+ `threadNested`,
+ `childLost`,
+ `linkDotDot`,
+ `threadStrict`,
+]
// Law 9's states that a constructed history of their own reaches, not the
// edit sequence: the mid-run edit, and an edit to data a test reads through
// fs, by each read.
@@ -8225,11 +8734,22 @@ const ownedIncrementalStates = [
`an unchanged check through the daemon computed nothing while a test read a source through fs`,
`a capture row read while the worker wrote it`,
`a run edited the data it had read, during a check through the daemon`,
+ `a run edited the gate it had read, during a check through the daemon`,
`edit fsData changed the cold result`,
`an edit to data read through sync changed the cold result`,
`an edit to data read through promise changed the cold result`,
`an edit to data read through callback changed the cold result`,
`an edit to data read through statDir changed the cold result`,
+ // Every read is a daemon input (maintainer decision, 2026-11-16): an edit
+ // of only the gate input that file b's verdicts read, by each kind, and an
+ // edit that kept the gate file's size and modification time (D10).
+ ...inputKinds.map(
+ (kind) => `an edit to the ${kind} gate input changed the cold result`,
+ ),
+ `a hand edit of a file the config's plugin writes was checked through the daemon`,
+ `edit inputGate changed the cold result`,
+ `an edit that kept a file's size and modification time changed the cold result`,
+ `a daemon restart on a changed plugin input`,
]
// The static states (probe structure and ownership through the reference
// tree) are gap-report-static-oracle's: it reaches each in every campaign,
@@ -8582,8 +9102,12 @@ const required = [
`an edit to data that only a copy spun alone read changed the cold result`,
`a slow warm-up was served by the daemon`,
`a check through the daemon worked past its CLI's bound`,
+ `a check through the daemon with a frozen plugin object named it and stored no unit`,
`a slow daemon start was served by the daemon`,
`a check abandoned while a context warmed in place of a cut one wrote nothing more`,
+ `an unchanged check through the daemon computed nothing while a test read what its child process wrote`,
+ `an unchanged check through the daemon computed nothing while a test made the files it reads`,
+ `an unchanged check through the daemon computed nothing while a test wrote to the console`,
]
// The faults the CLI analyzes anyway: a package's TypeScript is no input.
const analyzedFaults = [`noTypescript`, `apiLessTypescript`]
@@ -8759,8 +9283,15 @@ const separate = [
`an edit to data that only a copy spun alone read changed the cold result`,
`a slow warm-up was served by the daemon`,
`a check through the daemon worked past its CLI's bound`,
+ `a check through the daemon with a frozen plugin object named it and stored no unit`,
`a slow daemon start was served by the daemon`,
`a check abandoned while a context warmed in place of a cut one wrote nothing more`,
+ // Each has its own constructed history (#179; own writes of the test's
+ // process tree).
+ `an unchanged check through the daemon computed nothing while a test read what its child process wrote`,
+ `an unchanged check through the daemon computed nothing while a test made the files it reads`,
+ // Its own constructed history (a test that writes to the console).
+ `an unchanged check through the daemon computed nothing while a test wrote to the console`,
]
// A stop by SIGTERM exists only where Node can deliver it: on win32 kill is
// TerminateProcess, so there the stop law is judged by SIGINT (the test stop
@@ -8914,6 +9445,19 @@ const withDeclaration = (constructed) =>
// A literal construction that does not name the pair witness's field
// (`pair`, drawn last) runs without it; one that names it keeps it.
pair: false,
+ // The input fields this branch draws last (inputRead to frozenPlugin) at
+ // their neutral values: a construction that does not name one of them
+ // runs without it, and the history it returns is then taken back as
+ // drawn. A literal that names one keeps its value.
+ inputRead: `none`,
+ keepStamp: false,
+ inputSteps: NO_INPUT_STEPS,
+ childWrite: false,
+ childEnvironment: `node`,
+ midrunGate: false,
+ scratchPlugin: false,
+ frozenPlugin: false,
+ ownOutput: `none`,
...item.build({
...generated,
// The end-to-end dimensions a generated base may draw: a construction
@@ -8930,6 +9474,11 @@ const withDeclaration = (constructed) =>
failingLawCalls: `none`,
failingLawHook: `none`,
failingLawSpins: false,
+ // A frozen plugin stores no unit (CR-2), so a construction that does
+ // not name it cannot reach a state of reuse: it runs with a plugin
+ // that can be wrapped. The CR-2 history names it itself.
+ frozenPlugin: false,
+ ownOutput: `none`,
declaration: index % 2 === 0 ? `wrapper` : `oracleProperty`,
ownerless: false,
owners: [`a`, ...generated.owners.slice(1)],
@@ -9000,6 +9549,74 @@ const witnessEditSequence = (witness) => (generated) => ({
steps: witnessSteps,
})
+// `reuses` is false for a kind whose run the copy must not store (a child whose
+// log lost lines, CR-19): its check after the edit is no unchanged reuse, so the
+// history stops after the edit, and enters no unchanged-reuse state.
+const gateKindHistory = ([name, inputRead, keepStamp, reuses = true]) => ({
+ name,
+ enters: [
+ ...(inputRead === `pluginWrite`
+ ? [
+ `a hand edit of a file the config's plugin writes was checked through the daemon`,
+ ]
+ : [
+ `edit inputGate changed the cold result`,
+ `an edit to the ${inputRead} gate input changed the cold result`,
+ ]),
+ ...(reuses
+ ? [`an unchanged check through the daemon computed nothing`]
+ : []),
+ ...(keepStamp
+ ? [
+ `an edit that kept a file's size and modification time changed the cold result`,
+ ]
+ : []),
+ // A plugin input that the session holds restarts the daemon: the check
+ // after its edit is served by a new daemon (G34, the restart observable).
+ ...(PLUGIN_INPUT_READS.has(inputRead)
+ ? [`a daemon restart on a changed plugin input`]
+ : []),
+ ],
+ build: (generated) => ({
+ ...generated,
+ functions: [[{ kind: `push`, quote: `'` }]],
+ containers: [],
+ overloads: [],
+ owners: [`b`],
+ library: [],
+ libraryOwners: [],
+ runes: [],
+ derived: null,
+ dotGen: false,
+ dataOwners: [],
+ exportOwners: [],
+ importer: `none`,
+ wholeFile: `none`,
+ template: false,
+ tests: [{ ...judging(`b`, `fixed seed`, 1), fn: 0 }],
+ witness: false,
+ authored: null,
+ secondAuthored: false,
+ fault: `none`,
+ stability: `none`,
+ ordinary: false,
+ native: `none`,
+ boot: false,
+ cliPath: `plain`,
+ concurrentStart: false,
+ lazyGate: false,
+ fsRead: `none`,
+ prePlugin: false,
+ // A config the plugin can sit in, which Vitest discovers.
+ configPlace: `discovered`,
+ inputRead,
+ keepStamp,
+ laterSteps: NO_LATER_STEPS,
+ inputSteps: NO_INPUT_STEPS,
+ steps: reuses ? [`inputGate`, `recheck`] : [`inputGate`],
+ }),
+})
+
// A constructed history whose only owned function is a kill, owned by file a
// alone, with the tests given (the rest of the generated base is left as the
// grammar draws it, as the histories above do).
@@ -9264,6 +9881,9 @@ oracleProperty({
configRequire: false,
contexts: 4,
steps: null,
+ scratchPlugin: false,
+ frozenPlugin: false,
+ ownOutput: `none`,
dataOwners: ['b', 'a'],
exportOwners: ['b', 'b', 'b', 'b', 'a', 'none'],
importer: 'a',
@@ -9306,6 +9926,15 @@ oracleProperty({
heavy: 0,
// The pair witness's field (`pair`, drawn last), at its neutral value.
pair: false,
+ inputRead: `none`,
+ keepStamp: false,
+ inputSteps: NO_INPUT_STEPS,
+ childWrite: false,
+ childEnvironment: `node`,
+ midrunGate: false,
+ scratchPlugin: false,
+ frozenPlugin: false,
+ ownOutput: `none`,
failingLaw: `none`,
failingLawAt: `end`,
failingLawCalls: `none`,
@@ -9542,6 +10171,15 @@ oracleProperty({
failingLawSpins: false,
diffBase: `none`,
authoredSpan: false,
+ inputRead: `none`,
+ keepStamp: false,
+ inputSteps: NO_INPUT_STEPS,
+ childWrite: false,
+ childEnvironment: `node`,
+ midrunGate: false,
+ scratchPlugin: false,
+ frozenPlugin: false,
+ ownOutput: `none`,
},
},
{
@@ -9722,6 +10360,15 @@ oracleProperty({
failingLawSpins: false,
diffBase: `none`,
authoredSpan: false,
+ inputRead: `none`,
+ keepStamp: false,
+ inputSteps: NO_INPUT_STEPS,
+ childWrite: false,
+ childEnvironment: `node`,
+ midrunGate: false,
+ scratchPlugin: false,
+ frozenPlugin: false,
+ ownOutput: `none`,
},
},
{
@@ -9934,6 +10581,15 @@ oracleProperty({
failingLawSpins: false,
diffBase: `none`,
authoredSpan: false,
+ inputRead: `none`,
+ keepStamp: false,
+ inputSteps: NO_INPUT_STEPS,
+ childWrite: false,
+ childEnvironment: `node`,
+ midrunGate: false,
+ scratchPlugin: false,
+ frozenPlugin: false,
+ ownOutput: `none`,
},
},
{
@@ -10177,6 +10833,12 @@ oracleProperty({
spinData: false,
wholeFile: `none`,
fault: `none`,
+ // No gate input: its states are the daemon-input histories', and the
+ // witness module's own runs are the costliest of the campaign (the
+ // Windows job of this one history; review of #133, F6).
+ inputRead: `none`,
+ keepStamp: false,
+ inputSteps: NO_INPUT_STEPS,
authored: { stmt: 0, kind: `apply` },
stability: `insertGuard`,
steps: null,
@@ -11019,6 +11681,7 @@ oracleProperty({
steps: [`midrun`],
midrunBy: `b`,
midrunTarget: `helper`,
+ midrunGate: false,
fsRead: `none`,
lazyGate: false,
}),
@@ -11074,6 +11737,7 @@ oracleProperty({
steps: [`midrun`],
midrunBy: `b`,
midrunTarget: `data`,
+ midrunGate: false,
fsRead: `sync`,
lazyGate: false,
}),
@@ -15782,6 +16446,511 @@ oracleProperty({
loadPlugin: false,
}),
},
+ // Every read is a daemon input (maintainer decision, 2026-11-16, "All
+ // of them"). File b's verdict also waits on one gate input, and the
+ // one edit flips only that input from `open` to `shut`: the cold run
+ // then reports b's mutant as a survivor, and the daemon must not
+ // reuse a kill that read the open gate (law 9). A second check with
+ // nothing changed then computes nothing (the `unchanged reuse` law), so
+ // a daemon that never reuses, which equals a cold run trivially, fails
+ // too. One history per kind of input, appended last, so the histories
+ // before them keep their seeds' samples.
+ ...[
+ // A file in the package that the test reads, written back with its
+ // size and modification time, as `cp -p` leaves it: the daemon must
+ // see the new text all the same (D10).
+ [
+ `an edit to a file in the package that keeps its size and modification time`,
+ `inside`,
+ true,
+ ],
+ [
+ `an edit to a file outside the package that a test reads`,
+ `outside`,
+ false,
+ ],
+ [
+ `an edit to a file under node_modules that a test reads`,
+ `module`,
+ false,
+ ],
+ [`an edit to an environment variable that a test reads`, `env`, false],
+ [
+ `an edit to a file the config's plugin reads when the config resolves`,
+ `pluginConfig`,
+ false,
+ ],
+ // Written back with its size and modification time, too.
+ [
+ `an edit to a file the config's plugin reads when it transforms a test`,
+ `pluginTransform`,
+ true,
+ ],
+ // A directory's listing, by readdirSync and by opendirSync: the edit
+ // renames the one file in it.
+ [`an edit to a directory listing that a test reads`, `listing`, false],
+ [
+ `an edit to a directory a test reads through opendir`,
+ `opendir`,
+ false,
+ ],
+ // The package's gate file read through a stream, written back with
+ // its size and modification time.
+ [`an edit to a file a test reads through a stream`, `stream`, true],
+ // An input of Vite's own esbuild plugin (review of #133, F1).
+ [
+ `an edit to the tsconfig that Vite's own plugin reads`,
+ `tsconfig`,
+ false,
+ ],
+ // A listing that the config makes when it loads (review of #133, F2).
+ [
+ `an edit to a directory the config lists when it loads`,
+ `configListing`,
+ false,
+ ],
+ // A hand edit of a file that the config's plugin writes (review of
+ // #133, F3): the cold run's plugin writes it again, so the cold
+ // result does not change.
+ [
+ `a hand edit of a file the config's plugin writes`,
+ `pluginWrite`,
+ false,
+ ],
+ ].map(gateKindHistory),
+ {
+ // A file that the test's own child process tree wrote earlier in the
+ // check is no input of the test (maintainer decisions "Own writes
+ // aren't inputs", 2026-11-17, and "Optimize #133 before merging",
+ // 2026-11-19): file b reads, as it loads, a file that a node
+ // grandchild of its test wrote in a new temporary directory, so the
+ // unchanged recheck through the daemon must reuse b's runs although
+ // the file's path differs in every run (`unchanged reuse`).
+ name: `a test that reads a file its child process wrote, rechecked through the daemon`,
+ enters: [
+ `an unchanged check through the daemon computed nothing`,
+ `an unchanged check through the daemon computed nothing while a test read what its child process wrote`,
+ ],
+ build: (generated) => ({
+ ...generated,
+ functions: [[{ kind: `push`, quote: `'` }]],
+ containers: [],
+ overloads: [],
+ owners: [`b`],
+ library: [],
+ libraryOwners: [],
+ runes: [],
+ derived: null,
+ dotGen: false,
+ dataOwners: [],
+ exportOwners: [],
+ importer: `none`,
+ wholeFile: `none`,
+ template: false,
+ tests: [{ ...judging(`b`, `fixed seed`, 1), fn: 0 }],
+ witness: false,
+ authored: null,
+ secondAuthored: false,
+ fault: `none`,
+ stability: `none`,
+ ordinary: false,
+ native: `none`,
+ boot: false,
+ cliPath: `plain`,
+ concurrentStart: false,
+ lazyGate: false,
+ fsRead: `none`,
+ prePlugin: false,
+ inputRead: `none`,
+ keepStamp: false,
+ laterSteps: NO_LATER_STEPS,
+ inputSteps: NO_INPUT_STEPS,
+ steps: [`recheck`],
+ childWrite: true,
+ // In an environment that transforms file b for the client, as a
+ // jsdom environment does (`childEnvironment`).
+ childEnvironment: `client`,
+ midrunGate: false,
+ }),
+ },
+ ...[
+ [
+ `an edit to a file the test stats for its size, by statSync`,
+ `stat`,
+ false,
+ ],
+ [
+ `an edit to a file the test stats for its size, by fs/promises stat`,
+ `statAsync`,
+ false,
+ ],
+ [
+ `an edit to a file the test stats for its size, by the callback stat`,
+ `statCallback`,
+ false,
+ ],
+ [`an edit to a file a test appends to, then reads`, `append`, false],
+ [
+ `an edit to a file a test appends to with flag a, then reads`,
+ `flagAppend`,
+ false,
+ ],
+ [`an edit to a file a test requires as JSON`, `required`, false],
+ [
+ `an edit to a file that a test child process reads`,
+ `childRead`,
+ false,
+ ],
+ ].map(gateKindHistory),
+ {
+ // File a's test writes to the process's streams (`consoleOutput`), so
+ // its copy appends to the run's own test-output.log, which the run
+ // creates. That append is no input (capture-setup.mjs, isRunnerOwnAppend),
+ // so the unchanged recheck through the daemon reuses both files' runs.
+ // With the exemption removed, the log grows while the run settles,
+ // the runs are never stored, and the recheck computes them again.
+ name: `a test that writes to the console, rechecked through the daemon`,
+ enters: [
+ `an unchanged check through the daemon computed nothing`,
+ `an unchanged check through the daemon computed nothing while a test wrote to the console`,
+ ],
+ build: (generated) => ({
+ ...generated,
+ functions: [[{ kind: `push`, quote: `'` }]],
+ containers: [],
+ overloads: [],
+ owners: [`a`, `b`],
+ library: [],
+ libraryOwners: [],
+ runes: [],
+ derived: null,
+ dotGen: false,
+ dataOwners: [],
+ exportOwners: [],
+ importer: `none`,
+ wholeFile: `none`,
+ template: false,
+ tests: [
+ { ...judging(`a`, `fixed seed`, 1), fn: 0 },
+ { ...judging(`b`, `fixed seed`, 1), fn: 0 },
+ ],
+ witness: false,
+ authored: null,
+ secondAuthored: false,
+ fault: `none`,
+ stability: `none`,
+ ordinary: false,
+ native: `none`,
+ boot: false,
+ cliPath: `plain`,
+ concurrentStart: false,
+ lazyGate: false,
+ fsRead: `none`,
+ prePlugin: false,
+ inputRead: `none`,
+ keepStamp: false,
+ laterSteps: NO_LATER_STEPS,
+ inputSteps: NO_INPUT_STEPS,
+ steps: [`recheck`],
+ childWrite: false,
+ childEnvironment: `node`,
+ midrunGate: false,
+ consoleOutput: true,
+ }),
+ },
+ // File b reads the gate in a worker thread (worker_threads, #143): the
+ // harness gives each worker its preload (capture-setup.mjs), so the
+ // worker's read is an input and the edit changes the cold result.
+ gateKindHistory([
+ `an edit to a file a test reads inside a worker thread`,
+ `threadRead`,
+ false,
+ ]),
+ // File b requires a package: its main picks the file it loads, and the
+ // edit changes only that package.json. Node reads the main itself, so
+ // only the resolver wrapper (capture-setup.mjs) records the edit.
+ gateKindHistory([
+ `an edit to the package.json main that a test requires`,
+ `requireMain`,
+ false,
+ ]),
+ // The same package's type: a CommonJS file loads as a module after the
+ // edit, and the test's require then fails to see its export.
+ gateKindHistory([
+ `an edit to the package.json type that a test requires`,
+ `requireType`,
+ false,
+ ]),
+ {
+ // File b's test edits the gate that its own verdict reads, during a
+ // check through the daemon (`midrunGate`, I12 for the gate kinds). A run
+ // that read the old text and settled after the edit is not stored, so
+ // the check that follows equals a cold run of the state after the edit.
+ name: `an edit to a gate that a test reads, during a check through the daemon`,
+ enters: [
+ `an edit landed during a check through the daemon`,
+ `edit midrun changed the cold result`,
+ `a run edited the gate it had read, during a check through the daemon`,
+ ],
+ build: (generated) => ({
+ ...generated,
+ functions: [[{ kind: `push`, quote: `'` }]],
+ containers: [],
+ overloads: [],
+ owners: [`a`, `b`],
+ library: [],
+ libraryOwners: [],
+ runes: [],
+ derived: null,
+ dotGen: false,
+ dataOwners: [],
+ exportOwners: [],
+ importer: `none`,
+ wholeFile: `none`,
+ template: false,
+ tests: [
+ { ...judging(`a`, `fixed seed`, 1), fn: 0 },
+ { ...judging(`b`, `fixed seed`, 1), fn: 0 },
+ ],
+ witness: false,
+ authored: null,
+ secondAuthored: false,
+ fault: `none`,
+ stability: `none`,
+ ordinary: false,
+ native: `none`,
+ boot: false,
+ cliPath: `plain`,
+ concurrentStart: false,
+ lazyGate: false,
+ fsRead: `none`,
+ prePlugin: false,
+ inputRead: `stat`,
+ keepStamp: false,
+ laterSteps: NO_LATER_STEPS,
+ inputSteps: NO_INPUT_STEPS,
+ steps: [`midrun`],
+ midrunBy: `b`,
+ midrunGate: true,
+ contexts: 1,
+ budget: `two`,
+ // The driver finds the daemon's session directory beside the package, so
+ // the package is not a sibling of the check's directory here.
+ siblingDir: false,
+ childWrite: false,
+ childEnvironment: `node`,
+ }),
+ },
+ // Appended after the last recorded constructed history (the order
+ // canary): the four gate kinds of the CodeRabbit repairs (CR-12, CR-19,
+ // CR-21, CR-25).
+ // A worker that a worker starts reads the file: the nested worker has
+ // the preload too (CR-25).
+ gateKindHistory([
+ `an edit to a file a test reads inside a worker started by a worker`,
+ `threadNested`,
+ false,
+ ]),
+ // A failed exclusive create of the file, and then its read: the failed
+ // write makes nothing the tree's own (CR-12).
+ gateKindHistory([
+ `an edit to a file a test tries to create exclusively, then reads`,
+ `wxExisting`,
+ false,
+ ]),
+ // A write with flag r+ and no bytes, then the read: the write keeps the
+ // file's text, so the text is an input (CR-21).
+ gateKindHistory([
+ `an edit to a file a test opens for update, then reads`,
+ `rplus`,
+ false,
+ ]),
+ // A child process whose write log cannot be opened: it keeps its
+ // result, and the verdict follows the file it read (CR-19).
+ gateKindHistory([
+ `an edit to a file that a child process reads when its own log fails`,
+ `childLost`,
+ false,
+ false,
+ ]),
+ // A path through a symbolic link and `..` (CR-22).
+ gateKindHistory([
+ `an edit to a file a test reads through a link and dot-dot`,
+ `linkDotDot`,
+ false,
+ ]),
+ // A worker whose 'use strict' directive must stay first (CR-24).
+ gateKindHistory([
+ `an edit to a file a test reads in a worker with strict mode`,
+ `threadStrict`,
+ false,
+ ]),
+ {
+ // A config plugin that writes a scratch file beside the config, tests
+ // whether it exists, and removes it at each resolve: the stat of the
+ // session's own write is no input, so the unchanged check reuses every
+ // run and does not restart the daemon (check.mjs, ownWrite; CR-3).
+ name: `an unchanged check through the daemon while a config's plugin writes, stats and removes a scratch file`,
+ enters: [`an unchanged check through the daemon computed nothing`],
+ build: (generated) => ({
+ ...generated,
+ functions: [
+ [{ kind: `push`, quote: `'` }],
+ [{ kind: `push`, quote: `'` }],
+ ],
+ containers: [],
+ overloads: [],
+ owners: [`a`, `b`],
+ library: [],
+ libraryOwners: [],
+ runes: [],
+ derived: null,
+ dotGen: false,
+ dataOwners: [],
+ exportOwners: [],
+ importer: `none`,
+ wholeFile: `none`,
+ template: false,
+ tests: [
+ { ...judging(`a`, `fixed seed`, 1), fn: 0 },
+ { ...judging(`b`, `fixed seed`, 1), fn: 1 },
+ ],
+ witness: false,
+ authored: null,
+ secondAuthored: false,
+ fault: `none`,
+ stability: `none`,
+ ordinary: false,
+ native: `none`,
+ boot: false,
+ budget: `two`,
+ cliPath: `plain`,
+ concurrentStart: false,
+ contexts: 1,
+ laterSteps: NO_LATER_STEPS,
+ steps: [`recheck`],
+ scratchPlugin: true,
+ configPlace: `discovered`,
+ configFile: `vite.config.mjs`,
+ config: `object`,
+ }),
+ },
+ {
+ // A config whose plugin object is frozen: its hooks cannot take the runner's
+ // wrapper, so the check names the plugin and stores no unit of it, and
+ // computes each unit as a cold run does (CR-2).
+ name: `a check through the daemon of a config whose plugin object is frozen`,
+ enters: [
+ `a check through the daemon with a frozen plugin object named it and stored no unit`,
+ ],
+ build: (generated) => ({
+ ...generated,
+ functions: [
+ [{ kind: `push`, quote: `'` }],
+ [{ kind: `push`, quote: `'` }],
+ ],
+ containers: [],
+ overloads: [],
+ owners: [`a`, `b`],
+ library: [],
+ libraryOwners: [],
+ runes: [],
+ derived: null,
+ dotGen: false,
+ dataOwners: [],
+ exportOwners: [],
+ importer: `none`,
+ wholeFile: `none`,
+ template: false,
+ tests: [
+ { ...judging(`a`, `fixed seed`, 1), fn: 0 },
+ { ...judging(`b`, `fixed seed`, 1), fn: 1 },
+ ],
+ witness: false,
+ authored: null,
+ secondAuthored: false,
+ fault: `none`,
+ stability: `none`,
+ ordinary: false,
+ native: `none`,
+ boot: false,
+ budget: `two`,
+ cliPath: `plain`,
+ concurrentStart: false,
+ contexts: 1,
+ laterSteps: NO_LATER_STEPS,
+ steps: [`recheck`],
+ frozenPlugin: true,
+ ownOutput: `none`,
+ configPlace: `discovered`,
+ configFile: `vite.config.mjs`,
+ config: `object`,
+ }),
+ },
+ ...[
+ // The three shapes of a test's own output (ownOutput, the model): the
+ // test reads a file its child process makes, a copy its child reads, or
+ // a directory it writes into. Each unchanged recheck must reuse every run
+ // (law 9, own outputs are not inputs; check.mjs settleIn).
+ [
+ `created`,
+ `a file its child process makes after the test checks for it`,
+ ],
+ [`copied`, `a copy its child process reads, in a directory it removes`],
+ [`listed`, `a directory it lists before it writes a file into it`],
+ [
+ `childStat`,
+ `a directory its child process makes, checks for, and removes`,
+ ],
+ ].map(([ownOutput, shape]) => ({
+ name: `an unchanged check through the daemon while a test made the files it reads: ${shape}`,
+ enters: [
+ `an unchanged check through the daemon computed nothing while a test made the files it reads`,
+ ],
+ build: (generated) => ({
+ ...generated,
+ functions: [
+ [{ kind: `push`, quote: `'` }],
+ [{ kind: `push`, quote: `'` }],
+ ],
+ containers: [],
+ overloads: [],
+ owners: [`a`, `b`],
+ library: [],
+ libraryOwners: [],
+ runes: [],
+ derived: null,
+ dotGen: false,
+ dataOwners: [],
+ exportOwners: [],
+ importer: `none`,
+ wholeFile: `none`,
+ template: false,
+ tests: [
+ { ...judging(`a`, `fixed seed`, 1), fn: 0 },
+ { ...judging(`b`, `fixed seed`, 1), fn: 1 },
+ ],
+ witness: false,
+ authored: null,
+ secondAuthored: false,
+ fault: `none`,
+ stability: `none`,
+ ordinary: false,
+ native: `none`,
+ boot: false,
+ budget: `two`,
+ cliPath: `plain`,
+ concurrentStart: false,
+ contexts: 1,
+ laterSteps: NO_LATER_STEPS,
+ steps: [`recheck`],
+ childWrite: false,
+ ownOutput,
+ configPlace: `discovered`,
+ configFile: `vite.config.mjs`,
+ config: `object`,
+ }),
+ })),
]),
},
resolve: resolveHistory,
diff --git a/packages/oracles/oracle-gaps/gap-report-static-oracle.property.test.mjs b/packages/oracles/oracle-gaps/gap-report-static-oracle.property.test.mjs
index a2f8bfed..d0458f99 100644
--- a/packages/oracles/oracle-gaps/gap-report-static-oracle.property.test.mjs
+++ b/packages/oracles/oracle-gaps/gap-report-static-oracle.property.test.mjs
@@ -133,6 +133,7 @@ import {
refusalBreach,
resolveHistory,
removePath,
+ outsideOf,
sourceArgument,
caseless,
writeFixture,
@@ -255,6 +256,7 @@ function defaultOutputsOf(dir, sources) {
same: [outs[0] === outs[1], outs[0] === outs[2], outs[1] === outs[2]],
}
} finally {
+ rmSync(outsideOf(other), { recursive: true, force: true })
rmSync(other, { recursive: true, force: true })
}
}
@@ -1024,6 +1026,7 @@ async function driver(plan, observe) {
} finally {
written.delete(dir)
removePath(`${dir}.link`)
+ rmSync(outsideOf(dir), { recursive: true, force: true })
rmSync(scratch, { recursive: true, force: true })
}
}
@@ -1293,29 +1296,41 @@ const corruptArguments = (change) => (trace) => {
const value = { ...trace[index].value, ...change(trace[index].value) }
return trace.map((o, i) => (i === index ? { ...o, value } : o))
}
+// Each calibration names the history it corrupts (the framework's history
+// binding), so it runs that one history instead of searching the campaign's
+// histories for one its corruption applies to: a refusal's corruption needs a
+// refused run, which the search found only after a dozen other histories,
+// and the draws that #133's appended fields shift made that search longer
+// (review of #133, F6). The bound histories reach what each corruption needs:
+// a refusal, Svelte runes, owned mutants, a stability rerun, a derived class.
const calibrations = [
{
name: `a refusal prints a stack trace, as a crash does`,
+ history: { constructed: `bad arguments: noPackage` },
law: `report-shaped ending`,
corrupt: corruptArguments(() => ({ stackFrames: true })),
},
{
name: `a refusal exits 1, as a crash does`,
+ history: { constructed: `bad arguments: noPackage` },
law: `report-shaped ending`,
corrupt: corruptArguments(() => ({ exit: 1 })),
},
{
name: `a refusal gives no fix`,
+ history: { constructed: `bad arguments: noPackage` },
law: `report-shaped ending`,
corrupt: corruptArguments(() => ({ fix: undefined, cause: undefined })),
},
{
name: `a refusal ends without its done line`,
+ history: { constructed: `bad arguments: noPackage` },
law: `report-shaped ending`,
corrupt: corruptArguments(() => ({ done: undefined })),
},
{
name: `a refusal's fix offers a way around it`,
+ history: { constructed: `bad arguments: noPackage` },
law: `report-shaped ending`,
corrupt: corruptArguments((v) => ({
fix: `${v.fix} Or mark the mutant equivalent.`,
@@ -1323,11 +1338,13 @@ const calibrations = [
},
{
name: `a refusal names another cause`,
+ history: { constructed: `bad arguments: noPackage` },
law: `report-shaped ending`,
corrupt: corruptArguments(() => ({ cause: `something went wrong` })),
},
{
name: `a rune is moved from its place`,
+ history: { constructed: `every static state` },
law: `rune placement`,
corrupt: corrupt(`static`, (v) => {
if (!v.runes?.includes(`= $`)) return false
@@ -1336,11 +1353,13 @@ const calibrations = [
},
{
name: `a mutant is dropped`,
+ history: { constructed: `every static state` },
law: `enumeration`,
corrupt: corrupt(`static`, (v) => void v.mutants.shift()),
},
{
name: `production code is marked as probe code`,
+ history: { constructed: `every static state` },
law: `probe-only code`,
corrupt: corrupt(`static`, (v) => {
const m = v.mutants.find((x) => !x.probe)
@@ -1350,6 +1369,7 @@ const calibrations = [
},
{
name: `an owned mutant is reported unowned`,
+ history: { constructed: `every static state` },
law: `ownership`,
corrupt: corrupt(`static`, (v) => {
const m = v.mutants.find((x) => !x.probe && x.owned)
@@ -1359,6 +1379,7 @@ const calibrations = [
},
{
name: `a derived class's super call is made conditional`,
+ history: { constructed: `a plain-parameter derived class` },
law: `super unconditional`,
corrupt: corrupt(`derived`, (v) => {
const run = v.mutants[0]?.runs[0]
@@ -1370,6 +1391,7 @@ const calibrations = [
},
{
name: `the instrumented derived class differs with no mutant active`,
+ history: { constructed: `a plain-parameter derived class` },
law: `no-mutant behavior`,
corrupt: corrupt(`derived`, (v) => {
v.instrumented[0] = { error: `Must call super constructor` }
@@ -1377,6 +1399,7 @@ const calibrations = [
},
{
name: `a key drops its statement`,
+ history: { constructed: `every static state` },
law: `keys`,
corrupt: corrupt(`static`, (v) => {
v.mutants[0].key = v.mutants[0].key.slice(
@@ -1387,6 +1410,7 @@ const calibrations = [
},
{
name: `an edit moves a key`,
+ history: { constructed: `every static state` },
law: `key stability`,
corrupt: (trace) => {
const before = trace.find((o) => o.checkpoint === `static`)?.value
diff --git a/packages/oracles/oracle-gaps/history-fingerprint.json b/packages/oracles/oracle-gaps/history-fingerprint.json
index bae33106..d60481c0 100644
--- a/packages/oracles/oracle-gaps/history-fingerprint.json
+++ b/packages/oracles/oracle-gaps/history-fingerprint.json
@@ -93,6 +93,15 @@
["heavy", "3024c4a7c552e283"],
["pair", "8580a5ff7bdc698d"],
["failingLawHangs", "ed6866229ecc4969"],
+ ["inputRead", "b6322811a618059f"],
+ ["keepStamp", "15bcc8db377de55b"],
+ ["inputSteps", "4ac7b86b4893a9f1"],
+ ["childWrite", "870df294c727d368"],
+ ["childEnvironment", "2f1588837d534eff"],
+ ["midrunGate", "713ce34a4c29b9ea"],
+ ["scratchPlugin", "8ef451bcd3642b7a"],
+ ["frozenPlugin", "3c89007373c202b5"],
+ ["ownOutput", "7fec7ca2c6124a4a"],
["tests.pendingIo", "02f66613e9490d15"]
],
"histories": [
@@ -189,6 +198,15 @@
["heavy", "3024c4a7c552e283"],
["pair", "8580a5ff7bdc698d"],
["failingLawHangs", "ed6866229ecc4969"],
+ ["inputRead", "b6322811a618059f"],
+ ["keepStamp", "15bcc8db377de55b"],
+ ["inputSteps", "4ac7b86b4893a9f1"],
+ ["childWrite", "870df294c727d368"],
+ ["childEnvironment", "2f1588837d534eff"],
+ ["midrunGate", "713ce34a4c29b9ea"],
+ ["scratchPlugin", "8ef451bcd3642b7a"],
+ ["frozenPlugin", "3c89007373c202b5"],
+ ["ownOutput", "7fec7ca2c6124a4a"],
["tests.pendingIo", "02f66613e9490d15"]
]
}
diff --git a/packages/oracles/oracle-gaps/inputs.mjs b/packages/oracles/oracle-gaps/inputs.mjs
new file mode 100644
index 00000000..f35e3aff
--- /dev/null
+++ b/packages/oracles/oracle-gaps/inputs.mjs
@@ -0,0 +1,469 @@
+// What a run reads, as the daemon keys it. Every read is a daemon input
+// (maintainer decision, 2026-11-16, "All of them"): a file read through fs
+// on any path, node_modules included, an environment variable, and what
+// the config's own plugins read. So when one changes between two checks,
+// the next check through the daemon reports what a cold run reports (the
+// CLI oracle's law 9).
+//
+// An input's key is `fs:` for a file, hashed by its text (or as
+// `not a file`, or `missing`), `dir:` for a directory's listing,
+// hashed by its entries' names and kinds, or `dirs:` for a recursive
+// one, `stat:` for a test of whether a path exists and what it is,
+// hashed by that, `statx:` for a path's metadata (its size, times,
+// identity, mode and kind, a directory's by its kind alone), `env:`
+// for a variable, hashed by its value, or `env:*` for the
+// set of names, which code reads when it lists the environment. The harness (capture-setup.mjs) watches a test's reads in
+// its worker, and the session (check.mjs) watches what the config and its
+// plugins read in the CLI's process. Both files are copied beside the
+// harness with this one.
+import { createHash } from 'node:crypto'
+import fs from 'node:fs'
+import { createRequire, syncBuiltinESMExports } from 'node:module'
+import { basename, dirname, isAbsolute, join } from 'node:path'
+import { fileURLToPath, pathToFileURL } from 'node:url'
+import { posix } from './paths.mjs'
+
+// The calls that read a file (a stream's too, by the whole file). Each is
+// taken once per process, before a wrapper replaces it, so hashing a file is
+// not itself a read.
+const reads = [
+ [fs, [`readFileSync`, `readFile`, `createReadStream`]],
+ [fs.promises, [`readFile`]],
+]
+// The calls that test whether a file exists and what it is: an input by its
+// existence and kind (G42's stat family), not by its text, so that Vite's
+// resolution, which stats each module it imports, does not make every
+// module's text an input of every run. `existsSync` tells nothing more.
+const stats = [[fs, [`existsSync`]]]
+// The calls that read a path's metadata: a stat's size or times change with
+// the text, so the result is an input by all of them (`statx:`), not by kind
+// alone (133-1). The callback form of `stat` is one too (133-6).
+const metadata = [
+ [fs, [`statSync`, `stat`]],
+ [fs.promises, [`stat`]],
+]
+// The calls that list a directory.
+const listings = [
+ [fs, [`readdirSync`, `readdir`, `opendirSync`, `opendir`]],
+ [fs.promises, [`readdir`, `opendir`]],
+]
+// The calls that write a file's text. A file that a reader wrote before it
+// reads it holds the reader's own output, which follows from the reader's
+// other inputs, so that read is no input: a test's temporary file, or the
+// config that Vite bundles into a temporary file and then imports.
+const writes = [
+ [fs, [`writeFileSync`, `writeFile`, `appendFileSync`, `appendFile`]],
+ [fs.promises, [`writeFile`, `appendFile`]],
+]
+// The calls that copy a file or a tree from their first path to their second.
+// The source is read, and the destination is the tree's own output once the
+// copy succeeds, as a write's is (`copied`, below). A test that copies a
+// fixture into a directory it makes, then has its child read it, is no input.
+const copies = [
+ [fs, [`copyFileSync`, `cpSync`]],
+ [fs.promises, [`copyFile`, `cp`]],
+]
+// The calls that make a directory: its path (mkdir) or the one it returns
+// (mkdtemp) is the run's own output from the call's success, so a read of it
+// after that is no input (a test's temporary directory, removed at the end).
+const makes = [
+ [fs, [`mkdirSync`, `mkdtempSync`]],
+ [fs.promises, [`mkdir`, `mkdtemp`]],
+]
+const original = (globalThis.__oracleGapsOriginalFs ??= {
+ readFileSync: fs.readFileSync,
+ statSync: fs.statSync,
+ readdirSync: fs.readdirSync,
+ realpathSync: fs.realpathSync.native,
+})
+const sha1 = (data) => createHash(`sha1`).update(data).digest(`hex`)
+
+/**
+ * The SHA-1 of a file's bytes, read in chunks: a whole-file read fails for a
+ * regular file past about 2 GiB (ERR_FS_FILE_TOO_LARGE), and such a file's
+ * edits must still be seen (CR-10). Equal to `sha1(readFileSync(path))` for
+ * any file that a whole read can take.
+ */
+export function fileSha1(path) {
+ const hash = createHash(`sha1`)
+ const fd = fs.openSync(path, `r`)
+ try {
+ const chunk = Buffer.allocUnsafe(1 << 20)
+ for (;;) {
+ const count = fs.readSync(fd, chunk, 0, chunk.length, null)
+ if (count === 0) break
+ hash.update(chunk.subarray(0, count))
+ }
+ } finally {
+ fs.closeSync(fd)
+ }
+ return hash.digest(`hex`)
+}
+
+/**
+ * A file's input hash now, never from a cache: the hash of its text, or
+ * `not a file` (a test can stat a directory, whose input is that a
+ * directory is there), or `missing`.
+ */
+export function fileHash(path) {
+ try {
+ return original.statSync(path).isFile() ? fileSha1(path) : `not a file`
+ } catch {
+ return `missing`
+ }
+}
+
+// The directory that holds an entry of a listing: `parentPath` where Node has
+// it (20.12 and later, 21.4 and later), else `path`, which Node 20.1 to 20.11
+// gave as the parent (CR-11), else the listing's root.
+const parentOf = (entry, root) => entry.parentPath ?? entry.path ?? root
+
+/**
+ * A directory's input hash now: that of its entries' names and kinds, every
+ * level's for a recursive listing, or `not a directory`, or `missing`.
+ */
+function listingHash(path, recursive) {
+ try {
+ return sha1(
+ original
+ .readdirSync(path, { withFileTypes: true, recursive })
+ // The runner's own entries (its session directory) are no input.
+ .filter(
+ (entry) =>
+ !isRunnerFile(`${posix(parentOf(entry, path))}/${entry.name}/`),
+ )
+ .map(
+ (entry) =>
+ `${posix(parentOf(entry, path))}/${entry.name}\0${entry.isDirectory() ? `d` : entry.isSymbolicLink() ? `l` : `f`}`,
+ )
+ .sort()
+ .join(`\0`),
+ )
+ } catch (error) {
+ return error?.code === `ENOTDIR` ? `not a directory` : `missing`
+ }
+}
+
+/** A file's or a directory's input hash now, by its key. */
+export const inputHash = (key) =>
+ key.startsWith(`fs:`)
+ ? fileHash(key.slice(3))
+ : key.startsWith(`stat:`)
+ ? kindOf(key.slice(5))
+ : key.startsWith(`statx:`)
+ ? metadataHash(key.slice(6))
+ : key.startsWith(`dirs:`)
+ ? listingHash(key.slice(5), true)
+ : listingHash(key.slice(4), false)
+
+/** A path's existence and kind now. */
+function kindOf(path) {
+ try {
+ const stat = original.statSync(path)
+ return stat.isFile() ? `file` : stat.isDirectory() ? `directory` : `other`
+ } catch {
+ return `missing`
+ }
+}
+
+/**
+ * A path's metadata now: a file's size, times, identity, and mode, so that an
+ * edit that keeps the size, or a hand edit that keeps the time, is still a
+ * change (133-1). A directory's is its kind alone: its times move with every
+ * entry the runner itself writes beside the tests, and its entries are an
+ * input where a test lists them.
+ */
+function metadataHash(path) {
+ try {
+ const stat = original.statSync(path)
+ return stat.isFile()
+ ? sha1(
+ [
+ stat.size,
+ stat.mtimeMs,
+ stat.ctimeMs,
+ stat.ino,
+ stat.mode,
+ `file`,
+ ].join(`\0`),
+ )
+ : stat.isDirectory()
+ ? `directory`
+ : `other`
+ } catch {
+ return `missing`
+ }
+}
+
+/** A variable's input hash under `env`, or for `*`, that of its names. */
+export const envHash = (
+ name,
+ env = globalThis.__oracleGapsEnv ?? process.env,
+) =>
+ sha1(
+ name === `*`
+ ? Object.keys(env).sort().join(`\0`)
+ : `${env[name] === undefined ? `unset` : `=${env[name]}`}`,
+ )
+
+// A path as it was given, made absolute against the working directory but
+// with its `..` components kept (CR-22).
+const spelledAbsolute = (path) =>
+ isAbsolute(path) ? path : `${process.cwd()}/${path}`
+
+// The runner's own files: a session directory (`.oracle-gaps-/`, which
+// holds this file) and the copies of test files
+// (`.oracle-gaps---`). A user's path that only contains
+// `.oracle-gaps` is an input like any other.
+// The mid-run test marker (`.oracle-gaps-midrun.txt`, one per package) is
+// the test harness's own file, so it is runner-owned too.
+// The runner's own files, which no test reads as an input: its copies, the
+// marker of a mid-run check, and Vitest's results caches (`.vite/vitest` and
+// `.vitest-cache`, rewritten by every run of Vitest with the run's timings, so
+// no run finds the same text; a nested run of Vitest writes them too).
+const isRunnerFile = (path) =>
+ /\/\.oracle-gaps-\d+[-/]/.test(path) ||
+ path.endsWith(`/.oracle-gaps-midrun.txt`) ||
+ /\/node_modules\/\.vite\/vitest\//.test(path) ||
+ /\/node_modules\/\.vitest-cache\/_metadata\.json$/.test(path)
+
+/**
+ * A wrapper keeps every own property of the function it wraps (its name
+ * and length, which code that dispatches on arity reads, or
+ * `util.promisify.custom`), so a test that passes alone passes under the
+ * capture (law 3; review of #55).
+ */
+export function keepProperties(from, to) {
+ for (const key of Reflect.ownKeys(from))
+ if (key !== `prototype`)
+ Object.defineProperty(to, key, Object.getOwnPropertyDescriptor(from, key))
+ return to
+}
+
+/**
+ * Watches this process's reads from now on: each read calls `record(key)`
+ * with the input's key, and each write of a file or a variable
+ * `record(key, true)`, the
+ * `record` of the latest call. The wrappers are
+ * installed once per process. A file's path is the path rule's (paths.mjs),
+ * and the runner's own files are left out. An ES module's
+ * `import { readFileSync } from 'node:fs'` reads the wrappers too.
+ */
+export function watchReads(record) {
+ globalThis.__oracleGapsRecord = record
+ if (globalThis.__oracleGapsWatching) return
+ globalThis.__oracleGapsWatching = true
+ record = (key, write) => globalThis.__oracleGapsRecord(key, write)
+ // Records what a call reads before it runs, and returns the mark that
+ // records what a write makes the tree's own once the write has succeeded
+ // (undefined for a call that writes nothing). A failed write marks nothing
+ // (CR-12), so a read after it is an input.
+ const watched = (target, kind, args, name) => {
+ const write = kind === `write`
+ // A listing's options come first, a write's after its data.
+ const options = kind === `list` ? args[0] : args[1]
+ // A write that keeps the bytes it does not overwrite reads them first:
+ // an append (a call named `append...`, or the flag `a`), and a
+ // read-write open without truncation (the flag `r+`, CR-21; a numeric
+ // flag without O_TRUNC, such as fs.constants.O_RDWR, CR-21). Its read is
+ // an input unless the copy wrote the file first (133-3), so it records
+ // `append` (a read) before the call, and `true` (the write) after it.
+ const flag =
+ typeof options === `object` && options !== null
+ ? (options.flag ?? `w`)
+ : `w`
+ const keeps =
+ write &&
+ (/append/i.test(name) ||
+ (typeof flag === `number`
+ ? (flag & fs.constants.O_TRUNC) === 0
+ : /^[ar]/.test(String(flag))))
+ let path
+ try {
+ // A path keeps the spelling it was given: the kernel resolves `..`
+ // after a symbolic link, which `resolve` would collapse first (CR-22).
+ if (target instanceof URL) path = fileURLToPath(target)
+ else if (typeof target === `string`) path = spelledAbsolute(target)
+ else if (Buffer.isBuffer(target))
+ path = spelledAbsolute(target.toString())
+ } catch {
+ return undefined
+ }
+ if (path === undefined || isRunnerFile(posix(path))) return undefined
+ const prefix =
+ kind === `stat`
+ ? `stat`
+ : kind === `statx`
+ ? `statx`
+ : kind !== `list`
+ ? `fs`
+ : options?.recursive
+ ? `dirs`
+ : `dir`
+ const keys = [`${prefix}:${posix(path)}`]
+ // A written file is also known by its directory's real path, which a
+ // later read through a link, or an import by its real URL, names.
+ if (write)
+ try {
+ keys.push(
+ `fs:${posix(join(original.realpathSync(dirname(path)), basename(path)))}`,
+ )
+ } catch {
+ // No directory to write in: the write fails as it would.
+ }
+ if (!write) {
+ for (const key of keys) record(key, false)
+ return undefined
+ }
+ if (keeps) for (const key of keys) record(key, `append`)
+ return () => {
+ for (const key of keys) record(key, true)
+ }
+ }
+ // A copy reads its source (the first path) and writes its destination (the
+ // second), which is marked once the copy has succeeded.
+ const copied = (source, destination, name) => {
+ watched(source, `read`, [], name)
+ return watched(destination, `write`, [], name)
+ }
+ for (const [calls, kind] of [
+ [reads, `read`],
+ [stats, `stat`],
+ [metadata, `statx`],
+ [listings, `list`],
+ [writes, `write`],
+ [copies, `copy`],
+ ])
+ for (const [owner, names] of calls)
+ for (const name of names) {
+ const call = owner[name]
+ owner[name] = keepProperties(call, function (target, ...rest) {
+ const mark =
+ kind === `copy`
+ ? copied(target, rest[0], name)
+ : watched(target, kind, rest, name)
+ if (mark === undefined) return call.call(this, target, ...rest)
+ // The mark follows the write's success: a callback without an
+ // error, a promise's resolution, or the sync return.
+ if (typeof rest.at(-1) === `function`) {
+ const done = rest.pop()
+ rest.push(function (error, ...values) {
+ if (!error) mark()
+ return done.call(this, error, ...values)
+ })
+ return call.call(this, target, ...rest)
+ }
+ const result = call.call(this, target, ...rest)
+ if (result && typeof result.then === `function`)
+ return result.then((value) => {
+ mark()
+ return value
+ })
+ mark()
+ return result
+ })
+ }
+ for (const [owner, names] of makes)
+ for (const name of names) {
+ const call = owner[name]
+ const returned = name.startsWith(`mkdtemp`)
+ const made = (path) => {
+ if (path === undefined) return
+ const mark = watched(path, `write`, [], name)
+ if (mark !== undefined) mark()
+ }
+ owner[name] = keepProperties(call, function (target, ...rest) {
+ const result = call.call(this, target, ...rest)
+ if (result && typeof result.then === `function`)
+ return result.then((value) => {
+ made(returned ? value : target)
+ return value
+ })
+ made(returned ? result : target)
+ return result
+ })
+ }
+ syncBuiltinESMExports()
+ // A variable read by name, a test of whether it is set, and a listing of
+ // the names, which reads the set of names.
+ // The environment itself, which hashing reads without being watched.
+ globalThis.__oracleGapsEnv = process.env
+ process.env = new Proxy(process.env, {
+ get(env, name) {
+ if (typeof name === `string`) record(`env:${name}`)
+ return Reflect.get(env, name)
+ },
+ has(env, name) {
+ if (typeof name === `string`) record(`env:${name}`)
+ return Reflect.has(env, name)
+ },
+ ownKeys(env) {
+ record(`env:*`)
+ return Reflect.ownKeys(env)
+ },
+ // A write goes to the environment itself, which keeps its own rules
+ // (a value is a string). A variable the reader set is its own output.
+ set(env, name, value) {
+ if (typeof name === `string`) record(`env:${name}`, true)
+ return Reflect.set(env, name, value)
+ },
+ })
+}
+
+// The code of an eval worker with the preload first (CR-24). The preload goes
+// after the directive prologue (every leading string-literal statement, such
+// as `'use strict'`, and `'custom'` before it), which must stay the first
+// statements of the code, or the worker's strictness changes.
+const preloadedCode = (code, preload) => {
+ // Leading space and comments, then string-literal statements, each ended by
+ // `;` or a line end (so `'use strict'.length` is not a directive).
+ const prologue =
+ /^(?:\s|\/\/[^\n]*\n|\/\*[\s\S]*?\*\/)*(?:(['"])(?:[^'"\\\n]|\\.)*\1(?:[ \t]*;|[ \t]*(?=\n))\s*)*/.exec(
+ code,
+ )[0]
+ return `${prologue};require(${JSON.stringify(preload)});\n${code.slice(prologue.length)}`
+}
+
+/**
+ * Gives every Worker that this realm starts the child-writes preload, so a
+ * worker's reads and writes reach the log of its process tree (#143). A
+ * worker takes the `--import` in its execArgv, and an eval worker ignores it,
+ * so its code first requires the preload (`preloadedCode`). A worker whose
+ * `env` is an object gets the log's name too. Applied in the test's realm by
+ * capture-setup.mjs, and in every preloaded process by child-writes.mjs, so a
+ * worker started from a worker is covered at any depth (CR-25).
+ */
+export function patchWorkerThreads(preload) {
+ if (globalThis.__oracleGapsWorkerPatch) return
+ globalThis.__oracleGapsWorkerPatch = true
+ const threads = createRequire(import.meta.url)(`node:worker_threads`)
+ const Base = threads.Worker
+ const href = pathToFileURL(preload).href
+ class Watched extends Base {
+ constructor(file, options = {}) {
+ const env =
+ options.env && typeof options.env === `object`
+ ? {
+ ...options.env,
+ ORACLE_GAPS_CHILD_WRITES: process.env.ORACLE_GAPS_CHILD_WRITES,
+ }
+ : options.env
+ super(
+ options.eval && typeof file === `string`
+ ? preloadedCode(file, preload)
+ : file,
+ {
+ ...options,
+ env,
+ execArgv: [
+ ...(options.execArgv ?? process.execArgv),
+ `--import`,
+ href,
+ ],
+ },
+ )
+ }
+ }
+ threads.Worker = Watched
+ syncBuiltinESMExports()
+}
diff --git a/packages/oracles/scripts/e2e-shards.mjs b/packages/oracles/scripts/e2e-shards.mjs
index 52b1c777..e84d302e 100644
--- a/packages/oracles/scripts/e2e-shards.mjs
+++ b/packages/oracles/scripts/e2e-shards.mjs
@@ -42,6 +42,12 @@ const suite = `oracle-gaps.report`
export const shards = {
// 522 s in the measured run, about 221 s idle.
'e2e-1': [
+ `fixed seed 20261105: an edit to a gate that a test reads, during a check through the daemon`,
+ `fixed seed 20261105: an edit to a file a test reads through a link and dot-dot`,
+ `random seed: an edit to a file a test reads inside a worker started by a worker`,
+ `random seed: an edit to a file a test reads in a worker with strict mode`,
+ `determinism: constructed history: an edit to a gate that a test reads, during a check through the daemon`,
+ `determinism: constructed history: an edit to a file a test reads through a link and dot-dot`,
`fixed seed 20261105: a stop with the default output directory`,
`fixed seed 20261105: a daemon check with the default output directory`,
`fixed seed 20261105: a daemon check with the default output directory, unsupervised`,
@@ -133,6 +139,80 @@ export const shards = {
`fixed seed 20261105: an edit to data a test reads through fs (statDir)`,
`random seed: an edit to data a test reads through fs (statDir)`,
`determinism: constructed history: an edit to data a test reads through fs (statDir)`,
+ // The daemon-input histories (law 9, every read is a daemon input): about
+ // 25 s each on the Arca pool, fixed seed.
+ `fixed seed 20261105: an edit to a file in the package that keeps its size and modification time`,
+ `random seed: an edit to a file in the package that keeps its size and modification time`,
+ `determinism: constructed history: an edit to a file in the package that keeps its size and modification time`,
+ `fixed seed 20261105: an edit to a file outside the package that a test reads`,
+ `random seed: an edit to a file outside the package that a test reads`,
+ `determinism: constructed history: an edit to a file outside the package that a test reads`,
+ `fixed seed 20261105: an edit to a file under node_modules that a test reads`,
+ `random seed: an edit to a file under node_modules that a test reads`,
+ `determinism: constructed history: an edit to a file under node_modules that a test reads`,
+ `fixed seed 20261105: an edit to an environment variable that a test reads`,
+ `random seed: an edit to an environment variable that a test reads`,
+ `determinism: constructed history: an edit to an environment variable that a test reads`,
+ `fixed seed 20261105: an edit to a file the config's plugin reads when the config resolves`,
+ `random seed: an edit to a file the config's plugin reads when the config resolves`,
+ `determinism: constructed history: an edit to a file the config's plugin reads when the config resolves`,
+ `fixed seed 20261105: an edit to a file the config's plugin reads when it transforms a test`,
+ `random seed: an edit to a file the config's plugin reads when it transforms a test`,
+ `determinism: constructed history: an edit to a file the config's plugin reads when it transforms a test`,
+ `fixed seed 20261105: an edit to a directory listing that a test reads`,
+ `random seed: an edit to a directory listing that a test reads`,
+ `determinism: constructed history: an edit to a directory listing that a test reads`,
+ `fixed seed 20261105: an edit to a directory a test reads through opendir`,
+ `random seed: an edit to a directory a test reads through opendir`,
+ `determinism: constructed history: an edit to a directory a test reads through opendir`,
+ `fixed seed 20261105: an edit to a file a test reads through a stream`,
+ `random seed: an edit to a file a test reads through a stream`,
+ `determinism: constructed history: an edit to a file a test reads through a stream`,
+ "fixed seed 20261105: an edit to the tsconfig that Vite's own plugin reads",
+ "random seed: an edit to the tsconfig that Vite's own plugin reads",
+ "determinism: constructed history: an edit to the tsconfig that Vite's own plugin reads",
+ 'fixed seed 20261105: an edit to a directory the config lists when it loads',
+ 'random seed: an edit to a directory the config lists when it loads',
+ 'determinism: constructed history: an edit to a directory the config lists when it loads',
+ "fixed seed 20261105: a hand edit of a file the config's plugin writes",
+ "random seed: a hand edit of a file the config's plugin writes",
+ "determinism: constructed history: a hand edit of a file the config's plugin writes",
+ 'fixed seed 20261105: a test that reads a file its child process wrote, rechecked through the daemon',
+ 'random seed: a test that reads a file its child process wrote, rechecked through the daemon',
+ 'determinism: constructed history: a test that reads a file its child process wrote, rechecked through the daemon',
+ 'fixed seed 20261105: an edit to a file the test stats for its size, by statSync',
+ 'random seed: an edit to a file the test stats for its size, by statSync',
+ 'determinism: constructed history: an edit to a file the test stats for its size, by statSync',
+ 'fixed seed 20261105: an edit to a file the test stats for its size, by fs/promises stat',
+ 'random seed: an edit to a file the test stats for its size, by fs/promises stat',
+ 'determinism: constructed history: an edit to a file the test stats for its size, by fs/promises stat',
+ 'fixed seed 20261105: an edit to a file the test stats for its size, by the callback stat',
+ 'random seed: an edit to a file the test stats for its size, by the callback stat',
+ 'determinism: constructed history: an edit to a file the test stats for its size, by the callback stat',
+ 'fixed seed 20261105: an edit to a file a test appends to, then reads',
+ 'random seed: an edit to a file a test appends to, then reads',
+ 'determinism: constructed history: an edit to a file a test appends to, then reads',
+ 'fixed seed 20261105: an edit to a file a test appends to with flag a, then reads',
+ 'random seed: an edit to a file a test appends to with flag a, then reads',
+ 'determinism: constructed history: an edit to a file a test appends to with flag a, then reads',
+ 'fixed seed 20261105: an edit to a file a test requires as JSON',
+ 'random seed: an edit to a file a test requires as JSON',
+ 'determinism: constructed history: an edit to a file a test requires as JSON',
+ 'fixed seed 20261105: an edit to a file that a test child process reads',
+ 'random seed: an edit to a file that a test child process reads',
+ 'determinism: constructed history: an edit to a file that a test child process reads',
+ 'fixed seed 20261105: a test that writes to the console, rechecked through the daemon',
+ 'random seed: a test that writes to the console, rechecked through the daemon',
+ 'determinism: constructed history: a test that writes to the console, rechecked through the daemon',
+ 'fixed seed 20261105: an edit to a file a test reads inside a worker thread',
+ 'random seed: an edit to a file a test reads inside a worker thread',
+ 'determinism: constructed history: an edit to a file a test reads inside a worker thread',
+ 'fixed seed 20261105: an edit to the package.json main that a test requires',
+ 'random seed: an edit to the package.json main that a test requires',
+ 'determinism: constructed history: an edit to the package.json main that a test requires',
+ 'fixed seed 20261105: an edit to the package.json type that a test requires',
+ 'random seed: an edit to the package.json type that a test requires',
+ 'determinism: constructed history: an edit to the package.json type that a test requires',
// Added with the CLI's parent-config discovery (not yet measured).
`fixed seed 20261105: a package whose parent directory has its config`,
`random seed: test.projects in a parent's config`,
@@ -140,6 +220,12 @@ export const shards = {
],
// 522 s in the measured run, about 221 s idle.
'e2e-2': [
+ `fixed seed 20261105: an edit to a file a test reads inside a worker started by a worker`,
+ `fixed seed 20261105: an edit to a file a test reads in a worker with strict mode`,
+ `random seed: an edit to a file a test tries to create exclusively, then reads`,
+ `random seed: an unchanged check through the daemon while a config's plugin writes, stats and removes a scratch file`,
+ `determinism: constructed history: an edit to a file a test reads inside a worker started by a worker`,
+ `determinism: constructed history: an edit to a file a test reads in a worker with strict mode`,
`fixed seed 20261105: two starts race for a stale claim`,
`fixed seed 20261105: a start refuses a stale claim`,
`fixed seed 20261105: a start refuses an empty claim`,
@@ -156,6 +242,7 @@ export const shards = {
`random seed: a config fault in a run that owns nothing`,
`random seed: a declaration fault: apiLessTypescript`,
`calibration: a crash is reported as a kill`,
+ `calibration: a kill is reported as a crash, and names the error`,
`calibration: a daemon is left after --stop-daemon`,
`calibration: a refused run is reported as complete`,
`determinism: constructed history: a .cjs config that calls require`,
@@ -179,9 +266,18 @@ export const shards = {
`fixed seed 20261105: a failing owner under its parent's config`,
`random seed: a package whose parent directory has its config`,
`determinism: constructed history: test.projects in a parent's config`,
+ `fixed seed 20261105: an unchanged check through the daemon while a test made the files it reads: a file its child process makes after the test checks for it`,
+ `random seed: an unchanged check through the daemon while a test made the files it reads: a file its child process makes after the test checks for it`,
+ `determinism: constructed history: an unchanged check through the daemon while a test made the files it reads: a file its child process makes after the test checks for it`,
],
// 522 s in the measured run, about 221 s idle.
'e2e-3': [
+ `fixed seed 20261105: an edit to a file a test tries to create exclusively, then reads`,
+ `fixed seed 20261105: an unchanged check through the daemon while a config's plugin writes, stats and removes a scratch file`,
+ `random seed: an edit to a file a test opens for update, then reads`,
+ `random seed: a check through the daemon of a config whose plugin object is frozen`,
+ `determinism: constructed history: an edit to a file a test tries to create exclusively, then reads`,
+ `determinism: constructed history: an unchanged check through the daemon while a config's plugin writes, stats and removes a scratch file`,
`fixed seed 20261105: a daemon pause that cannot engage`,
`random seed: a daemon pause that cannot engage`,
`determinism: constructed history: a daemon pause that cannot engage`,
@@ -289,6 +385,12 @@ export const shards = {
],
// 522 s in the measured run, about 221 s idle.
'e2e-4': [
+ `fixed seed 20261105: an edit to a file a test opens for update, then reads`,
+ `fixed seed 20261105: a check through the daemon of a config whose plugin object is frozen`,
+ `random seed: an edit to a file that a child process reads when its own log fails`,
+ `calibration: the check that a changed plugin input reached kept the daemon of the check before it`,
+ `determinism: constructed history: an edit to a file a test opens for update, then reads`,
+ `determinism: constructed history: a check through the daemon of a config whose plugin object is frozen`,
`random seed: two starts race for a stale claim`,
`random seed: a start refuses a stale claim`,
`random seed: a start refuses an empty claim`,
@@ -363,9 +465,17 @@ export const shards = {
`fixed seed 20261105: a flaky owner's loop calls under the call budget`,
`random seed: a flaky owner's loop calls under the call budget`,
`determinism: constructed history: a flaky owner's loop calls under the call budget`,
+ `fixed seed 20261105: an unchanged check through the daemon while a test made the files it reads: a copy its child process reads, in a directory it removes`,
+ `random seed: an unchanged check through the daemon while a test made the files it reads: a copy its child process reads, in a directory it removes`,
+ `determinism: constructed history: an unchanged check through the daemon while a test made the files it reads: a copy its child process reads, in a directory it removes`,
],
// 522 s in the measured run, about 221 s idle.
'e2e-5': [
+ `fixed seed 20261105: an edit to a file that a child process reads when its own log fails`,
+ `random seed: an edit to a gate that a test reads, during a check through the daemon`,
+ `random seed: an edit to a file a test reads through a link and dot-dot`,
+ `calibration: the unchanged recheck that a new daemon served is named`,
+ `determinism: constructed history: an edit to a file that a child process reads when its own log fails`,
// A probe branch under a generated test's work bound (about 3 s each on
// an Arclet for the fixed-seed and random units).
`fixed seed 20261105: a probe branch under a generated test's work bound`,
@@ -670,6 +780,12 @@ export const shards = {
`random seed: an unregistered soft verdict before a later calibration spin survives the cut`,
`determinism: constructed history: a verdict after a clocked count cut's budget throw does not kill`,
`determinism: constructed history: an unregistered soft verdict before a later calibration spin survives the cut`,
+ `fixed seed 20261105: an unchanged check through the daemon while a test made the files it reads: a directory it lists before it writes a file into it`,
+ `random seed: an unchanged check through the daemon while a test made the files it reads: a directory it lists before it writes a file into it`,
+ `determinism: constructed history: an unchanged check through the daemon while a test made the files it reads: a directory it lists before it writes a file into it`,
+ `fixed seed 20261105: an unchanged check through the daemon while a test made the files it reads: a directory its child process makes, checks for, and removes`,
+ `random seed: an unchanged check through the daemon while a test made the files it reads: a directory its child process makes, checks for, and removes`,
+ `determinism: constructed history: an unchanged check through the daemon while a test made the files it reads: a directory its child process makes, checks for, and removes`,
],
}
diff --git a/packages/oracles/scripts/pr-shards.mjs b/packages/oracles/scripts/pr-shards.mjs
index 48fa9f7f..72efee46 100644
--- a/packages/oracles/scripts/pr-shards.mjs
+++ b/packages/oracles/scripts/pr-shards.mjs
@@ -28,18 +28,103 @@ import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { packedShards } from './ci-packed-shards.mjs'
+// The constructed histories of the edits of each kind of daemon input
+// (gap-report-oracle.property.test.mjs).
+const daemonInputUnits = [
+ 'an edit to a file in the package that keeps its size and modification time',
+ 'an edit to a file outside the package that a test reads',
+ 'an edit to a file under node_modules that a test reads',
+ 'an edit to an environment variable that a test reads',
+ "an edit to a file the config's plugin reads when the config resolves",
+ "an edit to a file the config's plugin reads when it transforms a test",
+ 'an edit to a directory listing that a test reads',
+ 'an edit to a directory a test reads through opendir',
+ 'an edit to a file a test reads through a stream',
+ "an edit to the tsconfig that Vite's own plugin reads",
+ 'an edit to a directory the config lists when it loads',
+ "a hand edit of a file the config's plugin writes",
+ // A file the test's child process wrote (own writes of the process tree).
+ 'a test that reads a file its child process wrote, rechecked through the daemon',
+ 'an edit to a file the test stats for its size, by statSync',
+ 'an edit to a file the test stats for its size, by fs/promises stat',
+ 'an edit to a file the test stats for its size, by the callback stat',
+ 'an edit to a file a test appends to, then reads',
+ 'an edit to a file a test appends to with flag a, then reads',
+ 'an edit to a file a test requires as JSON',
+ 'an edit to a file that a test child process reads',
+ 'a test that writes to the console, rechecked through the daemon',
+ 'an edit to a file a test reads inside a worker thread',
+ 'an edit to the package.json main that a test requires',
+ 'an edit to the package.json type that a test requires',
+]
const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, `\\$&`)
const anyOf = (names) => `(?:${names.map(escape).join(`|`)})`
const rest = Symbol(`rest`)
// A partition's shards as packed from CI's measured durations
// (scripts/pack-shards-from-ci.mjs writes ci-packed-shards.mjs).
-const packed = (partition) =>
- Object.fromEntries(
- Object.entries(packedShards[partition]).map(([shard, names]) => [
+// The constructed histories that this branch adds, which no CI run has
+// measured yet. `pack` (scripts/pack-shards-from-ci.mjs) places a test only
+// once `fetch` has its duration, so until the next measured run these are
+// dealt out over each packed partition's shards in turn, each under the
+// partition's prefix. Once a run measures them, `pack` places them, and this
+// list is emptied.
+const unmeasuredHistories = [
+ 'an edit to a file in the package that keeps its size and modification time',
+ 'an edit to a file outside the package that a test reads',
+ 'an edit to a file under node_modules that a test reads',
+ 'an edit to an environment variable that a test reads',
+ "an edit to a file the config's plugin reads when the config resolves",
+ "an edit to a file the config's plugin reads when it transforms a test",
+ 'an edit to a directory listing that a test reads',
+ 'an edit to a directory a test reads through opendir',
+ 'an edit to a file a test reads through a stream',
+ "an edit to the tsconfig that Vite's own plugin reads",
+ 'an edit to a directory the config lists when it loads',
+ "a hand edit of a file the config's plugin writes",
+ 'a test that reads a file its child process wrote, rechecked through the daemon',
+ 'an edit to a file the test stats for its size, by statSync',
+ 'an edit to a file the test stats for its size, by fs/promises stat',
+ 'an edit to a file the test stats for its size, by the callback stat',
+ 'an edit to a file a test appends to, then reads',
+ 'an edit to a file a test appends to with flag a, then reads',
+ 'an edit to a file a test requires as JSON',
+ 'an edit to a file that a test child process reads',
+ 'a test that writes to the console, rechecked through the daemon',
+ 'an edit to a file a test reads inside a worker thread',
+ 'an edit to the package.json main that a test requires',
+ 'an edit to the package.json type that a test requires',
+ 'an edit to a gate that a test reads, during a check through the daemon',
+ 'an edit to a file a test reads inside a worker started by a worker',
+ 'an edit to a file a test tries to create exclusively, then reads',
+ 'an edit to a file a test opens for update, then reads',
+ 'an edit to a file that a child process reads when its own log fails',
+ 'an edit to a file a test reads through a link and dot-dot',
+ 'an edit to a file a test reads in a worker with strict mode',
+ "an unchanged check through the daemon while a config's plugin writes, stats and removes a scratch file",
+ 'a check through the daemon of a config whose plugin object is frozen',
+ 'an unchanged check through the daemon while a test made the files it reads: a file its child process makes after the test checks for it',
+ 'an unchanged check through the daemon while a test made the files it reads: a copy its child process reads, in a directory it removes',
+ 'an unchanged check through the daemon while a test made the files it reads: a directory it lists before it writes a file into it',
+ 'an unchanged check through the daemon while a test made the files it reads: a directory its child process makes, checks for, and removes',
+]
+const unmeasuredPrefix = {
+ 'oracle-gaps-determinism': 'constructed history: ',
+}
+const packed = (partition) => {
+ const entries = Object.entries(packedShards[partition])
+ const dealt = entries.map(() => [])
+ unmeasuredHistories.forEach((name, index) =>
+ dealt[index % entries.length].push(
+ (unmeasuredPrefix[partition] ?? '') + name,
+ ),
+ )
+ return Object.fromEntries(
+ entries.map(([shard, names], index) => [
shard,
- anyOf(names),
+ anyOf([...names, ...dealt[index]]),
]),
)
+}
// The self-oracle's test names, split by the start of the name after its
// kind (`determinism: fixed history: `, `fixed history: `, `calibration: `):
diff --git a/packages/oracles/tests/gap-eval-worker-prologue.test.ts b/packages/oracles/tests/gap-eval-worker-prologue.test.ts
new file mode 100644
index 00000000..8204afd2
--- /dev/null
+++ b/packages/oracles/tests/gap-eval-worker-prologue.test.ts
@@ -0,0 +1,34 @@
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { createRequire } from 'node:module'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { describe, expect, test } from 'vitest'
+import { patchWorkerThreads } from '../oracle-gaps/inputs.mjs'
+
+// An eval worker's code gets the child-writes preload ahead of it. The preload
+// must go after the whole directive prologue: a `'custom'` directive before
+// `'use strict'` must not let the preload turn strict mode off (CR-24).
+const require = createRequire(import.meta.url)
+
+describe(`the preload of an eval worker`, () => {
+ test(`keeps every leading directive first, so the worker stays strict`, async () => {
+ const dir = mkdtempSync(join(tmpdir(), `gap-prologue-`))
+ try {
+ const preload = join(dir, `preload.mjs`)
+ writeFileSync(preload, `// an empty preload\n`)
+ patchWorkerThreads(preload)
+ const { Worker } = require(`node:worker_threads`)
+ const probe = `require('node:worker_threads').parentPort.postMessage((function () { return this === undefined })())`
+ const run = (code: string) =>
+ new Promise((resolve, reject) => {
+ const worker = new Worker(code, { eval: true })
+ worker.on(`message`, resolve)
+ worker.on(`error`, reject)
+ })
+ expect(await run(`'use strict'; ${probe}`)).toBe(true)
+ expect(await run(`'custom'; 'use strict'; ${probe}`)).toBe(true)
+ } finally {
+ rmSync(dir, { recursive: true, force: true })
+ }
+ })
+})
diff --git a/packages/oracles/tests/gap-inputs-large-file.test.ts b/packages/oracles/tests/gap-inputs-large-file.test.ts
new file mode 100644
index 00000000..3eff22c0
--- /dev/null
+++ b/packages/oracles/tests/gap-inputs-large-file.test.ts
@@ -0,0 +1,60 @@
+import {
+ closeSync,
+ mkdtempSync,
+ openSync,
+ rmSync,
+ truncateSync,
+ writeFileSync,
+ writeSync,
+} from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { describe, expect, test } from 'vitest'
+import { fileHash } from '../oracle-gaps/inputs.mjs'
+
+// A file's input hash is its text's SHA-1 (inputs.mjs). A whole-file read
+// cannot take a regular file past about 2 GiB (ERR_FS_FILE_TOO_LARGE), so a
+// larger file hashed as missing, and its edits were not seen (CR-10). The hash
+// reads the file in chunks instead. The file here is sparse, so it is cheap to
+// make and to read; sparse files are not made on Windows, so the test is
+// skipped there.
+const LIMIT = 2 * 1024 ** 3 + 512 * 1024 ** 2
+
+describe(`the input hash of a file past a whole read's limit`, () => {
+ test.skipIf(process.platform === `win32`)(
+ `hashes a 2.5 GiB file and sees an edit at its end`,
+ () => {
+ const dir = mkdtempSync(join(tmpdir(), `gap-large-`))
+ try {
+ const big = join(dir, `big.bin`)
+ writeFileSync(big, ``)
+ truncateSync(big, LIMIT)
+ const before = fileHash(big)
+ expect(before).toMatch(/^[0-9a-f]{40}$/)
+ const fd = openSync(big, `r+`)
+ try {
+ writeSync(fd, Buffer.from([1]), 0, 1, LIMIT - 1)
+ } finally {
+ closeSync(fd)
+ }
+ expect(fileHash(big)).toMatch(/^[0-9a-f]{40}$/)
+ expect(fileHash(big)).not.toBe(before)
+ } finally {
+ rmSync(dir, { recursive: true, force: true })
+ }
+ },
+ 60_000,
+ )
+
+ test(`hashes a small file as its text`, () => {
+ const dir = mkdtempSync(join(tmpdir(), `gap-small-`))
+ try {
+ const small = join(dir, `small.txt`)
+ writeFileSync(small, `text\n`)
+ // SHA-1 of `text\n`, the same as a whole read's hash.
+ expect(fileHash(small)).toBe('aa785adca3fcdfe1884ae840e13c6d294a2414e8')
+ } finally {
+ rmSync(dir, { recursive: true, force: true })
+ }
+ })
+})
diff --git a/packages/oracles/tests/gap-inputs-numeric-flag.test.ts b/packages/oracles/tests/gap-inputs-numeric-flag.test.ts
new file mode 100644
index 00000000..84229f5c
--- /dev/null
+++ b/packages/oracles/tests/gap-inputs-numeric-flag.test.ts
@@ -0,0 +1,52 @@
+import { execFileSync } from 'node:child_process'
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { describe, expect, test } from 'vitest'
+
+// A write with a numeric open flag that keeps the bytes it does not overwrite
+// (fs.constants.O_RDWR | O_CREAT, no O_TRUNC) is a read-write open, as the
+// string flag `r+` is: the write must record a read of the prior text before
+// it, or a later read of the file misses the bytes the write kept (CR-21). A
+// flag with O_TRUNC replaces the file, so it records no such read. The flags
+// are the combinations Node's string flags map to (`r+`, `w`), so the test does
+// not depend on how libuv maps a bare numeric flag on each platform (the
+// Windows unit suite failed with EINVAL on one of the bare forms). The watcher
+// is installed in a child process, so this test's own fs calls are not wrapped.
+const script = `
+import { mkdtempSync, writeFileSync, constants } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+const { watchReads } = await import(process.argv[2])
+const seen = []
+watchReads((key, write) => seen.push(write ?? 'read'))
+const dir = mkdtempSync(join(tmpdir(), 'numeric-flag-'))
+const fixture = join(dir, 'fixture.txt')
+writeFileSync(fixture, 'AB')
+seen.length = 0
+writeFileSync(fixture, 'X', { flag: constants.O_RDWR | constants.O_CREAT })
+const keeps = seen.slice()
+seen.length = 0
+writeFileSync(fixture, 'Y', { flag: constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC })
+console.log(JSON.stringify({ keeps, replaces: seen.slice() }))
+`
+
+describe(`a write with a numeric open flag`, () => {
+ test(`reads the prior text only when the flag keeps the bytes it does not write`, () => {
+ const dir = mkdtempSync(join(tmpdir(), `gap-numeric-flag-`))
+ try {
+ const file = join(dir, `run.mjs`)
+ writeFileSync(file, script)
+ const inputs = new URL(`../oracle-gaps/inputs.mjs`, import.meta.url).href
+ const out = execFileSync(process.execPath, [file, inputs], {
+ encoding: `utf8`,
+ })
+ const { keeps, replaces } = JSON.parse(out.trim().split(`\n`).pop()!)
+ expect(keeps[0]).toBe(`append`)
+ expect(keeps.at(-1)).toBe(true)
+ expect(replaces).not.toContain(`append`)
+ } finally {
+ rmSync(dir, { recursive: true, force: true })
+ }
+ })
+})
diff --git a/packages/oracles/tests/oracle-gaps-evidence-store.test.ts b/packages/oracles/tests/oracle-gaps-evidence-store.test.ts
index 8b9afac6..fb3297a7 100644
--- a/packages/oracles/tests/oracle-gaps-evidence-store.test.ts
+++ b/packages/oracles/tests/oracle-gaps-evidence-store.test.ts
@@ -203,8 +203,9 @@ describe.each(backends)(`evidence store (%s) size`, (name, open) => {
// Four versions of half a megabyte, with room for the backend's framing;
// the eight replaced versions must not have stayed in the store.
expect(storeBytes(dir)).toBeLessThan(6 * half)
- })
+ }, 60_000) // 60 s: the Windows runner's disk runs these flushes past the 5 s default
+ // 60 s: the Windows runner's disk runs these flushes past the 5 s default.
test(`the pages of pruned units go back to the file system`, async () => {
const dir = scratch()
let clock = 1_000_000
@@ -230,7 +231,7 @@ describe.each(backends)(`evidence store (%s) size`, (name, open) => {
// The store holds one small unit: the pruned units' pages are not kept
// for later use, they leave the file (review of #314, F2).
expect(storeBytes(dir)).toBeLessThan(4 * page)
- })
+ }, 60_000)
})
describe.each(backends)(`evidence store (%s) pruning`, (name, open) => {